Added report generator for thingsboard

This commit is contained in:
Nico Melone
2024-07-31 14:02:59 -05:00
parent c45c5a926d
commit 6db3e90fc1
82 changed files with 17951 additions and 27 deletions

View File

@@ -0,0 +1,300 @@
"""Define Meshify channel class."""
import time
import urllib
from pycomm.ab_comm.clx import Driver as ClxDriver
from pycomm.cip.cip_base import CommError, DataError
from file_logger import filelogger as log
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()
#clx.close()
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
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 new_value is None:
new_value = self.value
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 (time.time() - self.last_send_time) > self.guarantee_sec:
send_needed = True
send_reason = "guarantee sec"
elif self.value != new_value:
if self.map_:
if (not self.value == self.map_[new_value]) or force_send:
send_needed = True
send_reason = "value change"
else:
send_needed = True
send_reason = "value change"
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):
"""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
def read(self, mbsvalue):
"""Return the transformed read value."""
return self.transform_fn(mbsvalue)
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,33 @@
from Channel import PLCChannel, ModbusChannel
from plcfreshwater import PLC_IP_ADDRESS
tags = [
PLCChannel(PLC_IP_ADDRESS, "scaled_flow_meter","Scaled_Flow_Meter","REAL", 10, 3600, plc_type="Micro800"),
PLCChannel(PLC_IP_ADDRESS, "scaled_pressure_transducer","Scaled_Pressure_Transducer","REAL", 3, 3600, plc_type="Micro800"),
PLCChannel(PLC_IP_ADDRESS, "raw_hand_input","Raw_Hand_Input","BOOL", 1, 7200, plc_type="Micro800", map_={0: "Off", 1: "On", None: "N/A"}),
PLCChannel(PLC_IP_ADDRESS, "raw_auto_input","Raw_Auto_Input","BOOL", 1, 7200, plc_type="Micro800", map_={0: "Off", 1: "On", None: "N/A"}),
PLCChannel(PLC_IP_ADDRESS, "raw_run_status","Raw_Run_Status","BOOL", 1, 3600, plc_type="Micro800", map_={0: "Stopped", 1: "Running", None: "N/A"}),
PLCChannel(PLC_IP_ADDRESS, "raw_local_start","Raw_Local_Start","BOOL", 1, 3600, plc_type="Micro800"),
PLCChannel(PLC_IP_ADDRESS, "lifetime_flow_meter_gal","Lifetime_Flow_Meter_Gal","REAL", 1000, 3600, plc_type="Micro800"),
PLCChannel(PLC_IP_ADDRESS, "spt_flow_meter_unit","SPT_Flow_Meter_Unit","BOOL", 0, 3600, plc_type="Micro800"),
PLCChannel(PLC_IP_ADDRESS, "raw_overload_status", "Raw_Overload_Status", "BOOL", 0, 3600, plc_type="Micro800", map_={0: "Good", 1: "Down on Overload Tripped", None: "N/A"})
]
tags_totalizer = [
PLCChannel(PLC_IP_ADDRESS, "scaled_flow_meter","Scaled_Flow_Meter","REAL", 10, 3600, plc_type="Micro800"),
PLCChannel(PLC_IP_ADDRESS, "scaled_pressure_transducer","Scaled_Pressure_Transducer","REAL", 3, 3600, plc_type="Micro800"),
PLCChannel(PLC_IP_ADDRESS, "raw_hand_input","Raw_Hand_Input","BOOL", 1, 7200, plc_type="Micro800", map_={0: "Off", 1: "On", None: "N/A"}),
PLCChannel(PLC_IP_ADDRESS, "raw_auto_input","Raw_Auto_Input","BOOL", 1, 7200, plc_type="Micro800", map_={0: "Off", 1: "On", None: "N/A"}),
PLCChannel(PLC_IP_ADDRESS, "raw_run_status","Raw_Run_Status","BOOL", 1, 3600, plc_type="Micro800", map_={0: "Stopped", 1: "Running", None: "N/A"}),
PLCChannel(PLC_IP_ADDRESS, "raw_local_start","Raw_Local_Start","BOOL", 1, 3600, plc_type="Micro800"),
PLCChannel(PLC_IP_ADDRESS, "total_fm_yesterday_gal","Totalizer_FM_Yesterday_Total_Gal","REAL", 1, 3600, plc_type="Micro800"),
PLCChannel(PLC_IP_ADDRESS, "total_fm_day_gal","Totalizer_FM_Current_Day_Total_Gal","REAL", 1, 3600, plc_type="Micro800"),
PLCChannel(PLC_IP_ADDRESS, "total_fm_last_month_gal","Totalizer_FM_Last_Month_Gal","REAL", 1, 3600, plc_type="Micro800"),
PLCChannel(PLC_IP_ADDRESS, "total_fm_month_gal","Totalizer_FM_Current_Month_Gal","REAL", 1, 3600, plc_type="Micro800"),
PLCChannel(PLC_IP_ADDRESS, "total_fm_yesterday_bbls","Totalizer_FM_Yesterday_Total_BBLs","REAL", 1, 3600, plc_type="Micro800"),
PLCChannel(PLC_IP_ADDRESS, "total_fm_day_bbls","Totalizer_FM_Current_Day_Total_BBLs","REAL", 1, 3600, plc_type="Micro800"),
PLCChannel(PLC_IP_ADDRESS, "total_fm_last_month_bbls","Totalizer_FM_Last_Month_BBLs","REAL", 1, 3600, plc_type="Micro800"),
PLCChannel(PLC_IP_ADDRESS, "total_fm_month_bbls","Totalizer_FM_Current_Month_BBLs","REAL", 1, 3600, plc_type="Micro800"),
PLCChannel(PLC_IP_ADDRESS, "spt_flow_meter_unit","SPT_Flow_Meter_Unit","BOOL", 0, 3600, plc_type="Micro800"),
PLCChannel(PLC_IP_ADDRESS, "raw_overload_status", "Raw_Overload_Status", "BOOL", 0, 3600, plc_type="Micro800", map_={0: "Good", 1: "Down on Overload Tripped", None: "N/A"})
]

View File

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

View File

@@ -0,0 +1,360 @@
import types
import traceback
import binascii
import threading
import time
import thread
import os
import struct
import sys
import textwrap
import Queue
import json
class deviceBase():
def __init__(self, name=None, number=None, mac=None, Q=None, mcu=None, companyId=None, offset=None, mqtt=None, Nodes=None):
self.offset = offset
self.company = companyId
self.name = name
self.number = number
self.q = Q
self.deviceName = name + '_[' + mac + ':' + number[0:2] + ':' + number[2:] + ']!'
self.chName = "M1" + '_[' + mac + ':'
self.chName2 = '_[' + mac + ':'
print 'device name is:'
print self.deviceName
mac2 = mac.replace(":", "")
self.mac = mac2.upper()
self.address = 1
self.debug = True
self.mcu = mcu
self.firstRun = True
self.mqtt = mqtt
self.nodes = Nodes
#local dictionary of derived nodes ex: localNodes[tank_0199] = self
self.localNodes = {}
os.system("chmod 777 /root/reboot")
os.system("echo nameserver 8.8.8.8 > /etc/resolv.conf")
#Queue for imcoming sets
self.loraQ = Queue.Queue()
self.knownIDs = []
thread.start_new_thread(self.getSetsThread, ())
def getSetsThread(self):
while True:
try:
item = self.loraQ.get(block=True, timeout=600)
try:
print "here is the item from the sets q"
print item
if len(item) == 2:
techname = str(json.loads(item[1])[0]['payload']['name'].split(".")[0])
channel = str(json.loads(item[1])[0]['payload']['name'].split(".")[1])
name = techname.split("_")[0]
id = techname.split("_")[1][1:-2].replace(":","").upper()
value = json.loads(item[1])[0]['payload']['value']
msgId = json.loads(item[1])[0]['msgId']
print channel, value, id, name, msgId
success = self.specificSets(channel, value, id, name)
if success == True:
print "SUCCESS ON SET"
if int(msgId) == 0:
return
lc = self.getTime()
value = str(self.mac) + " Success Setting: " + channel + " To: " + value
msg = """[ { "value":"%s", "timestamp":"%s", "msgId":"%s" } ]""" % (value, str(lc), msgId)
print value
print msg
topic = "meshify/responses/" + str(msgId)
print topic
self.q.put([topic, str(msg), 2])
else:
lc = self.getTime()
if success == False:
reason = "(Internal Gateway/Device Error)"
else:
reason = success
value = str(self.mac) + " Failed Setting: " + channel + " To: " + value + " " + reason
msg = """[ { "value":"%s", "timestamp":"%s", "msgId":"%s" } ]""" % (value, str(lc), msgId)
topic = "meshify/responses/" + msgId
self.q.put([topic, str(msg), 2])
except:
if int(msgId) == 0:
return
lc = self.getTime()
value = str(self.mac) + " Failed Setting: " + channel + " To: " + value + " (No Callback Found)"
msg = """[ { "value":"%s", "timestamp":"%s", "msgId":"%s" } ]""" % (value, str(lc), msgId)
topic = "meshify/responses/" + msgId
self.q.put([topic, str(msg), 2])
print 'no Set callback found for channel: ' + funcName
except:
print "sets queue timeout, restarting..."
def sendtodbDevLora(self, id, channel, value, timestamp, deviceName):
mac = self.mac
if deviceName == "mainMeshify":
zigmac = "_[01:00:00:00:00:" + id[0:2] + ":" + id[2:4] + ":" + id[4:6] + "]!"
else:
zigmac = "_[00:00:00:00:00:" + id[0:2] + ":" + id[2:4] + ":" + id[4:6] + "]!"
dname = deviceName + zigmac
#define dname, make id into techname and mac
if id not in self.knownIDs:
self.knownIDs.append(id)
self.mcu.xbees[dname] = self.loraQ
#meshify/db/330/C493000354FB/ilora/c493000354fb2A6E/a1-v
#[ { "value":"0.5635", "timestamp":"1486039316" } ]
if int(timestamp) == 0:
timestamp = self.getTime()
topic = 'meshify/db/%s/%s/%s/%s' % (self.company, mac, dname, channel)
print topic
msg = """[ { "value":"%s", "timestamp":"%s" } ]""" % (str(value), str(timestamp))
print msg
self.q.put([topic, msg, 0])
def sendtodbLocLora(self, id, channel, value, timestamp, deviceName):
mac = id
while len(mac) < 12:
mac = "0" + mac
if deviceName == "mainMeshify":
zigmac = "_[01:00:00:00:00:" + id[0:2] + ":" + id[2:4] + ":" + id[4:6] + "]!"
else:
zigmac = "_[00:00:00:00:00:" + id[0:2] + ":" + id[2:4] + ":" + id[4:6] + "]!"
dname = deviceName + zigmac
#define dname, make id into techname and mac
if id not in self.knownIDs:
self.knownIDs.append(id)
topic = str(("meshify/sets/" + str(self.company) + "/" + mac + "/#"))
self.mqtt.subscribe(topic, 0)
topic = str(("meshify/sets/" + "1" + "/" + mac + "/#"))
self.mqtt.subscribe(topic, 0)
self.mcu.xbees[dname] = self.loraQ
#meshify/db/330/C493000354FB/ilora/c493000354fb2A6E/a1-v
#[ { "value":"0.5635", "timestamp":"1486039316" } ]
if int(timestamp) == 0:
timestamp = self.getTime()
topic = 'meshify/db/%s/%s/%s/%s' % (self.company, mac, dname, channel)
print topic
msg = """[ { "value":"%s", "timestamp":"%s" } ]""" % (str(value), str(timestamp))
print msg
self.q.put([topic, msg, 0])
def sendtodbLocLoraCom(self, id, channel, value, timestamp, deviceName):
mac = "1" + id
while len(mac) < 12:
mac = "0" + mac
if deviceName == "mainMeshify":
zigmac = "_[01:00:00:00:00:" + id[0:2] + ":" + id[2:4] + ":" + id[4:6] + "]!"
else:
zigmac = "_[00:00:00:00:01:" + id[0:2] + ":" + id[2:4] + ":" + id[4:6] + "]!"
dname = deviceName + zigmac
#define dname, make id into techname and mac
if id not in self.knownIDs:
self.knownIDs.append(id)
topic = str(("meshify/sets/" + str(self.company) + "/" + mac + "/#"))
self.mqtt.subscribe(topic, 0)
topic = str(("meshify/sets/" + "1" + "/" + mac + "/#"))
self.mqtt.subscribe(topic, 0)
self.mcu.xbees[dname] = self.loraQ
#meshify/db/330/C493000354FB/ilora/c493000354fb2A6E/a1-v
#[ { "value":"0.5635", "timestamp":"1486039316" } ]
if int(timestamp) == 0:
timestamp = self.getTime()
topic = 'meshify/db/%s/%s/%s/%s' % (self.company, mac, dname, channel)
print topic
msg = """[ { "value":"%s", "timestamp":"%s" } ]""" % (str(value), str(timestamp))
print msg
self.q.put([topic, msg, 0])
def sendtodbLoc(self, ch, channel, value, timestamp, deviceName, mac):
#this will add your derived nodes the master nodes list, allowing them to receive sets!!
localNodesName = deviceName + "_" + str(ch) + "99"
if not self.localNodes.has_key(localNodesName):
self.localNodes[localNodesName] = True
self.nodes[localNodesName] = self
#make the techname
lst = textwrap.wrap(str(mac), width=2)
tech = ""
for i in range(len(lst)):
tech += lst[i].lower() + ":"
chName2 = '_[' + tech
if int(ch) < 10:
ch = "0" + str(int(ch))
if len(ch) > 2:
ch = ch[:-2]
dname = deviceName + chName2 + str(ch) + ":98]!"
if int(timestamp) == 0:
timestamp = self.getTime()
topic = 'meshify/db/%s/%s/%s/%s' % (self.company, mac, dname, channel)
print topic
msg = """[ { "value":"%s", "timestamp":"%s" } ]""" % (str(value), str(timestamp))
print msg
self.q.put([topic, msg, 0])
def sendtodbDevJSON(self, ch, channel, value, timestamp, deviceName):
if int(ch) < 10:
ch = "0" + str(int(ch))
dname = deviceName + self.chName2 + str(ch) + ":99]!"
if int(timestamp) == 0:
timestamp = self.getTime()
topic = 'meshify/db/%s/%s/%s/%s' % (self.company, self.mac, dname, channel)
print topic
msg = """[ { "value":%s, "timestamp":"%s" } ]""" % (str(value), str(timestamp))
print msg
self.q.put([topic, msg, 0])
def sendtodbLora(self, ch, channel, value, timestamp, deviceName):
if ":" not in ch:
ch = ch[0:2] + ":" + ch[2:4]
#this will add your derived nodes the master nodes list, allowing them to receive sets!!
localNodesName = deviceName + "_" + str(ch).replace(':', "")
if not self.localNodes.has_key(localNodesName):
self.localNodes[localNodesName] = True
self.nodes[localNodesName] = self
dname = deviceName + self.chName2 + str(ch) + "]!"
if int(timestamp) == 0:
timestamp = self.getTime()
topic = 'meshify/db/%s/%s/%s/%s' % (self.company, self.mac, dname, channel)
print topic
msg = """[ { "value":"%s", "timestamp":"%s" } ]""" % (str(value), str(timestamp))
print msg
self.q.put([topic, msg, 0])
def sendtodbDev(self, ch, channel, value, timestamp, deviceName):
#this will add your derived nodes the master nodes list, allowing them to receive sets!!
localNodesName = deviceName + "_" + str(ch) + "99"
if not self.localNodes.has_key(localNodesName):
self.localNodes[localNodesName] = True
self.nodes[localNodesName] = self
if int(ch) < 10:
ch = "0" + str(int(ch))
dname = deviceName + self.chName2 + str(ch) + ":99]!"
if int(timestamp) == 0:
timestamp = self.getTime()
topic = 'meshify/db/%s/%s/%s/%s' % (self.company, self.mac, dname, channel)
print topic
msg = """[ { "value":"%s", "timestamp":"%s" } ]""" % (str(value), str(timestamp))
print msg
self.q.put([topic, msg, 0])
def sendtodbCH(self, ch, channel, value, timestamp):
if int(ch) < 10:
ch = "0" + str(ch)
dname = self.chName + str(ch) + ":99]!"
if int(timestamp) == 0:
timestamp = self.getTime()
topic = 'meshify/db/%s/%s/%s/%s' % (self.company, self.mac, dname, channel)
print topic
msg = """[ { "value":"%s", "timestamp":"%s" } ]""" % (str(value), str(timestamp))
print msg
self.q.put([topic, msg, 0])
def sendtodb(self, channel, value, timestamp):
if int(timestamp) == 0:
timestamp = self.getTime()
if timestamp < 1400499858:
return
else:
timestamp = str(int(timestamp) + int(self.offset))
topic = 'meshify/db/%s/%s/%s/%s' % (self.company, self.mac, self.deviceName, channel)
print topic
msg = """[ { "value":"%s", "timestamp":"%s" } ]""" % (str(value), str(timestamp))
print msg
self.q.put([topic, msg, 0])
def sendtodbJSON(self, channel, value, timestamp):
if int(timestamp) == 0:
timestamp = self.getTime()
if timestamp < 1400499858:
return
else:
timestamp = str(int(timestamp) + int(self.offset))
topic = 'meshify/db/%s/%s/%s/%s' % (self.company, self.mac, self.deviceName, channel)
print topic
msg = """[ { "value":%s, "timestamp":"%s" } ]""" % (str(value), str(timestamp))
print msg
self.q.put([topic, msg, 0])
def getTime(self):
return str(int(time.time() + int(self.offset)))

View File

@@ -0,0 +1,19 @@
"""Logging setup for plcfreshwater"""
import logging
from logging.handlers import RotatingFileHandler
import sys
from plcfreshwater import TOPIC_MAC
log_formatter = logging.Formatter('%(asctime)s %(levelname)s %(funcName)s(%(lineno)d) %(message)s')
log_file = './plcfreshwater_{}.log'.format(TOPIC_MAC)
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('plcfreshwater')
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,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,500 @@
"""Driver for plcfreshwater"""
import logging
import threading
import json
import time
from random import randint
import os
from device_base import deviceBase
import persistence
from utilities import get_public_ip_address, get_private_ip_address
from datetime import datetime as dt
_ = None
# GLOBAL VARIABLES
WAIT_FOR_CONNECTION_SECONDS = 10
IP_CHECK_PERIOD = 60
PLC_IP_ADDRESS = ""
TOPIC_MAC = ""
# PERSISTENCE FILE
IP_TABLE = persistence.load('persist.json')
if not IP_TABLE:
IP_TABLE = {
"000000000001":"192.168.1.201",
"000000000002":"192.168.1.202",
"000000000003":"192.168.1.203",
"000000000004":"192.168.1.211",
"000000000005":"192.168.1.210",
"000000000006":"192.168.1.208",
"000000000007":"192.168.1.209",
"000000000008":"192.168.1.208",
"000000000009":"192.168.1.209",
"000000000010":"192.168.1.210",
"000000000011":"192.168.1.211",
"000000000012":"192.168.1.212",
"000000000013":"192.168.1.213",
"000000000014":"192.168.1.214",
"000000000015":"192.168.1.215",
"000000000016":"192.168.1.216"
}
persistence.store(IP_TABLE, 'persist.json')
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 = "16"
self.finished = threading.Event()
self.force_send = False
self.public_ip_address = ""
self.public_ip_address_last_checked = 0
self.private_ip_address = ""
self.plcip = ""
self.ping_counter = 0
self.plc_ping_status = 'Default'
self.flowing = False
self.totalizing = False
self.totals_counter = 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("plcfreshwater driver will start in {} seconds".format(WAIT_FOR_CONNECTION_SECONDS - i))
time.sleep(1)
global TOPIC_MAC, PLC_IP_ADDRESS, log, write_tag, read_tag, PERSIST
TOPIC_MAC = self.mac
from file_logger import filelogger as log
log.info("plcfreshwater startup")
log.info("BOOM! Starting plcfreshwater driver...")
self._check_ip_address()
self.nodes["plcfreshwater_0199"] = self
send_loops = 0
PLC_IP_ADDRESS = IP_TABLE[self.mac]
self.plcip = PLC_IP_ADDRESS
log.info("PLC IP is {}".format(self.plcip))
self.sendtodbDev(1, 'plc_ip_address', self.plcip, 0, 'plcfreshwater')
PERSIST = persistence.load('totalizers_{}.json'.format(self.mac))
if not PERSIST:
PERSIST = {
'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,
'Totalizers': False
}
persistence.store(PERSIST, 'totalizers_{}.json'.format(self.mac))
from Channel import PLCChannel, ModbusChannel,read_tag, write_tag, TAG_DATAERROR_SLEEPTIME
from Tags import tags, tags_totalizer
if PERSIST["Totalizers"]:
CHANNELS = tags_totalizer
else:
CHANNELS = tags
while True:
now = time.time()
if self.force_send:
log.warning("FORCE SEND: TRUE")
if int(time.time()) % 600 == 0 or self.force_send:
if self.force_send:
payload = {"ts": time.time()*1000, "values": {}}
else:
payload = {"ts": round(time.time()/600)*600*1000, "values": {}}
resetPayload = {"ts": "", "values": {}}
dayReset, weekReset, monthReset, yearReset = False, False, False, False
for chan in CHANNELS:
try:
val = chan.read()
if chan.mesh_name == "lifetime_flow_meter_gal":
payload["values"]["day_volume"], dayReset = self.totalizeDay(val)
#payload["values"]["week_volume"], weekReset = self.totalizeWeek(val)
payload["values"]["month_volume"], monthReset = self.totalizeMonth(val)
#payload["values"]["year_volume"], yearReset = self.totalizeYear(val)
else:
if chan.mesh_name == "scaled_flow_meter":
if val > 0:
self.flowing = True
else:
self.flowing = False
payload["values"][chan.mesh_name] = val
#time.sleep(TAG_DATAERROR_SLEEPTIME) # sleep to allow Micro800 to handle ENET requests
except Exception as e:
log.error("Something went wrong in read: {}".format(e))
self.check_totals_reset(self.flowing,self.totalizing)
# print("plcfreshwater driver still alive...")
try:
plc_ping = os.system("ping -c 1 " + IP_TABLE[self.mac] + " > /dev/null 2>&1")
except Exception as e:
log.error("something went wrong in ping: {}".format(e))
if plc_ping == 0:
if not self.plc_ping_status == "OK":
payload["values"]["plc_ping"] = "OK"
self.plc_ping_status = "OK"
else:
if not self.plc_ping_status == "Comms Error to PLC":
payload["values"]["plc_ping"] = "Comms Error to PLC"
self.plc_ping_status = 'Comms Error to PLC'
self.sendToTB(json.dumps(payload))
self.sendToTBAttributes(json.dumps({"latestReportTime": round(time.time()/600)*600*1000}))
if dayReset:
resetPayload["values"]["yesterday_volume"] = payload["values"]["day_volume"]
resetPayload["values"]["day_volume"] = 0
if weekReset:
resetPayload["values"]["last_week_volume"] = payload["values"]["week_volume"]
resetPayload["values"]["week_volume"] = 0
if monthReset:
resetPayload["values"]["last_month_volume"] = payload["values"]["month_volume"]
resetPayload["values"]["month_volume"] = 0
if yearReset:
resetPayload["values"]["last_year_volume"] = payload["values"]["year_volume"]
resetPayload["values"]["year_volume"] = 0
if resetPayload["values"]:
resetPayload["ts"] = 1 + round(time.time()/600)*600*1000
self.sendToTB(json.dumps(resetPayload))
time.sleep(10)
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.sendtodbDev(1, 'public_ip_address', test_public_ip, 0, 'plcfreshwater')
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, 'plcfreshwater')
self.private_ip_address = test_private_ip
hostname = "8.8.8.8"
response = 1
try:
response = os.system("ping -c 1 " + hostname + " > /dev/null 2>&1")
except Exception as e:
print("Something went wrong in ping: {}".format(e))
#and then check the response...
if response == 0:
print(hostname, 'is up!')
self.ping_counter = 0
else:
print(hostname, 'is down!')
self.ping_counter += 1
if self.ping_counter >= 3:
print("Rebooting because no internet detected")
os.system('reboot')
def check_totals_reset(self, flowing, totalizing):
if flowing and not totalizing:
self.totals_counter = self.totals_counter + 1
else:
self.totals_counter = 0
if self.totals_counter >= 3:
self.fix_totals()
log.info("Would've run fix_totals!!!!")
self.totals_counter = 0
def fix_totals(self):
Daily_Holding = PERSIST["Daily Holding"] - PERSIST["Monthly Holding"]
new_lifetime = PERSIST["Lifetime"] - PERSIST["Monthly Holding"]
resp = write_tag(self.plcip, "Lifetime_Flow_Meter_Gal", new_lifetime, plc_type="Micro800")
if resp == True:
PERSIST["Daily Holding"] = Daily_Holding
PERSIST["Monthly Holding"] = 0.0
PERSIST["Lifetime"] = new_lifetime
persistence.store(PERSIST, 'totalizers_{}.json'.format(self.mac))
log.info("RESETTING TOTALIZERS!!!")
def plcfreshwater_sync(self, name, value):
"""Sync all data from the driver."""
self.force_send = True
# self.sendtodb("log", "synced", 0)
return True
def plcfreshwater_writeplctag(self, name, value):
"""Write a value to the PLC."""
from Channel import write_tag
new_val = json.loads(str(value).replace("'", '"'))
tag_n = str(new_val['tag']) # "cmd_Start"
val_n = new_val['val']
write_res = write_tag(str(PLC_IP_ADDRESS), tag_n, val_n, plc_type="Micro800")
print("Result of plcfreshwater_writeplctag(self, {}, {}) = {}".format(name, value, write_res))
if write_res is None:
write_res = "Error writing to PLC..."
return write_res
def convertPersist(original_json):
# Mapping of keys
key_mapping = {
'Todays': None,
'Yesterdays': None,
'Current Months': None,
'Previous Months': None,
'Monthly Holding': 'monthHolding',
'Daily Holding': 'dayHolding',
'Lifetime': 'lifetime',
'Day': 'day',
'Month': 'month',
'Last Report': None,
'Totalizers': 'Totalizers'
}
now = round(time.time()/600)*600*1000
# Convert keys and build new JSON object
new_json = {}
for original_key, new_key in key_mapping.items():
if new_key:
new_json[new_key] = original_json[original_key]
new_json["year"] = time.gmtime(now/1000.0).tm_year
# Convert to JSON format
#new_json_str = json.dumps(new_json, indent=4, sort_keys=True)
return(new_json)
def saveTotalizers(self, totalizers):
try:
with open("/root/python_firmware/totalizers.json", "w") as t:
json.dump(totalizers,t)
except Exception as e:
log.error(e)
def get_totalizers(self):
saveFile = "/root/python_firmware/totalizers.json"
# Check if the state file exists.
if not os.path.exists(saveFile):
return {
"day": 0,
"week": 0,
"month": 0,
"year": 0,
"lifetime": 0,
"dayHolding": 0,
"weekHolding": 0,
"monthHolding": 0,
"yearHolding": 0
}
try:
with open("/root/python_firmware/totalizers.json", "r") as t:
totalizers = json.load(t)
if not totalizers:
log.info("-----INITIALIZING TOTALIZERS-----")
totalizers = {
"day": 0,
"week": 0,
"month": 0,
"year": 0,
"lifetime": 0,
"dayHolding": 0,
"weekHolding": 0,
"monthHolding": 0,
"yearHolding": 0
}
except:
totalizers = {
"day": 0,
"week": 0,
"month": 0,
"year": 0,
"lifetime": 0,
"dayHolding": 0,
"weekHolding": 0,
"monthHolding": 0,
"yearHolding": 0
}
return totalizers
def totalizeDay(self,lifetime):
totalizers = self.get_totalizers()
if "Daily Holding" in totalizers.keys():
totalizers = self.convertPersist(totalizers)
now = round(time.time()/600)*600*1000
reset = False
value = lifetime - totalizers["dayHolding"]
if not int(time.gmtime(now/1000.0).tm_day) == int(totalizers["day"]):
totalizers["dayHolding"] = lifetime
totalizers["day"] = int(now.strftime("%d"))
self.saveTotalizers(totalizers)
reset = True
return (value,reset)
def totalizeWeek(self,lifetime):
totalizers = self.get_totalizers()
now = round(time.time()/600)*600*1000
reset = False
value = lifetime - totalizers["weekHolding"]
if (not now.strftime("%U") == totalizers["week"] and now.strftime("%a") == "Sun") or totalizers["week"] == 0:
totalizers["weekHolding"] = lifetime
totalizers["week"] = now.strftime("%U")
self.saveTotalizers(totalizers)
reset = True
return (value, reset)
def totalizeMonth(self,lifetime):
totalizers = self.get_totalizers()
if "Month Holding" in totalizers.keys():
totalizers = self.convertPersist(totalizers)
now = round(time.time()/600)*600*1000
reset = False
value = lifetime - totalizers["monthHolding"]
if not int(time.gmtime(now/1000.0).tm_mon) == int(totalizers["month"]):
totalizers["monthHolding"] = lifetime
totalizers["month"] = now.strftime("%m")
self.saveTotalizers(totalizers)
reset = True
return (value,reset)
def totalizeYear(self,lifetime):
totalizers = self.get_totalizers()
now = round(time.time()/600)*600*1000
reset = False
value = lifetime - totalizers["yearHolding"]
if not int(time.gmtime(now/1000.0).tm_year) == int(totalizers["year"]):
totalizers["yearHolding"] = lifetime
totalizers["year"] = now.strftime("%Y")
self.saveTotalizers(totalizers)
reset = True
return (value, reset)
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 PERSIST['Day'] == 0:
PERSIST['Day'] = day
PERSIST['Month'] = month
PERSIST['Daily Holding'] = val
PERSIST['Monthly Holding'] = val
persistence.store(PERSIST, 'totalizers_{}.json'.format(self.mac))
#Communication error during initialization check if lifetime has reported properly and update holdings
if PERSIST['Daily Holding'] == None and not(val == None):
PERSIST['Daily Holding'] = val
PERSIST['Monthly Holding'] = val
try:
if val - PERSIST["Lifetime"] > 0:
self.totalizing = True
else:
self.totalizing = False
except:
log.error("Error while checking for totalizing")
try:
if val - PERSIST['Daily Holding'] - PERSIST['Todays'] > 500 or time.time() - PERSIST['Last Report'] > 3600 or self.force_send:
PERSIST['Todays'] = val - PERSIST['Daily Holding']
PERSIST['Current Months'] = val - PERSIST['Monthly Holding']
PERSIST['Lifetime'] = val
self.sendtodbDev(1, 'total_fm_day_gal', PERSIST['Todays'], 0, 'plcfreshwater')
self.sendtodbDev(1, 'total_fm_day_bbls', PERSIST['Todays']/42, 0, 'plcfreshwater')
self.sendtodbDev(1, 'total_fm_month_gal', PERSIST['Current Months'], 0, 'plcfreshwater')
self.sendtodbDev(1, 'total_fm_month_bbls', PERSIST['Current Months']/42, 0, 'plcfreshwater')
self.sendtodbDev(1, 'total_fm_yesterday_gal', PERSIST['Yesterdays'], 0, 'plcfreshwater')
self.sendtodbDev(1, 'total_fm_yesterday_bbls', PERSIST['Yesterdays']/42, 0, 'plcfreshwater')
self.sendtodbDev(1, 'lifetime_flow_meter_gal', PERSIST['Lifetime'], 0, 'plcfreshwater')
self.sendtodbDev(1, 'lifetime_flow_meter_bbls', PERSIST['Lifetime']/42, 0, 'plcfreshwater')
if self.force_send:
self.sendtodbDev(1, 'total_fm_last_month_gal', PERSIST['Previous Months'], 0, 'plcfreshwater')
self.sendtodbDev(1, 'total_fm_last_month_bbls', PERSIST['Previous Months']/42, 0, 'plcfreshwater')
PERSIST['Last Report'] = time.time()
except:
if time.time() - PERSIST['Last Report'] > 3600 or self.force_send:
self.sendtodbDev(1, 'total_fm_day_gal', PERSIST['Todays'], 0, 'plcfreshwater')
self.sendtodbDev(1, 'total_fm_day_bbls', PERSIST['Todays']/42, 0, 'plcfreshwater')
self.sendtodbDev(1, 'total_fm_month_gal', PERSIST['Current Months'], 0, 'plcfreshwater')
self.sendtodbDev(1, 'total_fm_month_bbls', PERSIST['Current Months']/42, 0, 'plcfreshwater')
self.sendtodbDev(1, 'total_fm_yesterday_gal', PERSIST['Yesterdays'], 0, 'plcfreshwater')
self.sendtodbDev(1, 'total_fm_yesterday_bbls', PERSIST['Yesterdays']/42, 0, 'plcfreshwater')
self.sendtodbDev(1, 'lifetime_flow_meter_gal', PERSIST['Lifetime'], 0, 'plcfreshwater')
self.sendtodbDev(1, 'lifetime_flow_meter_bbls', PERSIST['Lifetime']/42, 0, 'plcfreshwater')
if self.force_send:
self.sendtodbDev(1, 'total_fm_last_month_gal', PERSIST['Previous Months'], 0, 'plcfreshwater')
self.sendtodbDev(1, 'total_fm_last_month_bbls', PERSIST['Previous Months']/42, 0, 'plcfreshwater')
PERSIST['Last Report'] = time.time()
#If the current day doesn't equal the stored day roll the dailies over
if not(day == PERSIST['Day']):
#if a comms error use the stored values else use the latested values
if val == None:
PERSIST['Yesterdays'] = PERSIST['Todays']
PERSIST['Todays'] = 0
PERSIST['Daily Holding'] = PERSIST['Lifetime']
else:
PERSIST['Yesterdays'] = val - PERSIST['Daily Holding']
PERSIST['Todays'] = 0
PERSIST['Daily Holding'] = val
PERSIST['Lifetime'] = val
PERSIST['Day'] = day
self.sendtodbDev(1, 'total_fm_day_gal', PERSIST['Todays'], 0, 'plcfreshwater')
self.sendtodbDev(1, 'total_fm_day_bbls', PERSIST['Todays']/42, 0, 'plcfreshwater')
self.sendtodbDev(1, 'total_fm_yesterday_gal', PERSIST['Yesterdays'], 0, 'plcfreshwater')
self.sendtodbDev(1, 'total_fm_yesterday_bbls', PERSIST['Yesterdays']/42, 0, 'plcfreshwater')
self.sendtodbDev(1, 'lifetime_flow_meter_gal', PERSIST['Lifetime'], 0, 'plcfreshwater')
self.sendtodbDev(1, 'lifetime_flow_meter_bbls', PERSIST['Lifetime']/42, 0, 'plcfreshwater')
PERSIST['Last Report'] = time.time()
#the day has rolled over if the month also rolls over
if not(month == PERSIST['Month']):
#if a comms error use the stored values else use the latested values
if val == None:
PERSIST['Previous Months'] = PERSIST['Current Months']
PERSIST['Current Months'] = 0
PERSIST['Monthly Holding'] = PERSIST['Lifetime']
else:
PERSIST['Previous Months'] = val - PERSIST['Monthly Holding']
PERSIST['Current Months'] = 0
PERSIST['Monthly Holding'] = val
PERSIST['Month'] = month
self.sendtodbDev(1, 'total_fm_month_gal', PERSIST['Current Months'], 0, 'plcfreshwater')
self.sendtodbDev(1, 'total_fm_month_bbls', PERSIST['Current Months']/42, 0, 'plcfreshwater')
self.sendtodbDev(1, 'total_fm_last_month_gal', PERSIST['Previous Months'], 0, 'plcfreshwater')
self.sendtodbDev(1, 'total_fm_last_month_bbls', PERSIST['Previous Months']/42, 0, 'plcfreshwater')
self.sendtodbDev(1, 'lifetime_flow_meter_gal', PERSIST['Lifetime'], 0, 'plcfreshwater')
self.sendtodbDev(1, 'lifetime_flow_meter_bbls', PERSIST['Lifetime']/42, 0, 'plcfreshwater')
PERSIST['Last Report'] = time.time()
persistence.store(PERSIST, 'totalizers_{}.json'.format(self.mac))

View File

@@ -0,0 +1,55 @@
from pycomm.ab_comm.clx import Driver as ClxDriver
from pycomm.cip.cip_base import CommError, DataError
import time
import sys
TAG_DATAERROR_SLEEPTIME = 5
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)
print("Data Error during readTag({}, {}): {}".format(addr, tag, err))
except CommError:
# err = c.get_status()
#clx.close()
print("Could not connect during readTag({}, {})".format(addr, tag))
except AttributeError as err:
clx.close()
print("AttributeError during readTag({}, {}): \n{}".format(addr, tag, err))
clx.close()
return False
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()
print("--\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()
print("--\nCommError during write_tag({}, {}, {}, plc_type={})\n{}\n--".format(addr, tag, val, plc_type, err))
#clx.close()
return False
resp = write_tag(sys.argv[1], "Lifetime_Flow_Meter_Gal", float(sys.argv[2]), "Micro800")
if resp:
print(read_tag(sys.argv[1], "Lifetime_Flow_Meter_Gal", "Micro800"))

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