213 lines
8.6 KiB
Python
213 lines
8.6 KiB
Python
"""Driver for PiFlow"""
|
|
import os
|
|
import threading
|
|
import json
|
|
import time
|
|
from random import randint
|
|
from datetime import datetime as dt
|
|
from device_base import deviceBase
|
|
import persistence
|
|
from utilities import get_public_ip_address, get_private_ip_address
|
|
from file_logger import filelogger as log
|
|
|
|
_ = None
|
|
os.system('sudo timedatectl set-timezone America/Chicago')
|
|
log.info("PiFlow startup")
|
|
|
|
# GLOBAL VARIABLES
|
|
WAIT_FOR_CONNECTION_SECONDS = 5
|
|
IP_CHECK_PERIOD = 60
|
|
|
|
|
|
# PERSISTENCE FILE
|
|
PERSIST = persistence.load('persist.json')
|
|
if not PERSIST:
|
|
PERSIST = {'flowmeter': 1, 'drive': 1, 'drive_enabled': False, 'yesterday_totalizer_1': dt.today().day, 'yesterday_totalizer_2': dt.today().day,'yesterday_totalizer_3': dt.today().day,
|
|
'yesterday_total_totalizer_1': 0, 'yesterday_total_midnight_totalizer_1': 0,
|
|
'yesterday_total_totalizer_2': 0, 'yesterday_total_midnight_totalizer_2': 0,
|
|
'yesterday_total_totalizer_3': 0, 'yesterday_total_midnight_totalizer_3': 0}
|
|
persistence.store(PERSIST, 'persist.json')
|
|
|
|
drive_enabled = PERSIST['drive_enabled']
|
|
from Tags import tags
|
|
|
|
CHANNELS = tags
|
|
|
|
class start(threading.Thread, deviceBase):
|
|
"""Start class required by Meshify."""
|
|
|
|
def __init__(self, name=None, number=None, mac=None, Q=None, mcu=None,
|
|
companyId=None, offset=None, mqtt=None, Nodes=None):
|
|
"""Initialize the driver."""
|
|
threading.Thread.__init__(self)
|
|
deviceBase.__init__(self, name=name, number=number, mac=mac, Q=Q,
|
|
mcu=mcu, companyId=companyId, offset=offset,
|
|
mqtt=mqtt, Nodes=Nodes)
|
|
|
|
self.daemon = True
|
|
self.version = "19"
|
|
self.finished = threading.Event()
|
|
self.force_send = False
|
|
self.public_ip_address = ""
|
|
self.private_ip_address = ""
|
|
self.public_ip_address_last_checked = 0
|
|
threading.Thread.start(self)
|
|
|
|
# this is a required function for all drivers, its goal is to upload some piece of data
|
|
# about your device so it can be seen on the web
|
|
def register(self):
|
|
"""Register the driver."""
|
|
# self.sendtodb("log", "BOOM! Booted.", 0)
|
|
pass
|
|
|
|
def run(self):
|
|
"""Actually run the driver."""
|
|
for i in range(0, WAIT_FOR_CONNECTION_SECONDS):
|
|
print("PiFlow driver will start in {} seconds".format(WAIT_FOR_CONNECTION_SECONDS - i))
|
|
time.sleep(1)
|
|
log.info("BOOM! Starting PiFlow driver...")
|
|
|
|
#self._check_watchdog()
|
|
self._check_ip_address()
|
|
|
|
self.nodes["PiFlow_0199"] = self
|
|
|
|
send_loops = 0
|
|
|
|
while True:
|
|
now = time.time()
|
|
if self.force_send:
|
|
log.warning("FORCE SEND: TRUE")
|
|
|
|
for chan in CHANNELS:
|
|
try:
|
|
for x in range(3):
|
|
val = chan.read()
|
|
if not val == None:
|
|
break
|
|
if val == None:
|
|
log.info("No modbus read sending previous value")
|
|
val = chan.value
|
|
if chan.mesh_name in ['totalizer_1','totalizer_2','totalizer_3']:
|
|
right_now = dt.today()
|
|
today_total, yesterday_total = self.totalize(val, PERSIST['yesterday_'+chan.mesh_name], right_now.day, right_now.hour, right_now.minute, PERSIST['yesterday_total_midnight_'+chan.mesh_name], PERSIST['yesterday_total_'+chan.mesh_name], chan.mesh_name)
|
|
if chan.check(val, self.force_send):
|
|
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'PiFlow')
|
|
self.sendtodbDev(1,"today_"+chan.mesh_name, today_total,0,'PiFlow')
|
|
self.sendtodbDev(1,"yesterday_"+chan.mesh_name, yesterday_total,0,'PiFlow')
|
|
else:
|
|
if chan.check(val, self.force_send):
|
|
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'PiFlow')
|
|
|
|
except Exception as e:
|
|
log.warning("An error occured: {}".format(e))
|
|
time.sleep(3)
|
|
|
|
|
|
# print("PiFlow driver still alive...")
|
|
if self.force_send:
|
|
if send_loops > 2:
|
|
log.warning("Turning off force_send")
|
|
self.force_send = False
|
|
send_loops = 0
|
|
else:
|
|
send_loops += 1
|
|
|
|
|
|
if (now - self.public_ip_address_last_checked) > IP_CHECK_PERIOD:
|
|
self._check_ip_address()
|
|
time.sleep(10)
|
|
|
|
def _check_ip_address(self):
|
|
"""Check the public IP address and send to Meshify if changed."""
|
|
self.public_ip_address_last_checked = time.time()
|
|
test_public_ip = get_public_ip_address()
|
|
test_public_ip = test_public_ip[:-1]
|
|
test_private_ip = get_private_ip_address()
|
|
if not test_public_ip == self.public_ip_address and not test_public_ip == "0.0.0.0":
|
|
self.sendtodbDev(1, 'public_ip_address', test_public_ip, 0, 'PiFlow')
|
|
self.public_ip_address = test_public_ip
|
|
if not test_private_ip == self.private_ip_address:
|
|
self.sendtodbDev(1, 'private_ip_address', test_private_ip, 0, 'PiFlow')
|
|
self.private_ip_address = test_private_ip
|
|
|
|
def PiFlow_sync(self, name, value):
|
|
"""Sync all data from the driver."""
|
|
self.force_send = True
|
|
# self.sendtodb("log", "synced", 0)
|
|
return True
|
|
|
|
def PiFlow_flowmeternumber(self, name, unit_number):
|
|
"""Change the unit number for the PiFlow flow meter"""
|
|
unit_number = int(unit_number)
|
|
if drive_enabled:
|
|
for chan in CHANNELS[0:8]:
|
|
chan.unit_number = unit_number
|
|
PERSIST['flowmeter'] = unit_number
|
|
persistence.store(PERSIST, 'persist.json')
|
|
return True
|
|
else:
|
|
for chan in CHANNELS:
|
|
chan.unit_number = unit_number
|
|
PERSIST['flowmeter'] = unit_number
|
|
persistence.store(PERSIST, 'persist.json')
|
|
self.sendtodbDev(1, 'flowmeternumber', unit_number, 0,'PiFlow')
|
|
return True
|
|
return False
|
|
|
|
def PiFlow_drivenumber(self, name, unit_number):
|
|
"""Change the unit number for the PiFlow drive"""
|
|
unit_number = int(unit_number)
|
|
for chan in CHANNELS[8:]:
|
|
chan.unit_number = unit_number
|
|
|
|
PERSIST['drive'] = unit_number
|
|
persistence.store(PERSIST, 'persist.json')
|
|
self.sendtodbDev(1, 'drivenumber', unit_number, 0,'PiFlow')
|
|
return True
|
|
|
|
def PiFlow_reboot(self, name, value):
|
|
os.system('reboot')
|
|
return True
|
|
|
|
def PiFlow_drive_enabled(self, name, value):
|
|
value = int(value)
|
|
if value == 1:
|
|
PERSIST['drive_enabled'] = True
|
|
else:
|
|
PERSIST['drive_enabled'] = False
|
|
|
|
persistence.store(PERSIST, 'persist.json')
|
|
self.sendtodbDev(1, 'drive_enabled', value, 0,'PiFlow')
|
|
return True
|
|
|
|
def PiFlow_write(self, name, value):
|
|
"""Write a value to the device via modbus"""
|
|
new_val = json.loads(str(value).replace("'", '"'))
|
|
addr_n = int(new_val['addr'])
|
|
reg_n = int(new_val['reg'])
|
|
val_n = new_val['val']
|
|
for chan in CHANNELS:
|
|
if chan.unit_number == addr_n and chan.register_number == reg_n:
|
|
write_res = chan.write(val_n)
|
|
|
|
log.info("Result of PiFlow_write(self, {}, {}) = {}".format(name, value, write_res))
|
|
return write_res
|
|
|
|
def totalize(self,val, yesterday, day, hour, minute, yesterday_total_midnight, yesterday_total,channel):
|
|
if (yesterday_total == 0 and yesterday_total_midnight == 0) or (yesterday_total == None or yesterday_total_midnight == None):
|
|
yesterday_total_midnight = val
|
|
PERSIST['yesterday_total_midnight_'+channel] = yesterday_total_midnight
|
|
persistence.store(PERSIST, 'persist.json')
|
|
today_total = val - yesterday_total_midnight
|
|
if hour == 0 and minute == 0 and not(day == yesterday):
|
|
yesterday_total = today_total
|
|
yesterday_total_midnight = val
|
|
today_total = val - yesterday_total_midnight
|
|
yesterday = day
|
|
PERSIST['yesterday_'+channel] = yesterday
|
|
PERSIST['yesterday_total_'+channel] = yesterday_total
|
|
PERSIST['yesterday_total_midnight_'+channel] = yesterday_total_midnight
|
|
persistence.store(PERSIST,'persist.json')
|
|
|
|
return today_total,yesterday_total |