added flowmetercc

This commit is contained in:
Nico Melone
2023-08-02 14:30:57 -05:00
parent 70b2f7c763
commit 69ddd7cd60
14 changed files with 734 additions and 21 deletions

Binary file not shown.

View File

@@ -1,14 +1,14 @@
{
"files": {
"file6": "persistence.py",
"file5": "file_logger.py",
"file4": "Channel.py",
"file3": "modbusMap.p",
"file6": "Tags.py",
"file5": "persistence.py",
"file4": "file_logger.py",
"file3": "Channel.py",
"file2": "utilities.py",
"file1": "flowmeterskid.py"
},
"deviceName": "flowmeterskid",
"driverId": "0190",
"releaseVersion": "1",
"driverId": "0199",
"releaseVersion": "2",
"driverFileName": "flowmeterskid.py"
}

View File

@@ -17,7 +17,7 @@ from datetime import datetime as dt
logger.info("flowmeterskid startup")
# GLOBAL VARIABLES
WAIT_FOR_CONNECTION_SECONDS = 20
WAIT_FOR_CONNECTION_SECONDS = 5
IP_CHECK_PERIOD = 60
_ = None
@@ -32,7 +32,7 @@ class start(threading.Thread, deviceBase):
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 = "1"
self.version = "2"
self.finished = threading.Event()
self.force_send = False
self.public_ip_address = ""
@@ -56,7 +56,7 @@ class start(threading.Thread, deviceBase):
time.sleep(1)
logger.info("BOOM! Starting flowmeterskid driver...")
self._check_ip_address()
#self._check_ip_address()
self.nodes["flowmeterskid_0199"] = self
@@ -65,13 +65,13 @@ class start(threading.Thread, deviceBase):
if self.force_send:
logger.warning("FORCE SEND: TRUE")
if int(time.time()) % 600 == 0 or self.force_send:
payload = {"ts": (round(dt.timestamp(dt.now())/600)*600)*1000, "values": {}}
payload = {"ts": round(time.time()/600)*600*1000, "values": {}}
resetPayload = {"ts": "", "values": {}}
dayReset, weekReset, monthReset, yearReset = False, False, False, False
for chan in CHANNELS:
val = chan.read()
try:
if chan in ["totalizer_1"]:
if chan.mesh_name in ["totalizer_1"]:
payload["values"]["day_volume"], dayReset = self.totalizeDay(val)
payload["values"]["week_volume"], weekReset = self.totalizeWeek(val)
payload["values"]["month_volume"], monthReset = self.totalizeMonth(val)
@@ -96,7 +96,7 @@ class start(threading.Thread, deviceBase):
resetPayload["values"]["year_volume"] = 0
if resetPayload["values"]:
resetPayload["ts"] = 1 + (round(dt.timestamp(dt.now())/600)*600)*1000
resetPayload["ts"] = 1 + round(time.time()/600)*600*1000
self.sendToTB(json.dumps(resetPayload))
if self.force_send:
@@ -162,7 +162,7 @@ class start(threading.Thread, deviceBase):
def totalizeDay(self,lifetime):
totalizers = self.get_totalizers()
now = dt.fromtimestamp(round(dt.timestamp(dt.now())/600)*600)
now = dt.fromtimestamp(round(time.time()/600)*600)
reset = False
value = lifetime - totalizers["dayHolding"]
if not int(now.strftime("%d")) == int(totalizers["day"]):
@@ -174,7 +174,7 @@ class start(threading.Thread, deviceBase):
def totalizeWeek(self,lifetime):
totalizers = self.get_totalizers()
now = dt.fromtimestamp(round(dt.timestamp(dt.now())/600)*600)
now = dt.fromtimestamp(round(time.time()/600)*600)
reset = False
value = lifetime - totalizers["weekHolding"]
if (not now.strftime("%U") == totalizers["week"] and now.strftime("%a") == "Sun") or totalizers["week"] == 0:
@@ -186,7 +186,7 @@ class start(threading.Thread, deviceBase):
def totalizeMonth(self,lifetime):
totalizers = self.get_totalizers()
now = dt.fromtimestamp(round(dt.timestamp(dt.now())/600)*600)
now = dt.fromtimestamp(round(time.time()/600)*600)
reset = False
value = lifetime - totalizers["monthHolding"]
if not int(now.strftime("%m")) == int(totalizers["month"]):
@@ -198,7 +198,7 @@ class start(threading.Thread, deviceBase):
def totalizeYear(self,lifetime):
totalizers = self.get_totalizers()
now = dt.fromtimestamp(round(dt.timestamp(dt.now())/600)*600)
now = dt.fromtimestamp(round(time.time()/600)*600)
reset = False
value = lifetime - totalizers["yearHolding"]
if not int(now.strftime("%Y")) == int(totalizers["year"]):

View File

@@ -0,0 +1,362 @@
"""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_loggerger import fileloggerger as logger
from flowmeterskid import INSTRUMENT, logger, 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)
logger.error("Data Error during readTag({}, {}): {}".format(addr, tag, err))
except CommError:
# err = c.get_status()
logger.error("Could not connect during readTag({}, {})".format(addr, tag))
except AttributeError as err:
clx.close()
logger.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:
logger.error("No length for {}".format(addr))
clx.close()
return False
except Exception:
logger.error("Error during readArray({}, {}, {}, {})".format(addr, tag, start, end))
err = clx.get_status()
clx.close()
logger.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()
logger.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()
logger.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 = ""
try:
for i in array:
i = hex(i).replace('0x', '')
while len(i) < 4:
i = "0" + i
print(i)
newVal = i + newVal
except:
logger.error("Issues with modbus read in Channel sending null")
return None
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:
logger.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()
logger.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:
logger.info("Error in read value: {}\nTrying one more time".format(e))
try:
read_value = instrument.read_float(self.register_number,4,self.channel_size)
except:
return None
elif self.data_type == "FLOATBS":
try:
read_value = byteSwap32(instrument.read_registers(self.register_number,2, 4))
except Exception as e:
logger.info("Error in read value: {}\nTrying one more time".format(e))
try:
read_value = byteSwap32(instrument.read_registers(self.register_number,2,4))
except:
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:
logger.info("Error in read value: {}\nTrying one more time".format(e))
try:
read_value = instrument.read_register(self.register_number,self.scaling,4)
except:
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:
logger.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:
logger.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:
logger.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()
logger.info("Sending {} for {} - {}".format(self.value, self.mesh_name, send_reason))
return send_needed

View File

@@ -0,0 +1,6 @@
from Channel import PLCChannel, ModbusChannel
tags = [
ModbusChannel('flowrate', 3873, 'FLOATBS', 10, 3600,channel_size=2, unit_number=2),
ModbusChannel('totalizer_1', 2609, 'FLOATBS', 100, 3600,channel_size=2, unit_number=2)
]

View File

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

View File

@@ -0,0 +1,18 @@
"""Logging setup for PiFlow"""
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 = './PiFlow.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('PiFlow')
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,231 @@
"""Driver for flowmeterskid."""
import threading
import json
import time
from random import randint
import os
import minimalmodbusM1
from device_base import deviceBase
from Channel import PLCChannel, ModbusChannel,read_tag, write_tag, TAG_DATAERROR_SLEEPTIME
import persistence
from utilities import get_public_ip_address, get_private_ip_address
from file_logger import filelogger as logger
from datetime import datetime as dt
logger.info("flowmeterskid startup")
# GLOBAL VARIABLES
WAIT_FOR_CONNECTION_SECONDS = 5
IP_CHECK_PERIOD = 60
_ = 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.daemon = True
self.version = "2"
self.finished = threading.Event()
self.force_send = False
self.public_ip_address = ""
self.public_ip_address_last_checked = 0
self.private_ip_address = ""
self.ping_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."""
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("flowmeterskid driver will start in {} seconds".format(WAIT_FOR_CONNECTION_SECONDS - i))
time.sleep(1)
logger.info("BOOM! Starting flowmeterskid driver...")
#self._check_ip_address()
self.nodes["flowmeterskid_0199"] = self
send_loops = 0
while True:
if self.force_send:
logger.warning("FORCE SEND: TRUE")
if int(time.time()) % 600 == 0 or self.force_send:
payload = {"ts": round(time.time()/600)*600*1000, "values": {}}
resetPayload = {"ts": "", "values": {}}
dayReset, weekReset, monthReset, yearReset = False, False, False, False
for chan in CHANNELS:
val = chan.read()
try:
if chan.mesh_name in ["totalizer_1"]:
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)
payload["values"][chan.mesh_name] = val
except Exception as e:
logger.error(e)
self.sendToTB(json.dumps(payload))
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))
if self.force_send:
self.force_send = False
def flowmeterskid_sync(self, name, value):
"""Sync all data from the driver."""
self.force_send = True
self.sendtodb("log", "synced", 0)
return True
def saveTotalizers(self, totalizers):
try:
with open("/root/python_firmware/totalizers.json", "w") as t:
json.dump(totalizers,t)
except Exception as e:
logger.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:
logger.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()
now = dt.fromtimestamp(round(time.time()/600)*600)
reset = False
value = lifetime - totalizers["dayHolding"]
if not int(now.strftime("%d")) == 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 = dt.fromtimestamp(round(time.time()/600)*600)
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()
now = dt.fromtimestamp(round(time.time()/600)*600)
reset = False
value = lifetime - totalizers["monthHolding"]
if not int(now.strftime("%m")) == 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 = dt.fromtimestamp(round(time.time()/600)*600)
reset = False
value = lifetime - totalizers["yearHolding"]
if not int(now.strftime("%Y")) == int(totalizers["year"]):
totalizers["yearHolding"] = lifetime
totalizers["year"] = now.strftime("%Y")
self.saveTotalizers(totalizers)
reset = True
return (value, reset)
def startRS485(self):
instrument = ""
with self.lock:
#minimalmodbus.BAUDRATE = 9600
#minimalmodbus.STOPBITS = 1
connected = False
while connected == False:
logger.info("Attempting to setup RS485")
connected = self.mcu.set485Baud(9600)#switch to configurable
time.sleep(1)
logger.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,62 @@
"""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."""
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.connect(("8.8.8.8", 80))
ip_address = sock.getsockname()[0]
sock.close()
except Exception as e:
return e
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 address: {}".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

View File

@@ -3,7 +3,7 @@
"driverFileName":"mainMeshify.py",
"deviceName":"mainMeshify",
"driverId":"0000",
"releaseVersion":"17",
"releaseVersion":"16",
"files": {
"file1":"mainMeshify.py",
"file2":"main.py",

View File

@@ -82,7 +82,7 @@ class main():
self.dst = ""
# queue for sets to the mesh network will handeled through a queue in this main driver
self.meshQ = Queue.Queue()
version = "13" # 6 - mistification # 5 - updated for SAT data and generic sets. 4 - devices changed to drivers for dia
version = "16" # 6 - mistification # 5 - updated for SAT data and generic sets. 4 - devices changed to drivers for dia
# self.sendtodb("version", version, 0)
thread.start_new_thread(self.registerThread, ())
@@ -339,8 +339,8 @@ class meshifyMain():
clientData = json.load(creds)
except:
clientData = {"clientId": mac, "username": "admin", "password": "columbus"}
with open("mqtt.json", "w+") as creds:
json.dump(clientData, creds)
#with open("mqtt.json", "w+") as creds:
#json.dump(clientData, creds)
self.mqtt = paho.Client(client_id=clientData["clientId"], clean_session=True)
# change to false for mqtt.meshify.com

View File

@@ -1,5 +1,4 @@
"""Driver for tankalarms"""
import threading
import json
import time