Updated totalizers

This commit is contained in:
2020-09-11 14:08:38 -05:00
parent f4fd410c7e
commit 1bddf77591
21 changed files with 2270 additions and 179 deletions

View File

@@ -0,0 +1,349 @@
"""Define Meshify channel class."""
import time
from pycomm.ab_comm.clx import Driver as ClxDriver
from pycomm.cip.cip_base import CommError, DataError
import struct
#from file_logger import filelogger as log
from flowmonitor import INSTRUMENT, log, lock
instrument = INSTRUMENT
TAG_DATAERROR_SLEEPTIME = 5
def binarray(intval):
"""Split an integer into its bits."""
bin_string = '{0:08b}'.format(intval)
bin_arr = [i for i in bin_string]
bin_arr.reverse()
return bin_arr
def read_tag(addr, tag, plc_type="CLX"):
"""Read a tag from the PLC."""
direct = plc_type == "Micro800"
clx = ClxDriver()
try:
if clx.open(addr, direct_connection=direct):
try:
val = clx.read_tag(tag)
clx.close()
return val
except DataError as err:
clx.close()
time.sleep(TAG_DATAERROR_SLEEPTIME)
log.error("Data Error during readTag({}, {}): {}".format(addr, tag, err))
except CommError:
# err = c.get_status()
log.error("Could not connect during readTag({}, {})".format(addr, tag))
except AttributeError as err:
clx.close()
log.error("AttributeError during readTag({}, {}): \n{}".format(addr, tag, err))
clx.close()
return False
def read_array(addr, tag, start, end, plc_type="CLX"):
"""Read an array from the PLC."""
direct = plc_type == "Micro800"
clx = ClxDriver()
if clx.open(addr, direct_connection=direct):
arr_vals = []
try:
for i in range(start, end):
tag_w_index = tag + "[{}]".format(i)
val = clx.read_tag(tag_w_index)
arr_vals.append(round(val[0], 4))
if arr_vals:
clx.close()
return arr_vals
else:
log.error("No length for {}".format(addr))
clx.close()
return False
except Exception:
log.error("Error during readArray({}, {}, {}, {})".format(addr, tag, start, end))
err = clx.get_status()
clx.close()
log.error(err)
clx.close()
def write_tag(addr, tag, val, plc_type="CLX"):
"""Write a tag value to the PLC."""
direct = plc_type == "Micro800"
clx = ClxDriver()
try:
if clx.open(addr, direct_connection=direct):
try:
initial_val = clx.read_tag(tag)
write_status = clx.write_tag(tag, val, initial_val[1])
clx.close()
return write_status
except DataError as err:
clx_err = clx.get_status()
clx.close()
log.error("--\nDataError during writeTag({}, {}, {}, plc_type={}) -- {}\n{}\n".format(addr, tag, val, plc_type, err, clx_err))
except CommError as err:
clx_err = clx.get_status()
log.error("--\nCommError during write_tag({}, {}, {}, plc_type={})\n{}\n--".format(addr, tag, val, plc_type, err))
clx.close()
return False
def byteSwap32(array):
#array is a list of 2 dec numbers
newVal = ""
for i in array:
i = hex(i).replace('0x', '')
while len(i) < 4:
i = "0" + i
print i
newVal = i + newVal
print newVal
return struct.unpack('!f', newVal.decode('hex'))[0]
class Channel(object):
"""Holds the configuration for a Meshify channel."""
def __init__(self, mesh_name, data_type, chg_threshold, guarantee_sec, map_=False, write_enabled=False):
"""Initialize the channel."""
self.mesh_name = mesh_name
self.data_type = data_type
self.last_value = None
self.value = None
self.last_send_time = 0
self.chg_threshold = chg_threshold
self.guarantee_sec = guarantee_sec
self.map_ = map_
self.write_enabled = write_enabled
def __str__(self):
"""Create a string for the channel."""
return "{}\nvalue: {}, last_send_time: {}".format(self.mesh_name, self.value, self.last_send_time)
def check(self, new_value, force_send=False):
"""Check to see if the new_value needs to be stored."""
send_needed = False
send_reason = ""
if self.data_type == 'BOOL' or self.data_type == 'STRING':
if self.last_send_time == 0:
send_needed = True
send_reason = "no send time"
elif self.value is None:
send_needed = True
send_reason = "no value"
elif self.value != new_value:
if self.map_:
if not self.value == self.map_[new_value]:
send_needed = True
send_reason = "value change"
else:
send_needed = True
send_reason = "value change"
elif (time.time() - self.last_send_time) > self.guarantee_sec:
send_needed = True
send_reason = "guarantee sec"
elif force_send:
send_needed = True
send_reason = "forced"
else:
if self.last_send_time == 0:
send_needed = True
send_reason = "no send time"
elif self.value is None:
send_needed = True
send_reason = "no value"
elif abs(self.value - new_value) > self.chg_threshold:
send_needed = True
send_reason = "change threshold"
elif (time.time() - self.last_send_time) > self.guarantee_sec:
send_needed = True
send_reason = "guarantee sec"
elif force_send:
send_needed = True
send_reason = "forced"
if send_needed:
self.last_value = self.value
if self.map_:
try:
self.value = self.map_[new_value]
except KeyError:
log.error("Cannot find a map value for {} in {} for {}".format(new_value, self.map_, self.mesh_name))
self.value = new_value
else:
self.value = new_value
self.last_send_time = time.time()
log.info("Sending {} for {} - {}".format(self.value, self.mesh_name, send_reason))
return send_needed
def read(self):
"""Read the value."""
pass
def identity(sent):
"""Return exactly what was sent to it."""
return sent
class ModbusChannel(Channel):
"""Modbus channel object."""
def __init__(self, mesh_name, register_number, data_type, chg_threshold, guarantee_sec, channel_size=1, map_=False, write_enabled=False, transform_fn=identity, unit_number=1, scaling=0):
"""Initialize the channel."""
super(ModbusChannel, self).__init__(mesh_name, data_type, chg_threshold, guarantee_sec, map_, write_enabled)
self.mesh_name = mesh_name
self.register_number = register_number
self.channel_size = channel_size
self.data_type = data_type
self.last_value = None
self.value = None
self.last_send_time = 0
self.chg_threshold = chg_threshold
self.guarantee_sec = guarantee_sec
self.map_ = map_
self.write_enabled = write_enabled
self.transform_fn = transform_fn
self.unit_number = unit_number
self.scaling= scaling
def read(self):
"""Return the transformed read value."""
with lock:
print("ATTEMPTING TO READ ON {}".format(self.mesh_name))
if self.data_type == "FLOAT":
try:
read_value = instrument.read_float(self.register_number,4,self.channel_size)
except Exception as e:
log.info(e)
return None
elif self.data_type == "FLOATBS":
try:
read_value = byteSwap32(instrument.read_registers(self.register_number,2, 4))
except Exception as e:
log.info(e)
return None
elif self.data_type == "INTEGER" or self.data_type == "STRING":
try:
read_value = instrument.read_register(self.register_number, self.scaling, 4)
except Exception as e:
log.info(e)
return None
read_value = self.transform_fn(read_value)
return read_value
def write(self, value):
"""Write a value to a register"""
if self.data_type == "FLOAT":
value = float(value)
elif self.data_type == "INTEGER":
value = int(value)
else:
value = str(value)
try:
instrument.write_register(self.register_number,value, self.scaling, 16 if self.channel_size > 1 else 6 )
return True
except Exception as e:
log.info("Failed to write value: {}".format(e))
return False
class PLCChannel(Channel):
"""PLC Channel Object."""
def __init__(self, ip, mesh_name, plc_tag, data_type, chg_threshold, guarantee_sec, map_=False, write_enabled=False, plc_type='CLX'):
"""Initialize the channel."""
super(PLCChannel, self).__init__(mesh_name, data_type, chg_threshold, guarantee_sec, map_, write_enabled)
self.plc_ip = ip
self.mesh_name = mesh_name
self.plc_tag = plc_tag
self.data_type = data_type
self.last_value = None
self.value = None
self.last_send_time = 0
self.chg_threshold = chg_threshold
self.guarantee_sec = guarantee_sec
self.map_ = map_
self.write_enabled = write_enabled
self.plc_type = plc_type
def read(self):
"""Read the value."""
plc_value = None
if self.plc_tag and self.plc_ip:
read_value = read_tag(self.plc_ip, self.plc_tag, plc_type=self.plc_type)
if read_value:
plc_value = read_value[0]
return plc_value
class BoolArrayChannels(Channel):
"""Hold the configuration for a set of boolean array channels."""
def __init__(self, ip, mesh_name, plc_tag, data_type, chg_threshold, guarantee_sec, map_=False, write_enabled=False):
"""Initialize the channel."""
super(BoolArrayChannels, self).__init__(mesh_name, data_type, chg_threshold, guarantee_sec, map_, write_enabled)
self.plc_ip = ip
self.mesh_name = mesh_name
self.plc_tag = plc_tag
self.data_type = data_type
self.last_value = None
self.value = None
self.last_send_time = 0
self.chg_threshold = chg_threshold
self.guarantee_sec = guarantee_sec
self.map_ = map_
self.write_enabled = write_enabled
def compare_values(self, new_val_dict):
"""Compare new values to old values to see if the values need storing."""
send = False
for idx in new_val_dict:
try:
if new_val_dict[idx] != self.last_value[idx]:
send = True
except KeyError:
log.error("Key Error in self.compare_values for index {}".format(idx))
send = True
return send
def read(self, force_send=False):
"""Read the value and check to see if needs to be stored."""
send_needed = False
send_reason = ""
if self.plc_tag:
val = read_tag(self.plc_ip, self.plc_tag)
if val:
bool_arr = binarray(val[0])
new_val = {}
for idx in self.map_:
try:
new_val[self.map_[idx]] = bool_arr[idx]
except KeyError:
log.error("Not able to get value for index {}".format(idx))
if self.last_send_time == 0:
send_needed = True
send_reason = "no send time"
elif self.value is None:
send_needed = True
send_reason = "no value"
elif self.compare_values(new_val):
send_needed = True
send_reason = "value change"
elif (time.time() - self.last_send_time) > self.guarantee_sec:
send_needed = True
send_reason = "guarantee sec"
elif force_send:
send_needed = True
send_reason = "forced"
if send_needed:
self.value = new_val
self.last_value = self.value
self.last_send_time = time.time()
log.info("Sending {} for {} - {}".format(self.value, self.mesh_name, send_reason))
return send_needed

View File

@@ -0,0 +1,12 @@
from Channel import PLCChannel, ModbusChannel
from flowmonitor import PLC_IP_ADDRESS
tags = [
ModbusChannel('gpm_flow', 3873, 'FLOATBS', 10, 3600,channel_size=2, unit_number=2),
ModbusChannel('psi_pressure', 0, 'FLOAT', 100, 3600,channel_size=2, unit_number=2),
ModbusChannel('run_status', 0, 'STRING', 1, 3600,channel_size=2, unit_number=2),
ModbusChannel('gal_total', 2609, 'FLOATBS', 100, 3600,channel_size=2, unit_number=2),
#ModbusChannel('gal_total_thismonth', 2609, 'FLOAT', 100, 3600,channel_size=2, unit_number=flowmeter_unit_number),
#ModbusChannel('gal_total_yesterday', 2609, 'FLOAT', 100, 3600,channel_size=2, unit_number=flowmeter_unit_number),
#ModbusChannel('gal_total_lastmonth', 2609, 'FLOAT', 100, 3600,channel_size=2, unit_number=flowmeter_unit_number)
]

View File

@@ -0,0 +1,14 @@
{
"files": {
"file3": "file_logger.py",
"file2": "Channel.py",
"file1": "flowmonitor.py",
"file6": "persistence.py",
"file5": "utilities.py",
"file4": "Tags.py"
},
"deviceName": "flowmonitor",
"releaseVersion": "21",
"driverFileName": "flowmonitor.py",
"driverId": "0140"
}

View File

@@ -0,0 +1,18 @@
"""Logging setup for flow-monitor"""
import logging
from logging.handlers import RotatingFileHandler
import sys
log_formatter = logging.Formatter('%(asctime)s %(levelname)s %(funcName)s(%(lineno)d) %(message)s')
log_file = './flowmonitor.log'
my_handler = RotatingFileHandler(log_file, mode='a', maxBytes=500*1024,
backupCount=2, encoding=None, delay=0)
my_handler.setFormatter(log_formatter)
my_handler.setLevel(logging.INFO)
filelogger = logging.getLogger('flowmonitor')
filelogger.setLevel(logging.INFO)
filelogger.addHandler(my_handler)
console_out = logging.StreamHandler(sys.stdout)
console_out.setFormatter(log_formatter)
filelogger.addHandler(console_out)

View File

@@ -0,0 +1,522 @@
"""Driver for flow-monitor"""
import threading
import json
import time
import os
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
from datetime import datetime as dt
import minimalmodbusM1
try:
os.system("/usr/sbin/ntpdate pool.ntp.org")
except:
dtz = dt.fromtimestamp(last_measured_timestamp)
os.system('date -s "{}-{}-{} {}:{}:{}"'.format(dtz.year,dtz.month,dtz.day,dtz.hour,dtz.minute,dtz.second))
PLC_IP_ADDRESS = "192.168.1.12"
#from Tags import tags
_ = None
log.info("flow-monitor startup")
# GLOBAL VARIABLES
WAIT_FOR_CONNECTION_SECONDS = 20
IP_CHECK_PERIOD = 60
#CHANNELS = tags
# PERSISTENCE FILE
PERSIST = persistence.load()
if not PERSIST:
PERSIST = {
"pressure_raw_min": 0.0,
"pressure_raw_max": 10.0,
"flow_raw_min": 3.89,
"pressure_psi_min": 0.0,
"gpm_or_bpd": "gpm",
"gpm_ignore_limit": 1.0,
"flow_gpm_max": 100.0,
"pressure_psi_max": 600.0,
"flow_raw_max": 19.54,
"flow_gpm_min": 0.0,
"lowflow": 10.0,
"modbus": False
}
persistence.store(PERSIST, 'persist.json')
try:
PERSIST['modbus']
except:
PERSIST['modbus'] = False
persistence.store(PERSIST, 'persist.json')
TOTALIZER = persistence.load('totalizers.json')
if not TOTALIZER:
TOTALIZER = {
'Todays': 0,
'Yesterdays': 0,
'Current Months': 0,
'Previous Months': 0,
'Monthly Holding': 0,
'Daily Holding': 0,
'Lifetime': 0,
'Day': 0,
'Month': 0,
'Last Report': 0
}
persistence.store(TOTALIZER, 'totalizers.json')
def scale(raw_val, raw_min, raw_max, eu_min, eu_max):
"""Scale a raw value."""
if raw_val < raw_min:
raw_val = raw_min
if raw_val > raw_max:
raw_val = raw_max
slope = (eu_max - eu_min) / (raw_max - raw_min)
intercept = eu_max - (slope * raw_max)
return slope * raw_val + intercept
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 = "21"
self.lock = threading.Lock()
self.force_send = False
self.public_ip_address = ""
self.private_ip_address = ""
self.public_ip_address_last_checked = 0
self.ping_counter = 0
self.finished = threading.Event()
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."""
self.instrument = self.startRS485()
global CHANNELS, INSTRUMENT, lock
INSTRUMENT = self.instrument
lock = self.lock
#from Channel import PLCChannel, ModbusChannel,read_tag, write_tag, TAG_DATAERROR_SLEEPTIME
from Tags import tags
CHANNELS = tags
for i in range(0, WAIT_FOR_CONNECTION_SECONDS):
print("flow-monitor driver will start in {} seconds".format(WAIT_FOR_CONNECTION_SECONDS - i))
time.sleep(1)
log.info("BOOM! Starting flow-monitor driver...")
self._check_ip_address()
self.nodes["flowmonitor_0140"] = self
send_loops = 0
self.sendtodb("setrawmin", PERSIST["flow_raw_min"], 0)
self.sendtodb("setrawmax", PERSIST["flow_raw_max"], 0)
self.sendtodb("setgpmmin", PERSIST["flow_gpm_min"], 0)
self.sendtodb("setgpmmax", PERSIST["flow_gpm_max"], 0)
self.sendtodb("setpressurerawmin", PERSIST["pressure_raw_min"], 0)
self.sendtodb("setpressurerawmax", PERSIST["pressure_raw_max"], 0)
self.sendtodb("setpressurepsimin", PERSIST["pressure_psi_min"], 0)
self.sendtodb("setpressurepsimax", PERSIST["pressure_psi_max"], 0)
gal_totalizer_value = TOTALIZER['Lifetime']
last_measured_timestamp = time.time()
while True:
try:
# Gets a dictionary of the IO states
# {
# 'bat': u'23.10',
# 'ver': u'Mar 16 2016 21:29:31',
# 'dout3': 'Off',
# 'temp': u'40.37',
# 'vin': u'24.6',
# 'pulse': u'0',
# 'dout4': 'Off',
# 'dout1': 'Off',
# 'din2': 'Off',
# 'din1': 'Off',
# 'dout2': 'On',
# 'cloop': u'0.0',
# 'analog4': u'0.0',
# 'analog3': u'0.0',
# 'analog2': u'0.0',
# 'analog1': u'0.0',
# 'relay1': 'Off'
# }
mcu_status = self.mcu.getDict()
except Exception as e:
log.error("Error getting MCU State: {}".format(e))
cloop_val = float(mcu_status['cloop'])
analog1_val = float(mcu_status['analog1'])
din1_val = 1 if mcu_status['din1'] == 'On' else 0 # Check DIGITAL INPUT 1 for run status
scaled_cloop = scale(cloop_val, PERSIST["flow_raw_min"], PERSIST["flow_raw_max"], PERSIST["flow_gpm_min"], PERSIST["flow_gpm_max"])
psi_val = scale(analog1_val, PERSIST["pressure_raw_min"], PERSIST["pressure_raw_max"], PERSIST["pressure_psi_min"], PERSIST["pressure_psi_max"])
if PERSIST["gpm_or_bpd"] == "gpm":
gpm_val = scaled_cloop
bpd_val = (gpm_val / 42.0) * 60.0 * 24.0 # Computes BPD from GPM
else:
bpd_val = scaled_cloop
gpm_val = (((bpd_val * 42.0) / 24.0) / 60.0) # Computes GPM from BPD
if gpm_val < PERSIST["gpm_ignore_limit"]:
gpm_val = 0
bpd_val = 0
#Determine run status
runstatus = "undefined"
if din1_val == 0 and gpm_val == 0:
runstatus = "Stopped" #Stopped
elif din1_val == 0 and gpm_val > 10:
runstatus = "Running" #Assumed running might not have run indication
elif din1_val == 0 and gpm_val > 0:
runstatus = "Running: Low Flow"
elif din1_val == 1 and gpm_val == 0:
runstatus = "Running: No Flow" #no flow warning
elif din1_val == 1 and gpm_val < PERSIST["lowflow"]:
runstatus = "Running: Low Flow" #low flow warning
elif din1_val == 1 and gpm_val >= PERSIST["lowflow"]:
runstatus = "Running" #running normally
now = time.time()
time_diff = now - last_measured_timestamp
if 0 < time_diff < 180:
# Volume flowed since last measuring
gal_flow_delta = (time_diff / 60.0) * gpm_val
# Increment totalizers
gal_totalizer_value += gal_flow_delta
last_measured_timestamp = now
elif time_diff < 0:
#negative time difference means clock got reset or somehow went the wrong way
try:
os.system("/usr/sbin/ntpdate pool.ntp.org")
except:
dtz = dt.fromtimestamp(last_measured_timestamp)
os.system('date -s "{}-{}-{} {}:{}:{}"'.format(dtz.year,dtz.month,dtz.day,dtz.hour,dtz.minute,dtz.second))
now = time.time()
elif time_diff > 180:
last_measured_timestamp = now
if self.force_send:
log.warning("FORCE SEND: TRUE")
for chan in CHANNELS:
if chan.mesh_name == "psi_pressure":
val = psi_val
elif chan.mesh_name == "run_status":
val = runstatus
elif PERSIST["modbus"]:
val = chan.read()
if chan.mesh_name == "gpm_flow":
if val == 0:
runstatus = "Stopped"
elif val > PERSIST["lowflow"]:
runstatus = "Running"
else:
runstatus = "Running: Low Flow"
elif chan.mesh_name == "gpm_flow":
val = gpm_val
else:
val = gal_totalizer_value
if chan.mesh_name == 'gal_total':
self.totalize(val)
elif chan.check(val, self.force_send):
self.sendtodb(chan.mesh_name, chan.value, 0)
if chan.mesh_name == 'gpm_flow':
if val == None:
self.sendtodb('bpd_flow', chan.value,0)
else:
self.sendtodb('bpd_flow', (chan.value / 42.0) * 60 * 24, 0)
#time.sleep(TAG_DATAERROR_SLEEPTIME) # sleep to allow Micro800 to handle ENET requests
if PERSIST["modbus"]:
time.sleep(5)
# print("flow-monitor 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()
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
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.sendtodb('public_ip_address', test_public_ip, 0)
self.public_ip_address = test_public_ip
if not test_private_ip == self.private_ip_address:
self.sendtodb('private_ip_address', test_private_ip, 0)
self.private_ip_address = test_private_ip
def flowmonitor_sync(self, name, value):
"""Sync all data from the driver."""
self.force_send = True
# self.sendtodb("log", "synced", 0)
return True
def flowmonitor_startcmd(self, name, value):
"""Start the well."""
self.mcu.relay1(str(1))
return True
def flowmonitor_stopcmd(self, name, value):
"""Stop the well."""
self.mcu.relay1(str(0))
return True
def flowmonitor_modbus(self, name, value):
if PERSIST["modbus"] == False:
PERSIST["modbus"] = True
else:
PERSIST["modbus"] = False
persistence.store(PERSIST, "persist.json")
return True
def flowmonitor_setrawmin(self, name, value):
"""Set the raw min scaling value."""
try:
PERSIST['flow_raw_min'] = float(value)
self.sendtodb("setrawmin", PERSIST['flow_raw_min'], 0)
persistence.store(PERSIST)
except Exception as e:
log.error("Could not set self.flow_raw_min: {}".format(e))
return(True)
def flowmonitor_setrawmax(self, name, value):
"""Set the raw max scaling value."""
try:
PERSIST['flow_raw_max'] = float(value)
self.sendtodb("setrawmax", PERSIST['flow_raw_max'], 0)
persistence.store(PERSIST)
except Exception as e:
log.error("Could not set self.flow_raw_max: {}".format(e))
return(True)
def flowmonitor_setgpmmin(self, name, value):
"""Set the gpm min scaling value."""
try:
PERSIST['flow_gpm_min'] = float(value)
self.sendtodb("setgpmmin", PERSIST['flow_gpm_min'], 0)
persistence.store(PERSIST)
except Exception as e:
log.error("Could not set self.flow_gpm_min: {}".format(e))
return(True)
def flowmonitor_setgpmmax(self, name, value):
"""Set the gpm max scaling value."""
try:
PERSIST['flow_gpm_max'] = float(value)
self.sendtodb("setgpmmax", PERSIST['flow_gpm_max'], 0)
persistence.store(PERSIST)
except Exception as e:
log.error("Could not set self.flow_gpm_max: {}".format(e))
return(True)
def flowmonitor_setpressurerawmin(self, name, value):
"""Set the pressure raw min scaling value."""
try:
PERSIST['pressure_raw_min'] = float(value)
self.sendtodb("setpressurerawmin", PERSIST['pressure_raw_min'], 0)
persistence.store(PERSIST)
except Exception as e:
log.error("Could not set self.pressure_raw_min: {}".format(e))
return(True)
def flowmonitor_setpressurerawmax(self, name, value):
"""Set the pressure raw max scaling value."""
try:
PERSIST['pressure_raw_max'] = float(value)
self.sendtodb("setpressurerawmax", PERSIST['pressure_raw_max'], 0)
persistence.store(PERSIST)
except Exception as e:
log.error("Could not set self.pressure_raw_max: {}".format(e))
return(True)
def flowmonitor_setpressurepsimin(self, name, value):
"""Set the pressure psi min scaling value."""
try:
PERSIST['pressure_psi_min'] = float(value)
self.sendtodb("setpressurepsimin", PERSIST['pressure_psi_min'], 0)
persistence.store(PERSIST)
except Exception as e:
log.error("Could not set self.pressure_psi_min: {}".format(e))
return(True)
def flowmonitor_setpressurepsimax(self, name, value):
"""Set the pressure psi max scaling value."""
try:
PERSIST['pressure_psi_max'] = float(value)
self.sendtodb("setpressurepsimax", PERSIST['pressure_psi_max'], 0)
persistence.store(PERSIST)
except Exception as e:
log.error("Could not set self.pressure_psi_max: {}".format(e))
return(True)
def flowmonitor_setgpmignorelimit(self, name, value):
"""Set the GPM Ignore Limit."""
try:
PERSIST['gpm_ignore_limit'] = float(value)
self.sendtodb("setgpmignorelimit", PERSIST['gpm_ignore_limit'], 0)
persistence.store(PERSIST)
return True
except Exception as e:
log.error("Error during flowmonitor_setgpmignorelimit: {}".format(e))
return False
def flowmonitor_gpmorbpd(self, name, value):
"""Set the read in value to GPM or BPD"""
try:
PERSIST["gpm_or_bpd"] = str(value)
self.sendtodb("gpmorbpd", PERSIST["gpm_or_bpd"], 0)
return True
except Exception as e:
log.error("Error during flowmonitor_setgpmorbpd: {}".format(e))
return False
def flowmonitor_setlowflow(self, name, value):
"""Set the low flow limit"""
try:
PERSIST["lowflow"] = float(value)
self.sendtodb("setlowflow", PERSIST["lowflow"],0)
persistence.store(PERSIST)
except Exception as e:
log.error("Error during flomonitor_setlowflow: {}".format(e))
return False
return True
def totalize(self, val):
right_now = dt.today()
month = right_now.month
day = right_now.day
#Totalize Today, Yesterday, Month, Last Month
#if the stored day is 0 then it's a fresh run of this should initalize values now
if TOTALIZER['Day'] == 0:
TOTALIZER['Day'] = day
TOTALIZER['Month'] = month
TOTALIZER['Daily Holding'] = val
TOTALIZER['Monthly Holding'] = val
persistence.store(TOTALIZER, 'totalizers.json')
#Communication error during initialization check if lifetime has reported properly and update holdings
if TOTALIZER['Daily Holding'] == None and not(val == None):
TOTALIZER['Daily Holding'] = val
TOTALIZER['Monthly Holding'] = val
try:
if val - TOTALIZER['Daily Holding'] - TOTALIZER['Todays'] > 500 or time.time() - TOTALIZER['Last Report'] > 3600 or self.force_send:
TOTALIZER['Todays'] = val - TOTALIZER['Daily Holding']
TOTALIZER['Current Months'] = val - TOTALIZER['Monthly Holding']
TOTALIZER['Lifetime'] = val
self.sendtodb('gal_total', TOTALIZER['Todays'], 0)
self.sendtodb('bbl_total', TOTALIZER['Todays']/42, 0)
self.sendtodb('gal_total_thismonth', TOTALIZER['Current Months'], 0)
self.sendtodb('bbl_total_thismonth', TOTALIZER['Current Months']/42, 0)
self.sendtodb('gal_total_yesterday', TOTALIZER['Yesterdays'], 0)
self.sendtodb('bbl_total_yesterday', TOTALIZER['Yesterdays']/42, 0)
if self.force_send:
self.sendtodb('gal_total_lastmonth', TOTALIZER['Previous Months'], 0)
self.sendtodb('bbl_total_lastmonth', TOTALIZER['Previous Months']/42, 0)
TOTALIZER['Last Report'] = time.time()
except:
if time.time() - TOTALIZER['Last Report'] > 3600 or self.force_send:
self.sendtodb('gal_total', TOTALIZER['Todays'], 0)
self.sendtodb('bbl_total', TOTALIZER['Todays']/42, 0)
self.sendtodb('gal_total_thismonth', TOTALIZER['Current Months'], 0)
self.sendtodb('bbl_total_thismonth', TOTALIZER['Current Months']/42, 0)
self.sendtodb('gal_total_yesterday', TOTALIZER['Yesterdays'], 0)
self.sendtodb('bbl_total_yesterday', TOTALIZER['Yesterdays']/42, 0)
if self.force_send:
self.sendtodb('gal_total_lastmonth', TOTALIZER['Previous Months'], 0)
self.sendtodb('bbl_total_lastmonth', TOTALIZER['Previous Months']/42, 0)
TOTALIZER['Last Report'] = time.time()
#If the current day doesn't equal the stored day roll the dailies over
if not(day == TOTALIZER['Day']):
#if a comms error use the stored values else use the latested values
if val == None:
TOTALIZER['Yesterdays'] = TOTALIZER['Todays']
TOTALIZER['Todays'] = 0
TOTALIZER['Daily Holding'] = TOTALIZER['Lifetime']
else:
TOTALIZER['Yesterdays'] = val - TOTALIZER['Daily Holding']
TOTALIZER['Todays'] = 0
TOTALIZER['Daily Holding'] = val
TOTALIZER['Lifetime'] = val
TOTALIZER['Day'] = day
self.sendtodb('gal_total', TOTALIZER['Todays'], 0)
self.sendtodb('bbl_total', TOTALIZER['Todays']/42, 0)
self.sendtodb('total_fm_yesterday_gal', TOTALIZER['Yesterdays'], 0)
self.sendtodb('total_fm_yesterday_bbls', TOTALIZER['Yesterdays']/42, 0)
self.sendtodb('lifetime_flow_meter_gal', TOTALIZER['Lifetime'], 0)
self.sendtodb('lifetime_flow_meter_bbls', TOTALIZER['Lifetime']/42, 0)
TOTALIZER['Last Report'] = time.time()
#the day has rolled over if the month also rolls over
if not(month == TOTALIZER['Month']):
#if a comms error use the stored values else use the latested values
if val == None:
TOTALIZER['Previous Months'] = TOTALIZER['Current Months']
TOTALIZER['Current Months'] = 0
TOTALIZER['Monthly Holding'] = TOTALIZER['Lifetime']
else:
TOTALIZER['Previous Months'] = val - TOTALIZER['Monthly Holding']
TOTALIZER['Current Months'] = 0
TOTALIZER['Monthly Holding'] = val
TOTALIZER['Month'] = month
self.sendtodb('gal_total_thismonth', TOTALIZER['Current Months'], 0)
self.sendtodb('bbl_total_thismonth', TOTALIZER['Current Months']/42, 0)
self.sendtodb('gal_total_lastmonth', TOTALIZER['Previous Months'], 0)
self.sendtodb('bbl_total_lastmonth', TOTALIZER['Previous Months']/42, 0)
TOTALIZER['Last Report'] = time.time()
persistence.store(TOTALIZER, 'totalizers.json')
def startRS485(self):
instrument = ""
with self.lock:
#minimalmodbus.BAUDRATE = 9600
#minimalmodbus.STOPBITS = 1
connected = False
while connected == False:
log.info("Attempting to setup RS485")
connected = self.mcu.set485Baud(9600)#switch to configurable
time.sleep(1)
log.info("RS485 SETUP SUCCESSFUL!!!!!")
serial = self.mcu.rs485
instrument = minimalmodbusM1.Instrument(1,serial)
instrument.address = 2 #switch to configurable
return instrument

View File

@@ -0,0 +1,21 @@
"""Data persistance functions."""
# if more advanced persistence is needed, use a sqlite database
import json
def load(filename="persist.json"):
"""Load persisted settings from the specified file."""
try:
with open(filename, 'r') as persist_file:
return json.load(persist_file)
except Exception:
return False
def store(persist_obj, filename="persist.json"):
"""Store the persisting settings into the specified file."""
try:
with open(filename, 'w') as persist_file:
return json.dump(persist_obj, persist_file, indent=4)
except Exception:
return False

View File

@@ -0,0 +1,64 @@
"""Utility functions for the driver."""
import socket
import struct
import urllib
import contextlib
def get_private_ip_address():
"""Find the private IP Address of the host device."""
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
sock.connect(("8.8.8.8", 80))
except Exception as e:
return e
ip_address = sock.getsockname()[0]
sock.close()
return ip_address
def get_public_ip_address():
ip_address = "0.0.0.0"
try:
with contextlib.closing(urllib.urlopen("http://checkip.amazonaws.com")) as url:
ip_address = url.read()
except Exception as e:
print("could not resolve check IP: {}".format(e))
return ip_address
return ip_address[:-1]
def int_to_float16(int_to_convert):
"""Convert integer into float16 representation."""
bin_rep = ('0' * 16 + '{0:b}'.format(int_to_convert))[-16:]
sign = 1.0
if int(bin_rep[0]) == 1:
sign = -1.0
exponent = float(int(bin_rep[1:6], 2))
fraction = float(int(bin_rep[6:17], 2))
if exponent == float(0b00000):
return sign * 2 ** -14 * fraction / (2.0 ** 10.0)
elif exponent == float(0b11111):
if fraction == 0:
return sign * float("inf")
return float("NaN")
frac_part = 1.0 + fraction / (2.0 ** 10.0)
return sign * (2 ** (exponent - 15)) * frac_part
def ints_to_float(int1, int2):
"""Convert 2 registers into a floating point number."""
mypack = struct.pack('>HH', int1, int2)
f_unpacked = struct.unpack('>f', mypack)
print("[{}, {}] >> {}".format(int1, int2, f_unpacked[0]))
return f_unpacked[0]
def degf_to_degc(temp_f):
"""Convert deg F to deg C."""
return (temp_f - 32.0) * (5.0/9.0)
def degc_to_degf(temp_c):
"""Convert deg C to deg F."""
return temp_c * 1.8 + 32.0