169 lines
7.9 KiB
Python
169 lines
7.9 KiB
Python
"""Driver for promagmbs."""
|
|
|
|
import threading
|
|
from device_base import deviceBase
|
|
from utilities import get_public_ip_address
|
|
import time
|
|
import logging
|
|
import sys
|
|
from logging.handlers import RotatingFileHandler
|
|
from Channel import Channel, ModbusChannel, volume_units, totalizer_units
|
|
from datetime import datetime as dt
|
|
from drivers import minimalmodbusM1
|
|
import persistence
|
|
log_formatter = logging.Formatter('%(asctime)s %(levelname)s %(funcName)s(%(lineno)d) %(message)s')
|
|
logFile = './promagmbs.log'
|
|
my_handler = RotatingFileHandler(logFile, mode='a', maxBytes=500*1024, backupCount=2, encoding=None, delay=0)
|
|
my_handler.setFormatter(log_formatter)
|
|
my_handler.setLevel(logging.INFO)
|
|
logger = logging.getLogger('promagmbs')
|
|
logger.setLevel(logging.INFO)
|
|
logger.addHandler(my_handler)
|
|
|
|
console_out = logging.StreamHandler(sys.stdout)
|
|
console_out.setFormatter(log_formatter)
|
|
logger.addHandler(console_out)
|
|
|
|
|
|
# PERSISTENCE FILE
|
|
PERSIST = persistence.load('persist.json')
|
|
if not PERSIST:
|
|
PERSIST = {
|
|
'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')
|
|
_ = None
|
|
|
|
|
|
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.lock = threading.Lock()
|
|
self.mcu = mcu
|
|
self.daemon = True
|
|
self.version = "5"
|
|
self.finished = threading.Event()
|
|
self.forceSend = False
|
|
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):
|
|
# pass
|
|
"""Actually run the driver."""
|
|
global persist
|
|
flowmeter_unit_number = 1
|
|
with self.lock:
|
|
CHANNELS = [
|
|
ModbusChannel('volume_flow', 2008, 'FLOATBS', 500, 3600,channel_size=2, unit_number=flowmeter_unit_number,mcu=self.mcu),
|
|
ModbusChannel('conductivity', 2012, 'FLOATBS', 500, 3600,channel_size=2, unit_number=flowmeter_unit_number,mcu=self.mcu),
|
|
ModbusChannel('totalizer_1', 2609, 'FLOATBS', 100, 3600,channel_size=2, unit_number=flowmeter_unit_number,mcu=self.mcu),
|
|
ModbusChannel('totalizer_2', 2809, 'FLOATBS', 100, 3600,channel_size=2, unit_number=flowmeter_unit_number,mcu=self.mcu),
|
|
ModbusChannel('totalizer_3', 3009, 'FLOATBS', 100, 3600,channel_size=2, unit_number=flowmeter_unit_number,mcu=self.mcu),
|
|
ModbusChannel('volume_flow_units', 2102, 'STRING', 1, 86400,channel_size=1, unit_number=flowmeter_unit_number, transform_fn=volume_units,mcu=self.mcu),
|
|
ModbusChannel('totalizer_1_units', 4603, 'STRING', 1, 86400,channel_size=1, unit_number=flowmeter_unit_number, transform_fn=totalizer_units,mcu=self.mcu),
|
|
ModbusChannel('totalizer_2_units', 4604, 'STRING', 1, 86400,channel_size=1, unit_number=flowmeter_unit_number, transform_fn=totalizer_units,mcu=self.mcu),
|
|
ModbusChannel('totalizer_3_units', 4605, 'STRING', 1, 86400,channel_size=1, unit_number=flowmeter_unit_number, transform_fn=totalizer_units,mcu=self.mcu)
|
|
]
|
|
wait_sec = 20
|
|
for i in range(0, wait_sec):
|
|
logger.info("promagmbs driver will start in {} seconds".format(wait_sec - i))
|
|
time.sleep(1)
|
|
logger.warning("BOOM! Starting promagmbs driver...")
|
|
|
|
public_ip_address = get_public_ip_address()
|
|
self.sendtodbDev(1, 'public_ip_address', public_ip_address, 0, 'promagmbs')
|
|
|
|
send_loops = 0
|
|
watchdog_loops = 0
|
|
watchdog_check_after = 5000
|
|
while True:
|
|
if self.forceSend:
|
|
logger.warning("FORCE SEND: TRUE")
|
|
|
|
for chan in CHANNELS:
|
|
try:
|
|
val = None
|
|
with self.lock:
|
|
for _ in range(3):
|
|
temp = chan.read()
|
|
if not temp == None:
|
|
val = temp
|
|
if val == None:
|
|
logger.info("No modbus data 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.forceSend):
|
|
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'promagmbs')
|
|
self.sendtodbDev(1,chan.mesh_name + "_today", today_total,0,'promagmbs')
|
|
self.sendtodbDev(1,chan.mesh_name + "_yesterday", yesterday_total,0,'promagmbs')
|
|
else:
|
|
if chan.check(val, self.forceSend):
|
|
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'promagmbs')
|
|
|
|
except Exception as e:
|
|
logger.warning("An error occured: {}".format(e))
|
|
time.sleep(3)
|
|
|
|
logger.info("promagmbs driver still alive...")
|
|
if self.forceSend:
|
|
if send_loops > 2:
|
|
logger.warning("Turning off forceSend")
|
|
self.forceSend = False
|
|
send_loops = 0
|
|
else:
|
|
send_loops += 1
|
|
|
|
watchdog_loops += 1
|
|
if (watchdog_loops >= watchdog_check_after):
|
|
test_public_ip = get_public_ip_address()
|
|
if not test_public_ip == public_ip_address:
|
|
self.sendtodbDev(1, 'public_ip_address', test_public_ip, 0, 'promagmbs')
|
|
public_ip_address = test_public_ip
|
|
watchdog_loops = 0
|
|
time.sleep(10)
|
|
|
|
|
|
def promagmbs_sync(self, name, value):
|
|
"""Sync all data from the driver."""
|
|
self.forceSend = True
|
|
self.sendtodb("log", "synced", 0)
|
|
return True
|
|
|
|
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
|