Files
Pond-Level-Sensor/python_driver/pondlevel.py
2018-07-03 16:51:51 -05:00

365 lines
14 KiB
Python

"""Driver for connecting Pond Level to Meshify."""
import threading
from device_base import deviceBase
import time
import json
import persistence
from utilities import get_public_ip_address
from file_logger import filelogger as log
_ = None
pond_level = {
'value': 15.0,
'timestamp': 0
}
psi_reading = {
'value': 0.0,
'timestamp': 0
}
send_delta = 2.0
send_time = 300
temp_pl = pond_level['value']
temp_psi = psi_reading['value']
scaling_persist = persistence.load(filename="scaling_persist.json")
strapping_persist = persistence.load(filename="strapping_persist.json")
def scale_to_eu(inp_measurement, raw_max, raw_min, eu_max, eu_min):
"""Scale the inp_measurement to engineering units."""
m = (eu_max - eu_min) / (raw_max - raw_min)
b = eu_max - raw_max * m
scaled = inp_measurement * m + b
return scaled
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 = "4"
self.finished = threading.Event()
self.forceSend = False
threading.Thread.start(self)
self.public_ip_address = ""
self.public_ip_address_last_checked = 0
self.PL_RAWMAX = 20.0
self.PL_RAWMIN = 4.0
self.PL_EUMAX = 23.068
self.PL_EUMIN = 0.0
self.PSI_RAWMAX = 10.0
self.PSI_RAWMIN = 0.0
self.PSI_EUMAX = 600.0
self.PSI_EUMIN = 0.0
# Strapping table format
# {
# height: volume,
# height: volume,
# height: volume,
# etc...
# }
self.strapping_table = {}
# 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)
def run(self):
"""Actually run the driver."""
global pond_level, temp_pl, psi_reading, temp_psi, send_delta, send_time
try:
self.PL_RAWMAX = scaling_persist['raw_max']
self.PL_RAWMIN = scaling_persist['raw_min']
self.PL_EUMAX = scaling_persist['eu_max']
self.PL_EUMIN = scaling_persist['eu_min']
except KeyError:
log.warning("No persistence data for pond level scaling parameters.")
except TypeError:
log.warning("No persistence data for pond level scaling parameters.")
try:
self.PSI_RAWMAX = scaling_persist['psi_raw_max']
self.PSI_RAWMIN = scaling_persist['psi_raw_min']
self.PSI_EUMAX = scaling_persist['psi_eu_max']
self.PSI_EUMIN = scaling_persist['psi_eu_min']
except KeyError:
log.warning("No persistence data for pressure scaling parameters.")
except TypeError:
log.warning("No persistence data for pressure scaling parameters.")
try:
if len(strapping_persist.keys()) > 0:
for k in strapping_persist.keys():
self.strapping_table[float(k)] = strapping_persist[k]
log.info("Using stored strapping table:\n{}".format(self.strapping_table))
else:
log.warning("No stored strapping table found.")
except Exception as e:
log.warning("No stored strapping table. Got Error: {}".format(e))
wait_sec = 30
for i in range(0, wait_sec):
log.info("pondlevel driver will start in {} seconds".format(wait_sec - i))
time.sleep(1)
log.info("BOOM! Starting pondlevel driver...")
# db.setup_calibration_table(drop_first=False)
self.send_calibration_points()
self._check_ip_address()
self.sendtodb("setrawmax", self.PL_RAWMAX, 0)
self.sendtodb("setrawmin", self.PL_RAWMIN, 0)
self.sendtodb("seteumax", self.PL_EUMAX, 0)
self.sendtodb("seteumin", self.PL_EUMIN, 0)
self.sendtodb("setpsirawmax", self.PSI_RAWMAX, 0)
self.sendtodb("setpsirawmin", self.PSI_RAWMIN, 0)
self.sendtodb("setpsieumax", self.PSI_EUMAX, 0)
self.sendtodb("setpsieumin", self.PSI_EUMIN, 0)
send_loops = 0
ip_check_after = 60
while True:
now = time.time()
pl_send_now = False
psi_send_now = False
if self.forceSend:
log.warning("FORCE SEND: TRUE")
pl_send_now = True
psi_send_now = True
try:
mcu_status = self.mcu.getDict() # Gets a dictionary of the IO states
cloop_val = float(mcu_status['cloop'])
analog1_val = float(mcu_status['analog1'])
temp_pl = scale_to_eu(cloop_val, self.PL_RAWMAX, self.PL_RAWMIN, self.PL_EUMAX, self.PL_EUMIN)
temp_psi = scale_to_eu(analog1_val, self.PSI_RAWMAX, self.PSI_RAWMIN, self.PSI_EUMAX, self.PSI_EUMIN)
except AttributeError as err:
log.error("Could not connect to MCU object, this device might not have an MCU: {}".format(err))
except KeyError as err:
log.error("Connected to MCU, but {} does not exist.".format(err))
if (now - pond_level['timestamp']) > send_time:
log.info("Sending pond level {} due to time limit".format(temp_pl))
pl_send_now = True
# Check if pressure needs to be sent
if abs(temp_psi - psi_reading['value']) > send_delta:
log.info("Sending pressure psi {} due to value change".format(temp_psi))
psi_send_now = True
if (now - psi_reading['timestamp']) > send_time:
log.info("Sending pressure psi {} due to time limit".format(temp_psi))
psi_send_now = True
if pl_send_now:
self.sendtodb('pond_level', temp_pl, 0)
pond_volume = 0.0
try:
pond_volume = self.get_volume_for_height(temp_pl)
except Exception:
pass
self.sendtodb('pond_volume', pond_volume, 0)
pond_level['value'] = temp_pl
pond_level['timestamp'] = now
if psi_send_now:
self.sendtodb('pressure_psi', temp_psi, 0)
psi_reading['value'] = temp_psi
psi_reading['timestamp'] = now
if (now - self.public_ip_address_last_checked) > ip_check_after or self.forceSend:
self._check_ip_address()
log.info("pondlevel driver still alive...")
if self.forceSend:
if send_loops > 2:
log.info("Turning off forceSend")
self.forceSend = False
send_loops = 0
else:
send_loops += 1
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()
if not test_public_ip == self.public_ip_address:
self.sendtodb('public_ip_address', test_public_ip, 0)
self.public_ip_address = test_public_ip
def send_calibration_points(self):
"""Send calibration data from database to Meshify."""
strapping_table_list = []
height_list = self.strapping_table.keys()
height_list.sort()
for height in height_list:
strapping_table_list.append([height, self.strapping_table[height]])
strapping_table_string = json.dumps(strapping_table_list)
self.sendtodb('calibration_data', strapping_table_string, 0)
def pondlevel_sync(self, name, value):
"""Sync all data from the driver."""
self.forceSend = True
self.sendtodb("log", "synced", 0)
return True
def pondlevel_addcalibrationpoint(self, name, value):
"""Add a JSON calibration point to the database."""
try:
new_point = json.loads(value.replace("'", '"'))
log.info("Trying to add Height: {}, volume: {}".format(new_point['height'], new_point['volume']))
self.strapping_table[float(new_point['height'])] = float(new_point['volume'])
self.store_strapping_table()
# db.insert_calibration_data(new_point['height'], new_point['volume'])
self.send_calibration_points()
return True
except Exception as e:
log.error("EXCEPTION: {}".format(e))
def pondlevel_deletecalibrationpoint(self, name, value):
"""Delete a calibration point from the database."""
try:
del self.strapping_table[float(value)]
self.store_strapping_table()
# db.delete_calibration_data(int(value))
self.send_calibration_points()
return True
except Exception as e:
log.error("Error deleting calibration point: {}".format(e))
return(e)
def store_scaling_data(self):
"""Store scaling data in the persist file."""
scale_obj = {
'raw_max': self.PL_RAWMAX,
'raw_min': self.PL_RAWMIN,
'eu_max': self.PL_EUMAX,
'eu_min': self.PL_EUMIN,
'psi_raw_max': self.PSI_RAWMAX,
'psi_raw_min': self.PSI_RAWMIN,
'psi_eu_max': self.PSI_EUMAX,
'psi_eu_min': self.PSI_EUMIN
}
persistence.store(scale_obj, filename="scaling_persist.json")
def store_strapping_table(self):
"""Store strapping table in the persist file."""
persistence.store(self.strapping_table, filename="strapping_persist.json")
def get_volume_for_height(self, height):
"""Interpret a volume for a given height."""
try:
height = float(height)
strapping_table_list = []
height_list = self.strapping_table.keys()
height_list.sort()
for height_i in height_list:
strapping_table_list.append([float(height_i), float(self.strapping_table[height_i])])
# print("Strapping Table Data\n===")
# print(strapping_table_list)
cal_min_height = strapping_table_list[0][0]
cal_max_height = strapping_table_list[-1][0]
lower_cal = [0.0, 0.0]
upper_cal = [0.0, 0.0]
if (height <= cal_max_height and height >= cal_min_height):
for i in range(0, len(strapping_table_list) - 1):
if (height >= strapping_table_list[i][0] and height <= strapping_table_list[i+1][0]):
lower_cal = strapping_table_list[i]
upper_cal = strapping_table_list[i+1]
elif height > cal_max_height:
lower_cal = strapping_table_list[-2]
upper_cal = strapping_table_list[-1]
elif height < cal_min_height:
lower_cal = strapping_table_list[0]
upper_cal = strapping_table_list[1]
line_m = (float(upper_cal[1]) - float(lower_cal[1])) / (float(upper_cal[0]) - float(lower_cal[0]))
line_b = float(upper_cal[1]) - line_m * float(upper_cal[0])
return line_m * height + line_b
except Exception as e:
log.error("Error in get_volume_for_height: {}".format(e))
return 0.0
def pondlevel_setrawmin(self, name, value):
"""Set the raw min scaling value."""
self.PL_RAWMIN = float(value)
self.sendtodb("setrawmin", self.PL_RAWMIN, 0)
self.store_scaling_data()
return(True)
def pondlevel_setrawmax(self, name, value):
"""Set the raw max scaling value."""
self.PL_RAWMAX = float(value)
self.sendtodb("setrawmax", self.PL_RAWMAX, 0)
self.store_scaling_data()
return(True)
def pondlevel_seteumin(self, name, value):
"""Set the gpm min scaling value."""
self.PL_EUMIN = float(value)
self.sendtodb("seteumin", self.PL_EUMIN, 0)
self.store_scaling_data()
return(True)
def pondlevel_seteumax(self, name, value):
"""Set the gpm max scaling value."""
self.PL_EUMAX = float(value)
self.sendtodb("seteumax", self.PL_EUMAX, 0)
self.store_scaling_data()
return(True)
def pondlevel_setpsirawmin(self, name, value):
"""Set the raw min pressure scaling value."""
self.PSI_RAWMIN = float(value)
self.sendtodb("setpsirawmin", self.PSI_RAWMIN, 0)
self.store_scaling_data()
return(True)
def pondlevel_setpsirawmax(self, name, value):
"""Set the raw max pressure scaling value."""
self.PSI_RAWMAX = float(value)
self.sendtodb("setpsirawmax", self.PSI_RAWMAX, 0)
self.store_scaling_data()
return(True)
def pondlevel_setpsieumin(self, name, value):
"""Set the psi min pressure scaling value."""
self.PSI_EUMIN = float(value)
self.sendtodb("setpsieumin", self.PSI_EUMIN, 0)
self.store_scaling_data()
return(True)
def pondlevel_setpsieumax(self, name, value):
"""Set the psi max pressure scaling value."""
self.PSI_EUMAX = float(value)
self.sendtodb("setpsieumax", self.PSI_EUMAX, 0)
self.store_scaling_data()
return(True)