Added Folders
Add all the driver folders
This commit is contained in:
298
multisensor/channel.py
Normal file
298
multisensor/channel.py
Normal file
@@ -0,0 +1,298 @@
|
||||
"""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 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):
|
||||
"""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
|
||||
13
multisensor/config.txt
Normal file
13
multisensor/config.txt
Normal file
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"driverFileName": "multisensor.py",
|
||||
"deviceName": "multisensor",
|
||||
"driverId": "0240",
|
||||
"releaseVersion": "5",
|
||||
"files": {
|
||||
"file1": "multisensor.py",
|
||||
"file2": "utilities.py",
|
||||
"file3": "channel.py",
|
||||
"file4": "file_logger.py",
|
||||
"file5": "persistence.py"
|
||||
}
|
||||
}
|
||||
18
multisensor/file_logger.py
Normal file
18
multisensor/file_logger.py
Normal file
@@ -0,0 +1,18 @@
|
||||
"""Logging setup for multisensor"""
|
||||
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 = './multisensor.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('multisensor')
|
||||
filelogger.setLevel(logging.INFO)
|
||||
filelogger.addHandler(my_handler)
|
||||
|
||||
console_out = logging.StreamHandler(sys.stdout)
|
||||
console_out.setFormatter(log_formatter)
|
||||
filelogger.addHandler(console_out)
|
||||
22
multisensor/logger.py
Normal file
22
multisensor/logger.py
Normal file
@@ -0,0 +1,22 @@
|
||||
"""Logging setup for multisensor"""
|
||||
# LOGGING SETUP
|
||||
import logging
|
||||
from logging.handlers import RotatingFileHandler
|
||||
import sys
|
||||
|
||||
def setup():
|
||||
"""Set up the logger and return it."""
|
||||
log_formatter = logging.Formatter('%(asctime)s %(levelname)s %(funcName)s(%(lineno)d) %(message)s')
|
||||
log_file = './multisensor.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('multisensor')
|
||||
filelogger.setLevel(logging.INFO)
|
||||
filelogger.addHandler(my_handler)
|
||||
|
||||
console_out = logging.StreamHandler(sys.stdout)
|
||||
console_out.setFormatter(log_formatter)
|
||||
filelogger.addHandler(console_out)
|
||||
return filelogger
|
||||
323
multisensor/multisensor.py
Normal file
323
multisensor/multisensor.py
Normal file
@@ -0,0 +1,323 @@
|
||||
"""Driver for multisensor"""
|
||||
|
||||
import threading
|
||||
import json
|
||||
import time
|
||||
from random import randint
|
||||
|
||||
from device_base import deviceBase
|
||||
from channel import PLCChannel, read_tag, write_tag
|
||||
from utilities import get_public_ip_address
|
||||
|
||||
from file_logger import filelogger as log
|
||||
|
||||
import persistence
|
||||
|
||||
# PERSISTENCE FILE
|
||||
PERSIST = persistence.load('persist.json')
|
||||
if not PERSIST:
|
||||
PERSIST = {'an0low': 1.0, 'an0high': 20.0, 'an0active': 0,
|
||||
'an1low': 1.0, 'an1high': 20.0, 'an1active': 0,
|
||||
'an2low': 1.0, 'an2high': 20.0, 'an2active': 0,
|
||||
'an3low': 1.0, 'an3high': 20.0, 'an3active': 0,
|
||||
'an4low': 1.0, 'an4high': 20.0, 'an4active': 0,
|
||||
'an5low': 1.0, 'an5high': 20.0, 'an5active': 0,
|
||||
'an6low': 1.0, 'an6high': 20.0, 'an6active': 0,
|
||||
'an7low': 1.0, 'an7high': 20.0, 'an7active': 0}
|
||||
persistence.store(PERSIST, 'persist.json')
|
||||
|
||||
_ = None
|
||||
|
||||
# log = file_logger.setup()
|
||||
log.info("multisensor startup")
|
||||
|
||||
# GLOBAL VARIABLES
|
||||
WAIT_FOR_CONNECTION_SECONDS = 60
|
||||
PLC_IP_ADDRESS = "192.168.1.12"
|
||||
|
||||
CALIBRATION_TABLES = [[] for x in xrange(8)]
|
||||
|
||||
CHANNELS = [
|
||||
PLCChannel(PLC_IP_ADDRESS, 'an0active', 'input0.active', 'BOOL', 1.0, 600, map_=False, write_enabled=False, plc_type="Micro800"),
|
||||
PLCChannel(PLC_IP_ADDRESS, 'an1active', 'input1.active', 'BOOL', 1.0, 600, map_=False, write_enabled=False, plc_type="Micro800"),
|
||||
PLCChannel(PLC_IP_ADDRESS, 'an2active', 'input2.active', 'BOOL', 1.0, 600, map_=False, write_enabled=False, plc_type="Micro800"),
|
||||
PLCChannel(PLC_IP_ADDRESS, 'an3active', 'input3.active', 'BOOL', 1.0, 600, map_=False, write_enabled=False, plc_type="Micro800"),
|
||||
PLCChannel(PLC_IP_ADDRESS, 'an4active', 'input4.active', 'BOOL', 1.0, 600, map_=False, write_enabled=False, plc_type="Micro800"),
|
||||
PLCChannel(PLC_IP_ADDRESS, 'an5active', 'input5.active', 'BOOL', 1.0, 600, map_=False, write_enabled=False, plc_type="Micro800"),
|
||||
PLCChannel(PLC_IP_ADDRESS, 'an6active', 'input6.active', 'BOOL', 1.0, 600, map_=False, write_enabled=False, plc_type="Micro800"),
|
||||
PLCChannel(PLC_IP_ADDRESS, 'an7active', 'input7.active', 'BOOL', 1.0, 600, map_=False, write_enabled=False, plc_type="Micro800"),
|
||||
PLCChannel(PLC_IP_ADDRESS, 'an0val', 'input0.scaledValue', 'REAL', 1.0, 600, map_=False, write_enabled=False, plc_type="Micro800"),
|
||||
PLCChannel(PLC_IP_ADDRESS, 'an1val', 'input1.scaledValue', 'REAL', 1.0, 600, map_=False, write_enabled=False, plc_type="Micro800"),
|
||||
PLCChannel(PLC_IP_ADDRESS, 'an2val', 'input2.scaledValue', 'REAL', 1.0, 600, map_=False, write_enabled=False, plc_type="Micro800"),
|
||||
PLCChannel(PLC_IP_ADDRESS, 'an3val', 'input3.scaledValue', 'REAL', 1.0, 600, map_=False, write_enabled=False, plc_type="Micro800"),
|
||||
PLCChannel(PLC_IP_ADDRESS, 'an4val', 'input4.scaledValue', 'REAL', 1.0, 600, map_=False, write_enabled=False, plc_type="Micro800"),
|
||||
PLCChannel(PLC_IP_ADDRESS, 'an5val', 'input5.scaledValue', 'REAL', 1.0, 600, map_=False, write_enabled=False, plc_type="Micro800"),
|
||||
PLCChannel(PLC_IP_ADDRESS, 'an6val', 'input6.scaledValue', 'REAL', 1.0, 600, map_=False, write_enabled=False, plc_type="Micro800"),
|
||||
PLCChannel(PLC_IP_ADDRESS, 'an7val', 'input7.scaledValue', 'REAL', 1.0, 600, map_=False, write_enabled=False, plc_type="Micro800"),
|
||||
PLCChannel(PLC_IP_ADDRESS, 'pond0volume', 'input0.pondVolume', 'REAL', 1000.0, 600, map_=False, write_enabled=False, plc_type="Micro800"),
|
||||
PLCChannel(PLC_IP_ADDRESS, 'pond1volume', 'input1.pondVolume', 'REAL', 1000.0, 600, map_=False, write_enabled=False, plc_type="Micro800"),
|
||||
PLCChannel(PLC_IP_ADDRESS, 'pond2volume', 'input2.pondVolume', 'REAL', 1000.0, 600, map_=False, write_enabled=False, plc_type="Micro800"),
|
||||
PLCChannel(PLC_IP_ADDRESS, 'pond3volume', 'input3.pondVolume', 'REAL', 1000.0, 600, map_=False, write_enabled=False, plc_type="Micro800"),
|
||||
PLCChannel(PLC_IP_ADDRESS, 'pond4volume', 'input4.pondVolume', 'REAL', 1000.0, 600, map_=False, write_enabled=False, plc_type="Micro800"),
|
||||
PLCChannel(PLC_IP_ADDRESS, 'pond5volume', 'input5.pondVolume', 'REAL', 1000.0, 600, map_=False, write_enabled=False, plc_type="Micro800"),
|
||||
PLCChannel(PLC_IP_ADDRESS, 'pond6volume', 'input6.pondVolume', 'REAL', 1000.0, 600, map_=False, write_enabled=False, plc_type="Micro800"),
|
||||
PLCChannel(PLC_IP_ADDRESS, 'pond7volume', 'input7.pondVolume', 'REAL', 1000.0, 600, map_=False, write_enabled=False, plc_type="Micro800")
|
||||
|
||||
]
|
||||
|
||||
|
||||
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 = "5"
|
||||
self.finished = threading.Event()
|
||||
self.force_send = False
|
||||
self.public_ip_address = ""
|
||||
self.public_ip_address_last_checked = 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("multisensor driver will start in {} seconds".format(WAIT_FOR_CONNECTION_SECONDS - i))
|
||||
time.sleep(1)
|
||||
log.info("BOOM! Starting multisensor driver...")
|
||||
|
||||
|
||||
self._check_ip_address()
|
||||
|
||||
self.nodes["multisensor_0199"] = self
|
||||
|
||||
send_loops = 0
|
||||
ip_check_after = 60
|
||||
|
||||
for i in range(0,8):
|
||||
self.read_pond_calibration(i)
|
||||
|
||||
while True:
|
||||
now = time.time()
|
||||
if self.force_send:
|
||||
log.warning("FORCE SEND: TRUE")
|
||||
|
||||
for chan in CHANNELS:
|
||||
val = chan.read()
|
||||
if "active" in chan.plc_tag:
|
||||
PERSIST[chan.mesh_name] = val
|
||||
persistence.store(PERSIST,'persist.json')
|
||||
if "scaledValue" in chan.plc_tag:
|
||||
if val <= PERSIST[chan.mesh_name[:3]+"low"] and PERSIST[chan.mesh_name[:3]+"active"] == 1:
|
||||
self.sendtodbDev(1, chan.mesh_name[:3]+"alarm", "LOW", 0, 'multisensor')
|
||||
elif val >= PERSIST[chan.mesh_name[:3]+"high"] and PERSIST[chan.mesh_name[:3]+"active"] == 1:
|
||||
self.sendtodbDev(1, chan.mesh_name[:3]+"alarm", "HIGH", 0, 'multisensor')
|
||||
else:
|
||||
self.sendtodbDev(1, chan.mesh_name[:3]+"alarm", "OK", 0, 'multisensor')
|
||||
if chan.check(val, self.force_send):
|
||||
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'multisensor')
|
||||
#time.sleep(5)
|
||||
|
||||
|
||||
# print("multisensor driver still alive...")
|
||||
if self.force_send:
|
||||
if send_loops > 2:
|
||||
log.warning("Turning off force_send")
|
||||
self.force_send = False
|
||||
send_loops = 0
|
||||
for i in range(0,8):
|
||||
self.read_pond_calibration(i)
|
||||
else:
|
||||
send_loops += 1
|
||||
|
||||
|
||||
if (now - self.public_ip_address_last_checked) > ip_check_after:
|
||||
self._check_ip_address()
|
||||
|
||||
def read_pond_calibration(self, input_number):
|
||||
"""Read all calibration values for a specific pond."""
|
||||
last_read_height = -1.0
|
||||
cal_values = []
|
||||
cal_index = 1
|
||||
while last_read_height != 0 and cal_index <= 10:
|
||||
cal_tag_height = "input{}.calibrationLevel[{}]".format(input_number, cal_index)
|
||||
cal_tag_volume = "input{}.calibrationVolume[{}]".format(input_number, cal_index)
|
||||
read_height = read_tag(PLC_IP_ADDRESS, cal_tag_height, plc_type="Micro800")
|
||||
time.sleep(5)
|
||||
read_volume = read_tag(PLC_IP_ADDRESS, cal_tag_volume, plc_type="Micro800")
|
||||
time.sleep(5)
|
||||
if read_height and read_volume:
|
||||
if read_height[0] > 0.0:
|
||||
cal_values.append({"height": read_height[0], "volume": read_volume[0]})
|
||||
last_read_height = read_height[0]
|
||||
cal_index += 1
|
||||
|
||||
if cal_values != CALIBRATION_TABLES[input_number] or self.force_send:
|
||||
calibration_channel = "pond{}calibration".format(input_number)
|
||||
calibration_string = json.dumps(cal_values).replace('"', "'")
|
||||
self.sendtodbDev(1, calibration_channel, calibration_string, 0, 'multisensor')
|
||||
CALIBRATION_TABLES[input_number] = cal_values
|
||||
|
||||
|
||||
def _check_ip_address(self):
|
||||
"""Check the public IP address and send to Meshify if changed."""
|
||||
self.public_ip_address_last_checked = time.time()
|
||||
test_public_ip = get_public_ip_address()
|
||||
if not test_public_ip == self.public_ip_address:
|
||||
self.sendtodbDev(1, 'public_ip_address', test_public_ip, 0, 'multisensor')
|
||||
self.public_ip_address = test_public_ip
|
||||
|
||||
|
||||
|
||||
|
||||
def multisensor_sync(self, name, value):
|
||||
"""Sync all data from the driver."""
|
||||
self.force_send = True
|
||||
print("got sync({}, {})".format(name, value))
|
||||
self.sendtodb("log", "synced", 0)
|
||||
return True
|
||||
|
||||
def multisensor_writeplctag(self, name, value):
|
||||
"""Write a value to the PLC."""
|
||||
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 multisensor_writeplctag(self, {}, {}) = {}".format(name, value, write_res))
|
||||
if write_res is None:
|
||||
write_res = "Error writing to PLC..."
|
||||
if write_res:
|
||||
if "scalingConfig" in tag_n:
|
||||
if tag_n[-1] == "x":
|
||||
self.sendtodbDev(1, 'an{}max'.format(tag_n[5]), val_n, 0, 'multisensor')
|
||||
else:
|
||||
self.sendtodbDev(1, 'an{}min'.format(tag_n[5]), val_n, 0, 'multisensor')
|
||||
elif "isPondLevel" in tag_n:
|
||||
self.sendtodbDev(1, 'an{}ispond'.format(tag_n[5]), val_n, 0, 'multisensor')
|
||||
|
||||
return write_res
|
||||
|
||||
def multisensor_an0lowpsialarm(self, name, value):
|
||||
|
||||
value = int(value)
|
||||
PERSIST["an0low"] = value
|
||||
self.sendtodbDev(1, 'an0lowpsialarm', value, 0, 'multisensor')
|
||||
return persistence.store(PERSIST,"persist.json")
|
||||
|
||||
def multisensor_an1lowpsialarm(self, name, value):
|
||||
|
||||
value = int(value)
|
||||
PERSIST["an1low"] = value
|
||||
self.sendtodbDev(1, 'an1lowpsialarm', value, 0, 'multisensor')
|
||||
return persistence.store(PERSIST,"persist.json")
|
||||
|
||||
def multisensor_an2lowpsialarm(self, name, value):
|
||||
|
||||
value = int(value)
|
||||
PERSIST["an2low"] = value
|
||||
self.sendtodbDev(1, 'an2lowpsialarm', value, 0, 'multisensor')
|
||||
return persistence.store(PERSIST,"persist.json")
|
||||
|
||||
def multisensor_an3lowpsialarm(self, name, value):
|
||||
|
||||
value = int(value)
|
||||
PERSIST["an3low"] = value
|
||||
self.sendtodbDev(1, 'an3lowpsialarm', value, 0, 'multisensor')
|
||||
return persistence.store(PERSIST,"persist.json")
|
||||
|
||||
def multisensor_an4lowpsialarm(self, name, value):
|
||||
|
||||
value = int(value)
|
||||
PERSIST["an4low"] = value
|
||||
self.sendtodbDev(1, 'an4lowpsialarm', value, 0, 'multisensor')
|
||||
return persistence.store(PERSIST,"persist.json")
|
||||
|
||||
def multisensor_an5lowpsialarm(self, name, value):
|
||||
|
||||
value = int(value)
|
||||
PERSIST["an5low"] = value
|
||||
self.sendtodbDev(1, 'an5lowpsialarm', value, 0, 'multisensor')
|
||||
return persistence.store(PERSIST,"persist.json")
|
||||
|
||||
def multisensor_an6lowpsialarm(self, name, value):
|
||||
|
||||
value = int(value)
|
||||
PERSIST["an6low"] = value
|
||||
self.sendtodbDev(1, 'an6lowpsialarm', value, 0, 'multisensor')
|
||||
return persistence.store(PERSIST,"persist.json")
|
||||
|
||||
def multisensor_an7lowpsialarm(self, name, value):
|
||||
|
||||
value = int(value)
|
||||
PERSIST["an7low"] = value
|
||||
self.sendtodbDev(1, 'an7lowpsialarm', value, 0, 'multisensor')
|
||||
return persistence.store(PERSIST,"persist.json")
|
||||
|
||||
def multisensor_an0highpsialarm(self, name, value):
|
||||
|
||||
value = int(value)
|
||||
PERSIST["an0high"] = value
|
||||
self.sendtodbDev(1, 'an0highpsialarm', value, 0, 'multisensor')
|
||||
return persistence.store(PERSIST,"persist.json")
|
||||
|
||||
def multisensor_an1highpsialarm(self, name, value):
|
||||
|
||||
value = int(value)
|
||||
PERSIST["an1high"] = value
|
||||
self.sendtodbDev(1, 'an1highpsialarm', value, 0, 'multisensor')
|
||||
return persistence.store(PERSIST,"persist.json")
|
||||
|
||||
def multisensor_an2highpsialarm(self, name, value):
|
||||
|
||||
value = int(value)
|
||||
PERSIST["an2high"] = value
|
||||
self.sendtodbDev(1, 'an2highpsialarm', value, 0, 'multisensor')
|
||||
return persistence.store(PERSIST,"persist.json")
|
||||
|
||||
def multisensor_an3highpsialarm(self, name, value):
|
||||
|
||||
value = int(value)
|
||||
PERSIST["an3high"] = value
|
||||
self.sendtodbDev(1, 'an3highpsialarm', value, 0, 'multisensor')
|
||||
return persistence.store(PERSIST,"persist.json")
|
||||
|
||||
def multisensor_an4highpsialarm(self, name, value):
|
||||
|
||||
value = int(value)
|
||||
PERSIST["an4high"] = value
|
||||
self.sendtodbDev(1, 'an4highpsialarm', value, 0, 'multisensor')
|
||||
return persistence.store(PERSIST,"persist.json")
|
||||
|
||||
def multisensor_an5highpsialarm(self, name, value):
|
||||
|
||||
value = int(value)
|
||||
PERSIST["an5high"] = value
|
||||
self.sendtodbDev(1, 'an5highpsialarm', value, 0, 'multisensor')
|
||||
return persistence.store(PERSIST,"persist.json")
|
||||
|
||||
def multisensor_an6highpsialarm(self, name, value):
|
||||
|
||||
value = int(value)
|
||||
PERSIST["an6high"] = value
|
||||
self.sendtodbDev(1, 'an6highpsialarm', value, 0, 'multisensor')
|
||||
return persistence.store(PERSIST,"persist.json")
|
||||
|
||||
def multisensor_an7highpsialarm(self, name, value):
|
||||
|
||||
value = int(value)
|
||||
PERSIST["an7high"] = value
|
||||
self.sendtodbDev(1, 'an7highpsialarm', value, 0, 'multisensor')
|
||||
return persistence.store(PERSIST,"persist.json")
|
||||
21
multisensor/persistence.py
Normal file
21
multisensor/persistence.py
Normal 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
|
||||
51
multisensor/utilities.py
Normal file
51
multisensor/utilities.py
Normal file
@@ -0,0 +1,51 @@
|
||||
"""Utility functions for the driver."""
|
||||
import socket
|
||||
import struct
|
||||
|
||||
|
||||
def get_public_ip_address():
|
||||
"""Find the public IP Address of the host device."""
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
s.connect(("8.8.8.8", 80))
|
||||
ip = s.getsockname()[0]
|
||||
s.close()
|
||||
return ip
|
||||
|
||||
|
||||
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")
|
||||
else:
|
||||
return float("NaN")
|
||||
else:
|
||||
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 = struct.unpack('>f', mypack)
|
||||
print("[{}, {}] >> {}".format(int1, int2, f[0]))
|
||||
return f[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
|
||||
Reference in New Issue
Block a user