added swd controller and promagmbs rework
This commit is contained in:
299
promagmbs/plc_rework/Channel.py
Normal file
299
promagmbs/plc_rework/Channel.py
Normal file
@@ -0,0 +1,299 @@
|
||||
"""Define Meshify channel class."""
|
||||
import time
|
||||
from pycomm.ab_comm.clx import Driver as ClxDriver
|
||||
from pycomm.cip.cip_base import CommError, DataError
|
||||
from file_logger import filelogger as log
|
||||
import minimalmodbus
|
||||
|
||||
minimalmodbus.BAUDRATE = 9600
|
||||
minimalmodbus.STOPBITS = 1
|
||||
|
||||
|
||||
TAG_DATAERROR_SLEEPTIME = 5
|
||||
|
||||
def binarray(intval):
|
||||
"""Split an integer into its bits."""
|
||||
bin_string = '{0:08b}'.format(intval)
|
||||
bin_arr = [i for i in bin_string]
|
||||
bin_arr.reverse()
|
||||
return bin_arr
|
||||
|
||||
|
||||
def read_tag(addr, tag, plc_type="CLX"):
|
||||
"""Read a tag from the PLC."""
|
||||
direct = plc_type == "Micro800"
|
||||
clx = ClxDriver()
|
||||
try:
|
||||
if clx.open(addr, direct_connection=direct):
|
||||
try:
|
||||
val = clx.read_tag(tag)
|
||||
clx.close()
|
||||
return val
|
||||
except DataError as err:
|
||||
clx.close()
|
||||
time.sleep(TAG_DATAERROR_SLEEPTIME)
|
||||
log.error("Data Error during readTag({}, {}): {}".format(addr, tag, err))
|
||||
except CommError:
|
||||
# err = c.get_status()
|
||||
|
||||
log.error("Could not connect during readTag({}, {})".format(addr, tag))
|
||||
except AttributeError as err:
|
||||
clx.close()
|
||||
log.error("AttributeError during readTag({}, {}): \n{}".format(addr, tag, err))
|
||||
clx.close()
|
||||
return False
|
||||
|
||||
|
||||
def read_array(addr, tag, start, end, plc_type="CLX"):
|
||||
"""Read an array from the PLC."""
|
||||
direct = plc_type == "Micro800"
|
||||
clx = ClxDriver()
|
||||
if clx.open(addr, direct_connection=direct):
|
||||
arr_vals = []
|
||||
try:
|
||||
for i in range(start, end):
|
||||
tag_w_index = tag + "[{}]".format(i)
|
||||
val = clx.read_tag(tag_w_index)
|
||||
arr_vals.append(round(val[0], 4))
|
||||
if arr_vals:
|
||||
clx.close()
|
||||
return arr_vals
|
||||
else:
|
||||
log.error("No length for {}".format(addr))
|
||||
clx.close()
|
||||
return False
|
||||
except Exception:
|
||||
log.error("Error during readArray({}, {}, {}, {})".format(addr, tag, start, end))
|
||||
err = clx.get_status()
|
||||
clx.close()
|
||||
log.error(err)
|
||||
clx.close()
|
||||
|
||||
|
||||
def write_tag(addr, tag, val, plc_type="CLX"):
|
||||
"""Write a tag value to the PLC."""
|
||||
direct = plc_type == "Micro800"
|
||||
clx = ClxDriver()
|
||||
try:
|
||||
if clx.open(addr, direct_connection=direct):
|
||||
try:
|
||||
initial_val = clx.read_tag(tag)
|
||||
write_status = clx.write_tag(tag, val, initial_val[1])
|
||||
clx.close()
|
||||
return write_status
|
||||
except DataError as err:
|
||||
clx_err = clx.get_status()
|
||||
clx.close()
|
||||
log.error("--\nDataError during writeTag({}, {}, {}, plc_type={}) -- {}\n{}\n".format(addr, tag, val, plc_type, err, clx_err))
|
||||
|
||||
except CommError as err:
|
||||
clx_err = clx.get_status()
|
||||
log.error("--\nCommError during write_tag({}, {}, {}, plc_type={})\n{}\n--".format(addr, tag, val, plc_type, err))
|
||||
clx.close()
|
||||
return False
|
||||
|
||||
|
||||
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
|
||||
8
promagmbs/plc_rework/Tags.py
Normal file
8
promagmbs/plc_rework/Tags.py
Normal file
@@ -0,0 +1,8 @@
|
||||
from Channel import PLCChannel
|
||||
from promagmbs import PLC_IP_ADDRESS
|
||||
|
||||
tags = [
|
||||
PLCChannel(PLC_IP_ADDRESS, "volume_flow","Scaled_BPD_FlowRate","REAL", 100, 3600, plc_type="Micro800"),
|
||||
PLCChannel(PLC_IP_ADDRESS, "totalizer_1","Lifetime_Flow_Meter_BBLS","REAL", 1000, 3600, plc_type="Micro800"),
|
||||
PLCChannel(PLC_IP_ADDRESS, "volume_flow_units","SPT_Flow_Meter_Unit","STRING", 1000, 3600, plc_type="Micro800")
|
||||
]
|
||||
14
promagmbs/plc_rework/config.txt
Normal file
14
promagmbs/plc_rework/config.txt
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"files": {
|
||||
"file6": "persistence.py",
|
||||
"file5": "file_logger.py",
|
||||
"file4": "Channel.py",
|
||||
"file3": "modbusMap.p",
|
||||
"file2": "utilities.py",
|
||||
"file1": "promagmbs.py"
|
||||
},
|
||||
"deviceName": "promagmbs",
|
||||
"driverId": "0190",
|
||||
"releaseVersion": "5",
|
||||
"driverFileName": "promagmbs.py"
|
||||
}
|
||||
18
promagmbs/plc_rework/file_logger.py
Normal file
18
promagmbs/plc_rework/file_logger.py
Normal 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)
|
||||
21
promagmbs/plc_rework/persistence.py
Normal file
21
promagmbs/plc_rework/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
|
||||
174
promagmbs/plc_rework/promagmbs.py
Normal file
174
promagmbs/plc_rework/promagmbs.py
Normal file
@@ -0,0 +1,174 @@
|
||||
"""Driver for promagmbs."""
|
||||
import threading
|
||||
import json
|
||||
import time
|
||||
from random import randint
|
||||
import os
|
||||
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 log
|
||||
PLC_IP_ADDRESS = "192.168.1.12"
|
||||
from Tags import tags
|
||||
|
||||
from datetime import datetime as dt
|
||||
|
||||
log.info("promagmbs startup")
|
||||
|
||||
# GLOBAL VARIABLES
|
||||
WAIT_FOR_CONNECTION_SECONDS = 20
|
||||
IP_CHECK_PERIOD = 60
|
||||
|
||||
|
||||
# PERSISTENCE FILE
|
||||
PERSIST = persistence.load('promagmbs_persist.json')
|
||||
if not PERSIST:
|
||||
PERSIST = {
|
||||
"unit": "BBL/d (US Oil)"
|
||||
}
|
||||
persistence.store(PERSIST, 'promagmbs_persist.json')
|
||||
TOTALIZER = persistence.load('promagmbs_totalizer.json')
|
||||
if not TOTALIZER:
|
||||
TOTALIZER = {
|
||||
'yesterday_totalizer_1': dt.today().day,
|
||||
'yesterday_totalizer_2': dt.today().day,
|
||||
'yesterday_totalizer_3': dt.today().day,
|
||||
'yesterday_total_totalizer_1': 0,
|
||||
'yesterday_total_midnight_totalizer_1': 0,
|
||||
'yesterday_total_totalizer_2': 0,
|
||||
'yesterday_total_midnight_totalizer_2': 0,
|
||||
'yesterday_total_totalizer_3': 0,
|
||||
'yesterday_total_midnight_totalizer_3': 0
|
||||
}
|
||||
persistence.store(TOTALIZER, 'promagmbs_totalizer.json')
|
||||
_ = None
|
||||
|
||||
CHANNELS = tags
|
||||
|
||||
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
|
||||
self.private_ip_address = ""
|
||||
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):
|
||||
# pass
|
||||
"""Actually run the driver."""
|
||||
for i in range(0, WAIT_FOR_CONNECTION_SECONDS):
|
||||
print("promagmbs driver will start in {} seconds".format(WAIT_FOR_CONNECTION_SECONDS - i))
|
||||
time.sleep(1)
|
||||
log.info("BOOM! Starting promagmbs driver...")
|
||||
|
||||
self._check_ip_address()
|
||||
|
||||
self.nodes["promagmbs_0199"] = self
|
||||
|
||||
send_loops = 0
|
||||
while True:
|
||||
now = time.time()
|
||||
if self.force_send:
|
||||
log.warning("FORCE SEND: TRUE")
|
||||
|
||||
for chan in CHANNELS:
|
||||
val = chan.read()
|
||||
if chan.mesh_name in ['volume_flow_units']:
|
||||
val = PERSIST["unit"]
|
||||
if chan.mesh_name in ['totalizer_1','totalizer_2','totalizer_3']:
|
||||
right_now = dt.today()
|
||||
today_total, yesterday_total = self.totalize(val, TOTALIZER['yesterday_'+chan.mesh_name], right_now.day, right_now.hour, right_now.minute, TOTALIZER['yesterday_total_midnight_'+chan.mesh_name], TOTALIZER['yesterday_total_'+chan.mesh_name], chan.mesh_name)
|
||||
if chan.check(val, self.force_send):
|
||||
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'promagmbs')
|
||||
self.sendtodbDev(1,chan.mesh_name + "_today", today_total,0,'promagmbs')
|
||||
self.sendtodbDev(1,chan.mesh_name + "_yesterday", yesterday_total,0,'promagmbs')
|
||||
else:
|
||||
if chan.check(val, self.force_send):
|
||||
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'promagmbs')
|
||||
time.sleep(TAG_DATAERROR_SLEEPTIME) # sleep to allow Micro800 to handle ENET requests
|
||||
|
||||
# print("promagmbs driver still alive...")
|
||||
if self.force_send:
|
||||
if send_loops > 2:
|
||||
log.warning("Turning off force_send")
|
||||
self.force_send = False
|
||||
send_loops = 0
|
||||
else:
|
||||
send_loops += 1
|
||||
|
||||
|
||||
if (now - self.public_ip_address_last_checked) > IP_CHECK_PERIOD:
|
||||
self._check_ip_address()
|
||||
|
||||
def _check_ip_address(self):
|
||||
"""Check the public IP address and send to Meshify if changed."""
|
||||
self.public_ip_address_last_checked = time.time()
|
||||
test_public_ip = get_public_ip_address()
|
||||
test_public_ip = test_public_ip
|
||||
test_private_ip = get_private_ip_address()
|
||||
if not test_public_ip == self.public_ip_address and not test_public_ip == "0.0.0.0":
|
||||
self.sendtodbDev(1, 'public_ip_address', test_public_ip, 0, 'promagmbs')
|
||||
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, 'promagmbs')
|
||||
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 promagmbs_sync(self, name, value):
|
||||
"""Sync all data from the driver."""
|
||||
self.force_send = True
|
||||
self.sendtodb("log", "synced", 0)
|
||||
return True
|
||||
|
||||
|
||||
def totalize(self,val, yesterday, day, hour, minute, yesterday_total_midnight, yesterday_total,channel):
|
||||
if (yesterday_total == 0 and yesterday_total_midnight == 0) or (yesterday_total == None or yesterday_total_midnight == None):
|
||||
yesterday_total_midnight = val
|
||||
TOTALIZER['yesterday_total_midnight_'+channel] = yesterday_total_midnight
|
||||
persistence.store(TOTALIZER, 'promagmbs_totalizer.json')
|
||||
today_total = val - yesterday_total_midnight
|
||||
if hour == 0 and minute == 0 and not(day == yesterday):
|
||||
yesterday_total = today_total
|
||||
yesterday_total_midnight = val
|
||||
today_total = val - yesterday_total_midnight
|
||||
yesterday = day
|
||||
TOTALIZER['yesterday_'+channel] = yesterday
|
||||
TOTALIZER['yesterday_total_'+channel] = yesterday_total
|
||||
TOTALIZER['yesterday_total_midnight_'+channel] = yesterday_total_midnight
|
||||
persistence.store(TOTALIZER,'promagmbs_totalizer.json')
|
||||
|
||||
return today_total,yesterday_total
|
||||
62
promagmbs/plc_rework/utilities.py
Normal file
62
promagmbs/plc_rework/utilities.py
Normal 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
|
||||
@@ -1,519 +0,0 @@
|
||||
"""Driver for PiFlow"""
|
||||
import os
|
||||
import threading
|
||||
import json
|
||||
import time
|
||||
from random import randint
|
||||
from datetime import datetime as dt
|
||||
from device_base import deviceBase
|
||||
import persistence
|
||||
from utilities import get_public_ip_address, get_private_ip_address
|
||||
from file_logger import filelogger as log
|
||||
"""import RPi.GPIO as GPIO
|
||||
|
||||
Relay_Ch1 = 26
|
||||
Relay_Ch2 = 20
|
||||
Relay_Ch3 = 21
|
||||
|
||||
GPIO.setwarnings(False)
|
||||
GPIO.setmode(GPIO.BCM)
|
||||
|
||||
GPIO.setup(Relay_Ch1,GPIO.OUT)
|
||||
GPIO.output(Relay_Ch1, GPIO.HIGH)
|
||||
GPIO.setup(Relay_Ch2,GPIO.OUT)
|
||||
GPIO.output(Relay_Ch2, GPIO.HIGH)
|
||||
GPIO.setup(Relay_Ch3,GPIO.OUT)
|
||||
GPIO.output(Relay_Ch3, GPIO.HIGH)
|
||||
"""
|
||||
_ = None
|
||||
os.system('sudo timedatectl set-timezone America/Chicago')
|
||||
log.info("PiFlow startup")
|
||||
|
||||
# GLOBAL VARIABLES
|
||||
WAIT_FOR_CONNECTION_SECONDS = 5
|
||||
IP_CHECK_PERIOD = 60
|
||||
|
||||
|
||||
# PERSISTENCE FILE
|
||||
PERSIST = persistence.load('persist.json')
|
||||
if not PERSIST:
|
||||
PERSIST = {
|
||||
'flowmeter': 247,
|
||||
'drive': 1,
|
||||
'isVFD': False,
|
||||
'drive_enabled': True,
|
||||
'state': False,
|
||||
'state_timer': 0,
|
||||
'plc_ip': '192.168.1.12',
|
||||
'yesterday_totalizer_1': dt.today().day,
|
||||
'yesterday_totalizer_2': dt.today().day,
|
||||
'yesterday_totalizer_3': dt.today().day,
|
||||
'yesterday_total_totalizer_1': 0,
|
||||
'yesterday_total_midnight_totalizer_1': 0,
|
||||
'yesterday_total_totalizer_2': 0,
|
||||
'yesterday_total_midnight_totalizer_2': 0,
|
||||
'yesterday_total_totalizer_3': 0,
|
||||
'yesterday_total_midnight_totalizer_3': 0
|
||||
}
|
||||
persistence.store(PERSIST, 'persist.json')
|
||||
try:
|
||||
if time.time() - PERSIST['state_timer'] >= 60:
|
||||
GPIO.output(Relay_Ch1, GPIO.HIGH)
|
||||
PERSIST['state'] = False
|
||||
persistence.store(PERSIST, "persist.json")
|
||||
elif PERSIST['state']:
|
||||
GPIO.output(Relay_Ch1, GPIO.LOW)
|
||||
else:
|
||||
GPIO.output(Relay_Ch1, GPIO.HIGH)
|
||||
except:
|
||||
PERSIST['state'] = False
|
||||
PERSIST['state_time'] = time.time()
|
||||
persistence.store(PERSIST, "persist.json")
|
||||
|
||||
drive_enabled = PERSIST['drive_enabled']
|
||||
try:
|
||||
isVFD = PERSIST['isVFD']
|
||||
except:
|
||||
PERSIST['isVFD'] = False
|
||||
isVFD = PERSIST['isVFD']
|
||||
persistence.store(PERSIST)
|
||||
|
||||
try:
|
||||
plc_ip = PERSIST['plc_ip']
|
||||
except:
|
||||
PERSIST['plc_ip'] = '192.168.1.12'
|
||||
plc_ip = PERSIST['plc_ip']
|
||||
persistence.store(PERSIST)
|
||||
|
||||
|
||||
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 = "25"
|
||||
self.finished = threading.Event()
|
||||
self.force_send = False
|
||||
self.public_ip_address = ""
|
||||
self.private_ip_address = ""
|
||||
self.public_ip_address_last_checked = 0
|
||||
self.status = ""
|
||||
self.alarm = ""
|
||||
global mcug, CHANNELS
|
||||
mcug = mcu
|
||||
from Tags import tags
|
||||
|
||||
CHANNELS = tags
|
||||
|
||||
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("PiFlow driver will start in {} seconds".format(WAIT_FOR_CONNECTION_SECONDS - i))
|
||||
time.sleep(1)
|
||||
log.info("BOOM! Starting PiFlow driver...")
|
||||
|
||||
#self._check_watchdog()
|
||||
self._check_ip_address()
|
||||
|
||||
self.nodes["PiFlow_0199"] = self
|
||||
|
||||
send_loops = 0
|
||||
|
||||
while True:
|
||||
now = time.time()
|
||||
if self.force_send:
|
||||
log.warning("FORCE SEND: TRUE")
|
||||
if isVFD:
|
||||
status = {}
|
||||
for chan in CHANNELS[:24]: #build status/alarm strings
|
||||
try:
|
||||
val = chan.read()
|
||||
chan.check(val, self.force_send)
|
||||
status[chan.mesh_name] = chan.value
|
||||
except Exception as e:
|
||||
log.warning("An error occured in status check: {}".format(e))
|
||||
try:
|
||||
self.sendStatus(status)
|
||||
except Exception as e:
|
||||
log.warning("An error occured in send status: {}".format(e))
|
||||
for chan in CHANNELS[24:]:
|
||||
try:
|
||||
val = chan.read()
|
||||
if chan.mesh_name in ['totalizer_1','totalizer_2','totalizer_3']:
|
||||
right_now = dt.today()
|
||||
today_total, yesterday_total = self.totalize(val, PERSIST['yesterday_'+chan.mesh_name], right_now.day, right_now.hour, right_now.minute, PERSIST['yesterday_total_midnight_'+chan.mesh_name], PERSIST['yesterday_total_'+chan.mesh_name], chan.mesh_name)
|
||||
if chan.check(val, self.force_send):
|
||||
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'PiFlow')
|
||||
self.sendtodbDev(1,"today_"+chan.mesh_name, today_total,0,'PiFlow')
|
||||
self.sendtodbDev(1,"yesterday_"+chan.mesh_name, yesterday_total,0,'PiFlow')
|
||||
self.sendtodbDev(1, chan.mesh_name + "_units", "BBL",0,'PiFlow')
|
||||
else:
|
||||
if chan.check(val, self.force_send):
|
||||
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'PiFlow')
|
||||
except Exception as e:
|
||||
log.warning("An error occured in data collection: {}".format(e))
|
||||
else:
|
||||
for chan in CHANNELS:
|
||||
try:
|
||||
if chan.mesh_name == "remote_start":
|
||||
val = PERSIST["state"]
|
||||
else:
|
||||
val = None
|
||||
for _ in range(3):
|
||||
temp = chan.read()
|
||||
if not temp == None:
|
||||
val = temp
|
||||
if val == None:
|
||||
log.info("No modbus data sending previous value")
|
||||
val = chan.value
|
||||
if chan.mesh_name in ['totalizer_1','totalizer_2','totalizer_3']:
|
||||
right_now = dt.today()
|
||||
today_total, yesterday_total = self.totalize(val, PERSIST['yesterday_'+chan.mesh_name], right_now.day, right_now.hour, right_now.minute, PERSIST['yesterday_total_midnight_'+chan.mesh_name], PERSIST['yesterday_total_'+chan.mesh_name], chan.mesh_name)
|
||||
if chan.check(val, self.force_send):
|
||||
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'PiFlow')
|
||||
self.sendtodbDev(1,"today_"+chan.mesh_name, today_total,0,'PiFlow')
|
||||
self.sendtodbDev(1,"yesterday_"+chan.mesh_name, yesterday_total,0,'PiFlow')
|
||||
elif chan.mesh_name == "volume_flow" and not PERSIST['drive_enabled']:
|
||||
if chan.check(val, self.force_send):
|
||||
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'PiFlow')
|
||||
if chan.value > 0:
|
||||
self.sendtodbDev(1, "run_status", "Running", 0, 'PiFlow')
|
||||
else:
|
||||
self.sendtodbDev(1,"run_status", "Stopped", 0, 'PiFlow')
|
||||
elif chan.mesh_name == "remote_start":
|
||||
if chan.check(val, self.force_send):
|
||||
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'PiFlow')
|
||||
PERSIST["state_timer"] = time.time()
|
||||
persistence.store(PERSIST, "persist.json")
|
||||
else:
|
||||
if chan.check(val, self.force_send):
|
||||
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'PiFlow')
|
||||
|
||||
except Exception as e:
|
||||
log.warning("An error occured: {}".format(e))
|
||||
time.sleep(3)
|
||||
|
||||
|
||||
# print("PiFlow driver still alive...")
|
||||
if self.force_send:
|
||||
if send_loops > 2:
|
||||
log.warning("Turning off force_send")
|
||||
self.force_send = False
|
||||
send_loops = 0
|
||||
else:
|
||||
send_loops += 1
|
||||
|
||||
|
||||
if (now - self.public_ip_address_last_checked) > IP_CHECK_PERIOD:
|
||||
self._check_ip_address()
|
||||
time.sleep(10)
|
||||
|
||||
def _check_ip_address(self):
|
||||
"""Check the public IP address and send to Meshify if changed."""
|
||||
self.public_ip_address_last_checked = time.time()
|
||||
test_public_ip = get_public_ip_address()
|
||||
test_public_ip = test_public_ip[:-1]
|
||||
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, 'PiFlow')
|
||||
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, 'PiFlow')
|
||||
self.private_ip_address = test_private_ip
|
||||
|
||||
def PiFlow_sync(self, name, value):
|
||||
"""Sync all data from the driver."""
|
||||
self.force_send = True
|
||||
# self.sendtodb("log", "synced", 0)
|
||||
return True
|
||||
|
||||
def PiFlow_flowmeternumber(self, name, unit_number):
|
||||
"""Change the unit number for the PiFlow flow meter"""
|
||||
unit_number = int(unit_number)
|
||||
if drive_enabled:
|
||||
for chan in CHANNELS[0:8]:
|
||||
chan.unit_number = unit_number
|
||||
PERSIST['flowmeter'] = unit_number
|
||||
persistence.store(PERSIST, 'persist.json')
|
||||
return True
|
||||
else:
|
||||
for chan in CHANNELS:
|
||||
chan.unit_number = unit_number
|
||||
PERSIST['flowmeter'] = unit_number
|
||||
persistence.store(PERSIST, 'persist.json')
|
||||
self.sendtodbDev(1, 'flowmeternumber', unit_number, 0,'PiFlow')
|
||||
return True
|
||||
return False
|
||||
|
||||
def PiFlow_drivenumber(self, name, unit_number):
|
||||
"""Change the unit number for the PiFlow drive"""
|
||||
unit_number = int(unit_number)
|
||||
for chan in CHANNELS[8:]:
|
||||
chan.unit_number = unit_number
|
||||
|
||||
PERSIST['drive'] = unit_number
|
||||
persistence.store(PERSIST, 'persist.json')
|
||||
self.sendtodbDev(1, 'drivenumber', unit_number, 0,'PiFlow')
|
||||
return True
|
||||
|
||||
def PiFlow_reboot(self, name, value):
|
||||
os.system('reboot')
|
||||
return True
|
||||
|
||||
def PiFlow_drive_enabled(self, name, value):
|
||||
value = int(value)
|
||||
if value == 1:
|
||||
PERSIST['drive_enabled'] = True
|
||||
else:
|
||||
PERSIST['drive_enabled'] = False
|
||||
|
||||
persistence.store(PERSIST, 'persist.json')
|
||||
self.sendtodbDev(1, 'drive_enabled', value, 0,'PiFlow')
|
||||
return True
|
||||
|
||||
def PiFlow_write(self, name, value):
|
||||
"""Write a value to the device via modbus"""
|
||||
new_val = json.loads(str(value).replace("'", '"'))
|
||||
addr_n = int(new_val['addr'])
|
||||
reg_n = int(new_val['reg'])
|
||||
val_n = new_val['val']
|
||||
for chan in CHANNELS:
|
||||
if chan.unit_number == addr_n and chan.register_number == reg_n:
|
||||
write_res = chan.write(val_n)
|
||||
|
||||
log.info("Result of PiFlow_write(self, {}, {}) = {}".format(name, value, write_res))
|
||||
return write_res
|
||||
|
||||
"""def PiFlow_start(self, name, value):
|
||||
if isVFD:
|
||||
#do something with the plc
|
||||
log.info("Sending START signal to PLC")
|
||||
else:
|
||||
log.info("Sending START signal to Drive via relay {}".format(Relay_Ch1))
|
||||
GPIO.output(Relay_Ch1,GPIO.LOW)
|
||||
PERSIST["state"] = True
|
||||
PERSIST["state_timer"] = time.time()
|
||||
persistence.store(PERSIST,"persist.json")
|
||||
|
||||
return True"""
|
||||
|
||||
"""def PiFlow_stop(self, name, value):
|
||||
if isVFD:
|
||||
log.info("Sending STOP signal to PLC")
|
||||
#do something with the plc
|
||||
else:
|
||||
log.info("Sending STOP signal to Drive")
|
||||
GPIO.output(Relay_Ch1,GPIO.HIGH)
|
||||
PERSIST["state"] = False
|
||||
PERSIST["state_timer"] = time.time()
|
||||
persistence.store(PERSIST, "persist.json")
|
||||
return True"""
|
||||
|
||||
def totalize(self,val, yesterday, day, hour, minute, yesterday_total_midnight, yesterday_total,channel):
|
||||
if (yesterday_total == 0 and yesterday_total_midnight == 0) or (yesterday_total == None or yesterday_total_midnight == None):
|
||||
yesterday_total_midnight = val
|
||||
PERSIST['yesterday_total_midnight_'+channel] = yesterday_total_midnight
|
||||
persistence.store(PERSIST, 'persist.json')
|
||||
today_total = val - yesterday_total_midnight
|
||||
if hour == 0 and minute == 0 and not(day == yesterday):
|
||||
yesterday_total = today_total
|
||||
yesterday_total_midnight = val
|
||||
today_total = val - yesterday_total_midnight
|
||||
yesterday = day
|
||||
PERSIST['yesterday_'+channel] = yesterday
|
||||
PERSIST['yesterday_total_'+channel] = yesterday_total
|
||||
PERSIST['yesterday_total_midnight_'+channel] = yesterday_total_midnight
|
||||
persistence.store(PERSIST,'persist.json')
|
||||
|
||||
return today_total,yesterday_total
|
||||
|
||||
def sendStatus(self,status):
|
||||
status_string = ""
|
||||
|
||||
fault_codes = {
|
||||
0: "",
|
||||
2: "Auxiliary Input",
|
||||
3: "Power Loss",
|
||||
4: "UnderVoltage",
|
||||
5: "OverVoltage",
|
||||
7: "Motor Overload",
|
||||
8: "Heatsink OvrTemp",
|
||||
9: "Thermister OvrTemp",
|
||||
10: "DynBrake OverTemp",
|
||||
12: "HW OverCurrent",
|
||||
13: "Ground Fault",
|
||||
14: "Ground Warning",
|
||||
15: "Load Loss",
|
||||
17: "Input Phase Loss",
|
||||
18: "Motor PTC Trip",
|
||||
19: "Task Overrun",
|
||||
20: "TorqPrv Spd Band",
|
||||
21: "Output PhaseLoss",
|
||||
24: "Decel Inhibit",
|
||||
25: "OverSpeed Limit",
|
||||
26: "Brake Slipped",
|
||||
27: "Torq Prove Cflct",
|
||||
28: "TP Encls Config",
|
||||
29: "Analog In Loss",
|
||||
33: "AuRsts Exhausted",
|
||||
35: "IPM OverCurrent",
|
||||
36: "SW OverCurrent",
|
||||
38: "Phase U to Grnd",
|
||||
39: "Phase V to Grnd",
|
||||
40: "Phase W to Grnd",
|
||||
41: "Phase UV Short",
|
||||
42: "Phase VW Short",
|
||||
43: "Phase WU Short",
|
||||
44: "Phase UNegToGrnd",
|
||||
45: "Phase VNegToGrnd",
|
||||
46: "Phase WNegToGrnd",
|
||||
48: "System Defaulted",
|
||||
49: "Drive Powerup",
|
||||
51: "Clr Fault Queue",
|
||||
55: "Ctrl Bd Overtemp",
|
||||
59: "Invalid Code",
|
||||
61: "Shear Pin 1",
|
||||
62: "Shear Pin 2",
|
||||
64: "Drive Overload",
|
||||
67: "Pump Off",
|
||||
71: "Port 1 Adapter",
|
||||
72: "Port 2 Adapter",
|
||||
73: "Port 3 Adapter",
|
||||
74: "Port 4 Adapter",
|
||||
75: "Port 5 Adapter",
|
||||
76: "Port 6 Adapter",
|
||||
77: "IR Volts Range",
|
||||
78: "FluxAmpsRef Rang",
|
||||
79: "Excessive Load",
|
||||
80: "AutoTune Aborted",
|
||||
81: "Port 1 DPI Loss",
|
||||
82: "Port 2 DPI Loss",
|
||||
83: "Port 3 DPI Loss",
|
||||
84: "Port 4 DPI Loss",
|
||||
85: "Port 5 DPI Loss",
|
||||
86: "Port 6 DPI Loss",
|
||||
87: "Ixo VoltageRange",
|
||||
91: "Pri VelFdbk Loss",
|
||||
93: "Hw Enable Check",
|
||||
94: "Alt VelFdbk Loss",
|
||||
95: "Aux VelFdbk Loss",
|
||||
96: "PositionFdbkLoss",
|
||||
97: "Auto Tach Switch",
|
||||
100: "Parameter Chksum",
|
||||
101: "PwrDn NVS Blank",
|
||||
102: "NVS Not Blank",
|
||||
103: "PwrDn Nvs Incomp",
|
||||
104: "Pwr Brd Checksum",
|
||||
106: "Incompat MCB-PB",
|
||||
107: "Replaced MCB-PB",
|
||||
108: "Anlg Cal Chksum",
|
||||
110: "Ivld Pwr Bd Data",
|
||||
111: "PwrBd Invalid ID",
|
||||
112: "PwrBd App MinVer",
|
||||
113: "Tracking DataErr",
|
||||
115: "PwrDn Table Full",
|
||||
116: "PwrDnEntry2Large",
|
||||
117: "PwrDn Data Chksm",
|
||||
118: "PwrBd PwrDn Chks",
|
||||
124: "App ID Changed",
|
||||
125: "Using Backup App",
|
||||
134: "Start on PowerUp",
|
||||
137: "Ext Prechrg Err",
|
||||
138: "Precharge Open",
|
||||
141: "Autn Enc Angle",
|
||||
142: "Autn Spd Rstrct",
|
||||
143: "AutoTune CurReg",
|
||||
144: "AutoTune Inertia",
|
||||
145: "AutoTune Travel",
|
||||
13037: "Net IO Timeout"
|
||||
}
|
||||
|
||||
if status['vfd_active'] == "Stopped":
|
||||
status_string = status_string + status['vfd_active'] + "; " + status['vfd_ready']
|
||||
else:
|
||||
status_string = status_string + status['vfd_active']
|
||||
if status['vfd_rev']:
|
||||
status_string = status_string + '; ' + status['vfd_rev']
|
||||
if status['vfd_fwd']:
|
||||
status_string = status_string + '; ' + status['vfd_fwd']
|
||||
if status['vfd_atreference']:
|
||||
status_string = status_string + '; ' + status['vfd_atreference']
|
||||
alarm_string = ""
|
||||
if status['vfd_faulted'] == "Drive Faulted":
|
||||
status_string = status_string + '; ' + status['vfd_faulted']
|
||||
if status['vfd_commloss']:
|
||||
alarm_string = alarm_string + '; ' + status['vfd_commloss']
|
||||
if status['vfd_fbkalarm']:
|
||||
alarm_string = alarm_string + '; ' + status['vfd_fbkalarm']
|
||||
if status['vfd_faultcode']:
|
||||
alarm_string = alarm_string + '; ' + "Fault: {} Fault code: {}".format(fault_codes[status['vfd_faultcode']],str(status['vfd_faultcode']))
|
||||
if status['minspeedalarm']:
|
||||
alarm_string = alarm_string + '; ' + status['minspeedalarm']
|
||||
if status['pumpedoff']:
|
||||
alarm_string = alarm_string + '; ' + status['pumpedoff']
|
||||
if status['lockedout']:
|
||||
alarm_string = alarm_string + '; ' + status['lockedout']
|
||||
if status['tubingpressurehi']:
|
||||
alarm_string = alarm_string + '; ' + status['tubingpressurehi']
|
||||
if status['tubingpressurehihi']:
|
||||
alarm_string = alarm_string + '; ' + status['tubingpressurehihi']
|
||||
if status['tubingpressurelo']:
|
||||
alarm_string = alarm_string + '; ' + status['tubingpressurelo']
|
||||
if status['tubingpressurelolo']:
|
||||
alarm_string = alarm_string + '; ' + status['tubingpressurelolo']
|
||||
if status['flowmeterhihi']:
|
||||
alarm_string = alarm_string + '; ' + status['flowmeterhihi']
|
||||
if status['flowmeterhi']:
|
||||
alarm_string = alarm_string + '; ' + status['flowmeterhi']
|
||||
if status['flowmeterlolo']:
|
||||
alarm_string = alarm_string + '; ' + status['flowmeterlolo']
|
||||
if status['flowmeterlo']:
|
||||
alarm_string = alarm_string + '; ' + status['flowmeterlo']
|
||||
if status['fluidlevellolo']:
|
||||
alarm_string = alarm_string + '; ' + status['fluidlevellolo']
|
||||
if status['fluidlevello']:
|
||||
alarm_string = alarm_string + '; ' + status['fluidlevello']
|
||||
if status['fluidlevelhi']:
|
||||
alarm_string = alarm_string + '; ' + status['fluidlevelhi']
|
||||
if status['fluidlevelhihi']:
|
||||
alarm_string = alarm_string + '; ' + status['fluidlevelhihi']
|
||||
try:
|
||||
if status_string and status_string[0] == '; ':
|
||||
status_string = status_string[1:]
|
||||
if status_string and status_string[-1] == '; ':
|
||||
status_string = status_string[:-1]
|
||||
if alarm_string and alarm_string[0] == '; ':
|
||||
alarm_string = alarm_string[1:]
|
||||
if alarm_string and alarm_string[-1] == '; ':
|
||||
alarm_string = alarm_string[:-1]
|
||||
except Exception as e:
|
||||
log.warning("Error in send status semicolon: {}".format(e))
|
||||
|
||||
if self.status != status_string:
|
||||
self.status = status_string
|
||||
log.info("Sending {} for {}".format(status_string, 'run_status'))
|
||||
self.sendtodbDev(1, 'run_status', status_string, 0, 'PiFlow')
|
||||
if self.alarm != alarm_string:
|
||||
self.alarm = alarm_string
|
||||
log.info("Sending {} for {}".format(alarm_string, 'fault_a'))
|
||||
self.sendtodbDev(1, 'fault_a', alarm_string, 0 , 'PiFlow')
|
||||
|
||||
|
||||
|
||||
|
||||
299
swdcontroller/Channel.py
Normal file
299
swdcontroller/Channel.py
Normal file
@@ -0,0 +1,299 @@
|
||||
"""Define Meshify channel class."""
|
||||
import time
|
||||
from pycomm.ab_comm.clx import Driver as ClxDriver
|
||||
from pycomm.cip.cip_base import CommError, DataError
|
||||
from file_logger import filelogger as log
|
||||
import minimalmodbus
|
||||
|
||||
minimalmodbus.BAUDRATE = 9600
|
||||
minimalmodbus.STOPBITS = 1
|
||||
|
||||
|
||||
TAG_DATAERROR_SLEEPTIME = 5
|
||||
|
||||
def binarray(intval):
|
||||
"""Split an integer into its bits."""
|
||||
bin_string = '{0:08b}'.format(intval)
|
||||
bin_arr = [i for i in bin_string]
|
||||
bin_arr.reverse()
|
||||
return bin_arr
|
||||
|
||||
|
||||
def read_tag(addr, tag, plc_type="CLX"):
|
||||
"""Read a tag from the PLC."""
|
||||
direct = plc_type == "Micro800"
|
||||
clx = ClxDriver()
|
||||
try:
|
||||
if clx.open(addr, direct_connection=direct):
|
||||
try:
|
||||
val = clx.read_tag(tag)
|
||||
clx.close()
|
||||
return val
|
||||
except DataError as err:
|
||||
clx.close()
|
||||
time.sleep(TAG_DATAERROR_SLEEPTIME)
|
||||
log.error("Data Error during readTag({}, {}): {}".format(addr, tag, err))
|
||||
except CommError:
|
||||
# err = c.get_status()
|
||||
|
||||
log.error("Could not connect during readTag({}, {})".format(addr, tag))
|
||||
except AttributeError as err:
|
||||
clx.close()
|
||||
log.error("AttributeError during readTag({}, {}): \n{}".format(addr, tag, err))
|
||||
clx.close()
|
||||
return False
|
||||
|
||||
|
||||
def read_array(addr, tag, start, end, plc_type="CLX"):
|
||||
"""Read an array from the PLC."""
|
||||
direct = plc_type == "Micro800"
|
||||
clx = ClxDriver()
|
||||
if clx.open(addr, direct_connection=direct):
|
||||
arr_vals = []
|
||||
try:
|
||||
for i in range(start, end):
|
||||
tag_w_index = tag + "[{}]".format(i)
|
||||
val = clx.read_tag(tag_w_index)
|
||||
arr_vals.append(round(val[0], 4))
|
||||
if arr_vals:
|
||||
clx.close()
|
||||
return arr_vals
|
||||
else:
|
||||
log.error("No length for {}".format(addr))
|
||||
clx.close()
|
||||
return False
|
||||
except Exception:
|
||||
log.error("Error during readArray({}, {}, {}, {})".format(addr, tag, start, end))
|
||||
err = clx.get_status()
|
||||
clx.close()
|
||||
log.error(err)
|
||||
clx.close()
|
||||
|
||||
|
||||
def write_tag(addr, tag, val, plc_type="CLX"):
|
||||
"""Write a tag value to the PLC."""
|
||||
direct = plc_type == "Micro800"
|
||||
clx = ClxDriver()
|
||||
try:
|
||||
if clx.open(addr, direct_connection=direct):
|
||||
try:
|
||||
initial_val = clx.read_tag(tag)
|
||||
write_status = clx.write_tag(tag, val, initial_val[1])
|
||||
clx.close()
|
||||
return write_status
|
||||
except DataError as err:
|
||||
clx_err = clx.get_status()
|
||||
clx.close()
|
||||
log.error("--\nDataError during writeTag({}, {}, {}, plc_type={}) -- {}\n{}\n".format(addr, tag, val, plc_type, err, clx_err))
|
||||
|
||||
except CommError as err:
|
||||
clx_err = clx.get_status()
|
||||
log.error("--\nCommError during write_tag({}, {}, {}, plc_type={})\n{}\n--".format(addr, tag, val, plc_type, err))
|
||||
clx.close()
|
||||
return False
|
||||
|
||||
|
||||
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
|
||||
79
swdcontroller/Tags.py
Normal file
79
swdcontroller/Tags.py
Normal file
@@ -0,0 +1,79 @@
|
||||
from Channel import PLCChannel, ModbusChannel
|
||||
from swdcontroller import PLC_IP_ADDRESS
|
||||
|
||||
tags = [
|
||||
PLCChannel(PLC_IP_ADDRESS["b1"], "b1_suction_pressure","Ain_SuctionPressure.Val","REAL", 250, 3600, plc_type="CLX"),
|
||||
PLCChannel(PLC_IP_ADDRESS["b1"], "b1_discharge_pressure","Ain_DischargePressure.Val","REAL", 250, 3600, plc_type="CLX"),
|
||||
PLCChannel(PLC_IP_ADDRESS["b1"], "b1_speed_fbk","VFD_SpeedFdbk","REAL", 250, 3600, plc_type="CLX"),
|
||||
PLCChannel(PLC_IP_ADDRESS["b1"], "b1_out_current","VFD_OutCurrent","REAL", 250, 3600, plc_type="CLX"),
|
||||
PLCChannel(PLC_IP_ADDRESS["b1"], "b1_energy_today","Energy_Total[0]","REAL", 250, 3600, plc_type="CLX"),
|
||||
PLCChannel(PLC_IP_ADDRESS["b1"], "b1_energy_yesterday","Energy_Total[1]","REAL", 250, 3600, plc_type="CLX"),
|
||||
PLCChannel(PLC_IP_ADDRESS["b1"], "b1_spt_pid_manual","cfg_PID_ManualSP","REAL", 250, 3600, plc_type="CLX"),
|
||||
PLCChannel(PLC_IP_ADDRESS["b1"], "b1_spt_pid_discharge","cfg_PID_DischargePressureSP","REAL", 250, 3600, plc_type="CLX"),
|
||||
PLCChannel(PLC_IP_ADDRESS["b1"], "b1_spt_pid_suction","cfg_PID_SuctionPressureSP","REAL", 250, 3600, plc_type="CLX"),
|
||||
PLCChannel(PLC_IP_ADDRESS["b1"], "b1_alm_suction","alarm_SuctionPressure","STRING", 0, 3600, plc_type="CLX", map_={0: "OK", 1: "Alarmed"}),
|
||||
PLCChannel(PLC_IP_ADDRESS["b1"], "b1_alm_discharge","alarm_DischargePressure","STRING", 0, 3600, plc_type="CLX", map_={0: "OK", 1: "Alarmed"}),
|
||||
PLCChannel(PLC_IP_ADDRESS["b1"], "b1_alm_vfd","alarm_VFD","STRING", 0, 3600, plc_type="CLX", map_={0: "OK", 1: "Alarmed"}),
|
||||
PLCChannel(PLC_IP_ADDRESS["b1"], "b1_alm_lockout","alarm_Lockout","STRING", 0, 3600, plc_type="CLX", map_={0: "OK", 1: "Alarmed"}),
|
||||
PLCChannel(PLC_IP_ADDRESS["b1"], "b1_cmd_start","cmd_Start","BOOL", 0, 3600, plc_type="CLX"),
|
||||
PLCChannel(PLC_IP_ADDRESS["b1"], "b1_cmd_stop","cmd_Stop","BOOL", 0, 3600, plc_type="CLX"),
|
||||
PLCChannel(PLC_IP_ADDRESS["b1"], "b1_pid_discharge","cfg_PID_DischargePressure","BOOL", 0, 3600, plc_type="CLX"),
|
||||
PLCChannel(PLC_IP_ADDRESS["b1"], "b1_pid_control","sts_PID_Control","STRING", 250, 3600, plc_type="CLX", map_={0:"suction", 1: "discharge", 2: "manual"}),
|
||||
PLCChannel(PLC_IP_ADDRESS["b1"], "b1_status","Device_Status_INT","STRING", 250, 3600, plc_type="CLX", map_={0:"Stopped",1:"Run", 2:"Lockout", 3:"True Alarm"}),
|
||||
PLCChannel(PLC_IP_ADDRESS["b1"], "b1_run_permissive","Run_Permissive_INT","STRING", 250, 3600, plc_type="CLX", map_={0: "All Clear", 1:"Suction Pressure", 2:"Discharge Pressure", 3:"VFD", 4:"Minimum Speed"}),
|
||||
PLCChannel(PLC_IP_ADDRESS["b1"], "b1_start_permissive","Start_Permissive_INT","STRING", 250, 3600, plc_type="CLX", map_={0:"All Clear", 1:"Suctions Pressure", 2:"Discharge Pressure",3:"VFD", 4:"Downtime"}),
|
||||
PLCChannel(PLC_IP_ADDRESS["b1"], "b1_vfd_last_fault","PowerFlex755.Val_LastFaultCode","STRING", 250, 3600, plc_type="CLX", map_={ 0: "No Fault", 2: "Auxiliary Input", 3: "Power Loss", 4: "UnderVoltage", 5: "OverVoltage", 7: "Motor Overload", 8: "Heatsink OverTemp", 9: "Thermister OverTemp", 10: "Dynamic Brake OverTemp", 12: "Hardware OverCurrent", 13: "Ground Fault", 14: "Ground Warning", 15: "Load Loss", 17: "Input Phase Loss", 18: "Motor PTC Trip", 19: "Task Overrun", 20: "Torque Prove Speed Band", 21: "Output Phase Loss", 24: "Decel Inhibit", 25: "OverSpeed Limit", 26: "Brake Slipped", 27: "Torque Prove Conflict", 28: "TP Encls Confict", 29: "Analog In Loss", 33: "Auto Restarts Exhausted", 35: "IPM OverCurrent", 36: "SW OverCurrent", 38: "Phase U to Ground", 39: "Phase V to Ground", 40: "Phase W to Ground", 41: "Phase UV Short", 42: "Phase VW Short", 43: "Phase WU Short", 44: "Phase UNeg to Ground", 45: "Phase VNeg to Ground", 46: "Phase WNeg to Ground", 48: "System Defaulted", 49: "Drive Powerup", 51: "Clear Fault Queue", 55: "Control Board Overtemp", 59: "Invalid Code", 61: "Shear Pin 1", 62: "Shear Pin 2", 64: "Drive Overload", 66: "OW Torque Level", 67: "Pump Off", 71: "Port 1 Adapter", 72: "Port 2 Adapter", 73: "Port 3 Adapter", 74: "Port 4 Adapter", 75: "Port 5 Adapter", 76: "Port 6 Adapter", 77: "IR Volts Range", 78: "FluxAmps Ref Range", 79: "Excessive Load", 80: "AutoTune Aborted", 81: "Port 1 DPI Loss", 82: "Port 2 DPI Loss", 83: "Port 3 DPI Loss", 84: "Port 4 DPI Loss", 85: "Port 5 DPI Loss", 86: "Port 6 DPI Loss", 87: "IXo Voltage Range", 91: "Primary Velocity Feedback Loss", 93: "Hardware Enable Check", 94: "Alternate Velocity Feedback Loss", 95: "Auxiliary Velocity Feedback Loss", 96: "Position Feedback Loss", 97: "Auto Tach Switch", 100: "Parameter Checksum", 101: "Power Down NVS Blank", 102: "NVS Not Blank", 103: "Power Down NVS Incompatible", 104: "Power Board Checksum", 106: "Incompat MCB-PB", 107: "Replaced MCB-PB", 108: "Analog Calibration Checksum", 110: "Invalid Power Board Data", 111: "Power Board Invalid ID", 112: "Power Board App Min Version", 113: "Tracking DataError", 115: "Power Down Table Full", 116: "Power Down Entry Too Large", 117: "Power Down Data Checksum", 118: "Power Board Power Down Checksum", 124: "App ID Changed", 125: "Using Backup App", 134: "Start on Power Up", 137: "External Precharge Error", 138: "Precharge Open", 141: "Autotune Enc Angle", 142: "Autotune Speed Restricted", 143: "Autotune Current Regulator", 144: "Autotune Inertia", 145: "Autotune Travel", 13035: "Net IO Timeout", 13037: "Net IO Timeout" } ),
|
||||
PLCChannel(PLC_IP_ADDRESS["b1"], "b1_vfd_current_fault","sts_CurrentVFDFaultCode","STRING", 250, 3600, plc_type="CLX", map_={ 0: "No Fault", 2: "Auxiliary Input", 3: "Power Loss", 4: "UnderVoltage", 5: "OverVoltage", 7: "Motor Overload", 8: "Heatsink OverTemp", 9: "Thermister OverTemp", 10: "Dynamic Brake OverTemp", 12: "Hardware OverCurrent", 13: "Ground Fault", 14: "Ground Warning", 15: "Load Loss", 17: "Input Phase Loss", 18: "Motor PTC Trip", 19: "Task Overrun", 20: "Torque Prove Speed Band", 21: "Output Phase Loss", 24: "Decel Inhibit", 25: "OverSpeed Limit", 26: "Brake Slipped", 27: "Torque Prove Conflict", 28: "TP Encls Confict", 29: "Analog In Loss", 33: "Auto Restarts Exhausted", 35: "IPM OverCurrent", 36: "SW OverCurrent", 38: "Phase U to Ground", 39: "Phase V to Ground", 40: "Phase W to Ground", 41: "Phase UV Short", 42: "Phase VW Short", 43: "Phase WU Short", 44: "Phase UNeg to Ground", 45: "Phase VNeg to Ground", 46: "Phase WNeg to Ground", 48: "System Defaulted", 49: "Drive Powerup", 51: "Clear Fault Queue", 55: "Control Board Overtemp", 59: "Invalid Code", 61: "Shear Pin 1", 62: "Shear Pin 2", 64: "Drive Overload", 66: "OW Torque Level", 67: "Pump Off", 71: "Port 1 Adapter", 72: "Port 2 Adapter", 73: "Port 3 Adapter", 74: "Port 4 Adapter", 75: "Port 5 Adapter", 76: "Port 6 Adapter", 77: "IR Volts Range", 78: "FluxAmps Ref Range", 79: "Excessive Load", 80: "AutoTune Aborted", 81: "Port 1 DPI Loss", 82: "Port 2 DPI Loss", 83: "Port 3 DPI Loss", 84: "Port 4 DPI Loss", 85: "Port 5 DPI Loss", 86: "Port 6 DPI Loss", 87: "IXo Voltage Range", 91: "Primary Velocity Feedback Loss", 93: "Hardware Enable Check", 94: "Alternate Velocity Feedback Loss", 95: "Auxiliary Velocity Feedback Loss", 96: "Position Feedback Loss", 97: "Auto Tach Switch", 100: "Parameter Checksum", 101: "Power Down NVS Blank", 102: "NVS Not Blank", 103: "Power Down NVS Incompatible", 104: "Power Board Checksum", 106: "Incompat MCB-PB", 107: "Replaced MCB-PB", 108: "Analog Calibration Checksum", 110: "Invalid Power Board Data", 111: "Power Board Invalid ID", 112: "Power Board App Min Version", 113: "Tracking DataError", 115: "Power Down Table Full", 116: "Power Down Entry Too Large", 117: "Power Down Data Checksum", 118: "Power Board Power Down Checksum", 124: "App ID Changed", 125: "Using Backup App", 134: "Start on Power Up", 137: "External Precharge Error", 138: "Precharge Open", 141: "Autotune Enc Angle", 142: "Autotune Speed Restricted", 143: "Autotune Current Regulator", 144: "Autotune Inertia", 145: "Autotune Travel", 13035: "Net IO Timeout", 13037: "Net IO Timeout" }),
|
||||
PLCChannel(PLC_IP_ADDRESS["b1"], "b1_io_fault","ControllerFault_IO","STRING", 250, 3600, plc_type="CLX", map_={0: "No Fault", 1: "Faulted"}),
|
||||
PLCChannel(PLC_IP_ADDRESS["b1"], "b1_program_fault","ControllerFault_Program","STRING", 250, 3600, plc_type="CLX", map_={0: "No Fault", 1: "Faulted"}),
|
||||
PLCChannel(PLC_IP_ADDRESS["b1"], "b1_min_speed","PowerFlex755.Cfg_MinSpdRef","REAL", 250, 3600, plc_type="CLX"),
|
||||
PLCChannel(PLC_IP_ADDRESS["b1"], "b1_max_speed","PowerFlex755.Cfg_MaxSpdRef","REAL", 250, 3600, plc_type="CLX"),
|
||||
PLCChannel(PLC_IP_ADDRESS["b2"], "b2_suction_pressure","Ain_SuctionPressure.Val","REAL", 250, 3600, plc_type="CLX"),
|
||||
PLCChannel(PLC_IP_ADDRESS["b2"], "b2_discharge_pressure","Ain_DischargePressure.Val","REAL", 250, 3600, plc_type="CLX"),
|
||||
PLCChannel(PLC_IP_ADDRESS["b2"], "b2_speed_fbk","VFD_SpeedFdbk","REAL", 250, 3600, plc_type="CLX"),
|
||||
PLCChannel(PLC_IP_ADDRESS["b2"], "b2_out_current","VFD_OutCurrent","REAL", 250, 3600, plc_type="CLX"),
|
||||
PLCChannel(PLC_IP_ADDRESS["b2"], "b2_energy_today","Energy_Total[0]","REAL", 250, 3600, plc_type="CLX"),
|
||||
PLCChannel(PLC_IP_ADDRESS["b2"], "b2_energy_yesterday","Energy_Total[1]","REAL", 250, 3600, plc_type="CLX"),
|
||||
PLCChannel(PLC_IP_ADDRESS["b2"], "b2_spt_pid_manual","cfg_PID_ManualSP","REAL", 250, 3600, plc_type="CLX"),
|
||||
PLCChannel(PLC_IP_ADDRESS["b2"], "b2_spt_pid_discharge","cfg_PID_DischargePressureSP","REAL", 250, 3600, plc_type="CLX"),
|
||||
PLCChannel(PLC_IP_ADDRESS["b2"], "b2_spt_pid_suction","cfg_PID_SuctionPressureSP","REAL", 250, 3600, plc_type="CLX"),
|
||||
PLCChannel(PLC_IP_ADDRESS["b2"], "b2_alm_suction","alarm_SuctionPressure","STRING", 0, 3600, plc_type="CLX", map_={0: "OK", 1: "Alarmed"}),
|
||||
PLCChannel(PLC_IP_ADDRESS["b2"], "b2_alm_discharge","alarm_DischargePressure","STRING", 0, 3600, plc_type="CLX", map_={0: "OK", 1: "Alarmed"}),
|
||||
PLCChannel(PLC_IP_ADDRESS["b2"], "b2_alm_vfd","alarm_VFD","STRING", 0, 3600, plc_type="CLX", map_={0: "OK", 1: "Alarmed"}),
|
||||
PLCChannel(PLC_IP_ADDRESS["b2"], "b2_alm_lockout","alarm_Lockout","STRING", 0, 3600, plc_type="CLX", map_={0: "OK", 1: "Alarmed"}),
|
||||
PLCChannel(PLC_IP_ADDRESS["b2"], "b2_cmd_start","cmd_Start","BOOL", 0, 3600, plc_type="CLX"),
|
||||
PLCChannel(PLC_IP_ADDRESS["b2"], "b2_cmd_stop","cmd_Stop","BOOL", 0, 3600, plc_type="CLX"),
|
||||
PLCChannel(PLC_IP_ADDRESS["b2"], "b2_pid_discharge","cfg_PID_DischargePressure","BOOL", 0, 3600, plc_type="CLX"),
|
||||
PLCChannel(PLC_IP_ADDRESS["b2"], "b2_pid_control","sts_PID_Control","STRING", 250, 3600, plc_type="CLX", map_={0:"suction", 1: "discharge", 2: "manual"}),
|
||||
PLCChannel(PLC_IP_ADDRESS["b2"], "b2_status","Device_Status_INT","STRING", 250, 3600, plc_type="CLX", map_={0:"Stopped",1:"Run", 2:"Lockout", 3:"True Alarm"}),
|
||||
PLCChannel(PLC_IP_ADDRESS["b2"], "b2_run_permissive","Run_Permissive_INT","STRING", 250, 3600, plc_type="CLX", map_={0: "All Clear", 1:"Suction Pressure", 2:"Discharge Pressure", 3:"VFD", 4:"Minimum Speed"}),
|
||||
PLCChannel(PLC_IP_ADDRESS["b2"], "b2_start_permissive","Start_Permissive_INT","STRING", 250, 3600, plc_type="CLX", map_={0:"All Clear", 1:"Suctions Pressure", 2:"Discharge Pressure",3:"VFD", 4:"Downtime"}),
|
||||
PLCChannel(PLC_IP_ADDRESS["b2"], "b2_vfd_last_fault","PowerFlex755.Val_LastFaultCode","STRING", 250, 3600, plc_type="CLX", map_={ 0: "No Fault", 2: "Auxiliary Input", 3: "Power Loss", 4: "UnderVoltage", 5: "OverVoltage", 7: "Motor Overload", 8: "Heatsink OverTemp", 9: "Thermister OverTemp", 10: "Dynamic Brake OverTemp", 12: "Hardware OverCurrent", 13: "Ground Fault", 14: "Ground Warning", 15: "Load Loss", 17: "Input Phase Loss", 18: "Motor PTC Trip", 19: "Task Overrun", 20: "Torque Prove Speed Band", 21: "Output Phase Loss", 24: "Decel Inhibit", 25: "OverSpeed Limit", 26: "Brake Slipped", 27: "Torque Prove Conflict", 28: "TP Encls Confict", 29: "Analog In Loss", 33: "Auto Restarts Exhausted", 35: "IPM OverCurrent", 36: "SW OverCurrent", 38: "Phase U to Ground", 39: "Phase V to Ground", 40: "Phase W to Ground", 41: "Phase UV Short", 42: "Phase VW Short", 43: "Phase WU Short", 44: "Phase UNeg to Ground", 45: "Phase VNeg to Ground", 46: "Phase WNeg to Ground", 48: "System Defaulted", 49: "Drive Powerup", 51: "Clear Fault Queue", 55: "Control Board Overtemp", 59: "Invalid Code", 61: "Shear Pin 1", 62: "Shear Pin 2", 64: "Drive Overload", 66: "OW Torque Level", 67: "Pump Off", 71: "Port 1 Adapter", 72: "Port 2 Adapter", 73: "Port 3 Adapter", 74: "Port 4 Adapter", 75: "Port 5 Adapter", 76: "Port 6 Adapter", 77: "IR Volts Range", 78: "FluxAmps Ref Range", 79: "Excessive Load", 80: "AutoTune Aborted", 81: "Port 1 DPI Loss", 82: "Port 2 DPI Loss", 83: "Port 3 DPI Loss", 84: "Port 4 DPI Loss", 85: "Port 5 DPI Loss", 86: "Port 6 DPI Loss", 87: "IXo Voltage Range", 91: "Primary Velocity Feedback Loss", 93: "Hardware Enable Check", 94: "Alternate Velocity Feedback Loss", 95: "Auxiliary Velocity Feedback Loss", 96: "Position Feedback Loss", 97: "Auto Tach Switch", 100: "Parameter Checksum", 101: "Power Down NVS Blank", 102: "NVS Not Blank", 103: "Power Down NVS Incompatible", 104: "Power Board Checksum", 106: "Incompat MCB-PB", 107: "Replaced MCB-PB", 108: "Analog Calibration Checksum", 110: "Invalid Power Board Data", 111: "Power Board Invalid ID", 112: "Power Board App Min Version", 113: "Tracking DataError", 115: "Power Down Table Full", 116: "Power Down Entry Too Large", 117: "Power Down Data Checksum", 118: "Power Board Power Down Checksum", 124: "App ID Changed", 125: "Using Backup App", 134: "Start on Power Up", 137: "External Precharge Error", 138: "Precharge Open", 141: "Autotune Enc Angle", 142: "Autotune Speed Restricted", 143: "Autotune Current Regulator", 144: "Autotune Inertia", 145: "Autotune Travel", 13035: "Net IO Timeout", 13037: "Net IO Timeout" }),
|
||||
PLCChannel(PLC_IP_ADDRESS["b2"], "b2_vfd_current_fault","sts_CurrentVFDFaultCode","STRING", 250, 3600, plc_type="CLX", map_={ 0: "No Fault", 2: "Auxiliary Input", 3: "Power Loss", 4: "UnderVoltage", 5: "OverVoltage", 7: "Motor Overload", 8: "Heatsink OverTemp", 9: "Thermister OverTemp", 10: "Dynamic Brake OverTemp", 12: "Hardware OverCurrent", 13: "Ground Fault", 14: "Ground Warning", 15: "Load Loss", 17: "Input Phase Loss", 18: "Motor PTC Trip", 19: "Task Overrun", 20: "Torque Prove Speed Band", 21: "Output Phase Loss", 24: "Decel Inhibit", 25: "OverSpeed Limit", 26: "Brake Slipped", 27: "Torque Prove Conflict", 28: "TP Encls Confict", 29: "Analog In Loss", 33: "Auto Restarts Exhausted", 35: "IPM OverCurrent", 36: "SW OverCurrent", 38: "Phase U to Ground", 39: "Phase V to Ground", 40: "Phase W to Ground", 41: "Phase UV Short", 42: "Phase VW Short", 43: "Phase WU Short", 44: "Phase UNeg to Ground", 45: "Phase VNeg to Ground", 46: "Phase WNeg to Ground", 48: "System Defaulted", 49: "Drive Powerup", 51: "Clear Fault Queue", 55: "Control Board Overtemp", 59: "Invalid Code", 61: "Shear Pin 1", 62: "Shear Pin 2", 64: "Drive Overload", 66: "OW Torque Level", 67: "Pump Off", 71: "Port 1 Adapter", 72: "Port 2 Adapter", 73: "Port 3 Adapter", 74: "Port 4 Adapter", 75: "Port 5 Adapter", 76: "Port 6 Adapter", 77: "IR Volts Range", 78: "FluxAmps Ref Range", 79: "Excessive Load", 80: "AutoTune Aborted", 81: "Port 1 DPI Loss", 82: "Port 2 DPI Loss", 83: "Port 3 DPI Loss", 84: "Port 4 DPI Loss", 85: "Port 5 DPI Loss", 86: "Port 6 DPI Loss", 87: "IXo Voltage Range", 91: "Primary Velocity Feedback Loss", 93: "Hardware Enable Check", 94: "Alternate Velocity Feedback Loss", 95: "Auxiliary Velocity Feedback Loss", 96: "Position Feedback Loss", 97: "Auto Tach Switch", 100: "Parameter Checksum", 101: "Power Down NVS Blank", 102: "NVS Not Blank", 103: "Power Down NVS Incompatible", 104: "Power Board Checksum", 106: "Incompat MCB-PB", 107: "Replaced MCB-PB", 108: "Analog Calibration Checksum", 110: "Invalid Power Board Data", 111: "Power Board Invalid ID", 112: "Power Board App Min Version", 113: "Tracking DataError", 115: "Power Down Table Full", 116: "Power Down Entry Too Large", 117: "Power Down Data Checksum", 118: "Power Board Power Down Checksum", 124: "App ID Changed", 125: "Using Backup App", 134: "Start on Power Up", 137: "External Precharge Error", 138: "Precharge Open", 141: "Autotune Enc Angle", 142: "Autotune Speed Restricted", 143: "Autotune Current Regulator", 144: "Autotune Inertia", 145: "Autotune Travel", 13035: "Net IO Timeout", 13037: "Net IO Timeout" }),
|
||||
PLCChannel(PLC_IP_ADDRESS["b2"], "b2_io_fault","ControllerFault_IO","STRING", 250, 3600, plc_type="CLX", map_={0: "No Fault", 1: "Faulted"}),
|
||||
PLCChannel(PLC_IP_ADDRESS["b2"], "b2_program_fault","ControllerFault_Program","STRING", 250, 3600, plc_type="CLX", map_={0: "No Fault", 1: "Faulted"}),
|
||||
PLCChannel(PLC_IP_ADDRESS["b2"], "b2_min_speed","PowerFlex755.Cfg_MinSpdRef","REAL", 250, 3600, plc_type="CLX"),
|
||||
PLCChannel(PLC_IP_ADDRESS["b2"], "b2_max_speed","PowerFlex755.Cfg_MaxSpdRef","REAL", 250, 3600, plc_type="CLX"),
|
||||
PLCChannel(PLC_IP_ADDRESS["vs1"], "vs1_pressure","PT_Scaled","REAL", 250, 3600, plc_type="Micro800"),
|
||||
PLCChannel(PLC_IP_ADDRESS["vs1"], "vs1_spt_hi_pressure","PT_High_Alarm_SP","REAL", 250, 3600, plc_type="Micro800"),
|
||||
PLCChannel(PLC_IP_ADDRESS["vs1"], "vs1_spt_lo_pressure","PT_Low_Alarm_SP","REAL", 250, 3600, plc_type="Micro800"),
|
||||
PLCChannel(PLC_IP_ADDRESS["vs1"], "vs1_alm_hi_pressure","PT_High_Alarm","STRING", 0, 3600, plc_type="Micro800", map_={0: "OK", 1: "Alarmed"}),
|
||||
PLCChannel(PLC_IP_ADDRESS["vs1"], "vs1_alm_lo_pressure","PT_Low_Alarm","STRING", 0, 3600, plc_type="Micro800", map_={0: "OK", 1: "Alarmed"}),
|
||||
PLCChannel(PLC_IP_ADDRESS["vs1"], "vs1_flow_rate","FM_FR","REAL", 250, 3600, plc_type="Micro800"),
|
||||
PLCChannel(PLC_IP_ADDRESS["vs1"], "vs1_spt_hi_flow","FM_High_Alarm_SP","REAL", 250, 3600, plc_type="Micro800"),
|
||||
PLCChannel(PLC_IP_ADDRESS["vs1"], "vs1_spt_lo_flow","FM_Low_Alarm_SP","REAL", 250, 3600, plc_type="Micro800"),
|
||||
PLCChannel(PLC_IP_ADDRESS["vs1"], "vs1_alm_hi_flow","FM_High_Alarm","STRING", 0, 3600, plc_type="Micro800", map_={0: "OK", 1: "Alarmed"}),
|
||||
PLCChannel(PLC_IP_ADDRESS["vs1"], "vs1_alm_lo_flow","FM_Low_Alarm","STRING", 0, 3600, plc_type="Micro800", map_={0: "OK", 1: "Alarmed"}),
|
||||
PLCChannel(PLC_IP_ADDRESS["vs1"], "vs1_flow_today","FM_TodayTotal","REAL", 250, 3600, plc_type="Micro800"),
|
||||
PLCChannel(PLC_IP_ADDRESS["vs1"], "vs1_flow_yesterday","FM_YesterdayTotal","REAL", 250, 3600, plc_type="Micro800"),
|
||||
PLCChannel(PLC_IP_ADDRESS["vs1"], "vs1_flow_month","FM_MonthTotal","REAL", 250, 3600, plc_type="Micro800"),
|
||||
PLCChannel(PLC_IP_ADDRESS["vs1"], "vs1_flow_last_month","FM_LastMonthTotal","REAL", 250, 3600, plc_type="Micro800"),
|
||||
PLCChannel(PLC_IP_ADDRESS["vs1"], "vs1_valve_status","ValveStatusOpen","BOOL", 0, 3600, plc_type="Micro800", map_={0: "Closed", 1: "Open"}),
|
||||
PLCChannel(PLC_IP_ADDRESS["vs1"], "vs1_alm_close","ValveCloseAlarm","STRING", 0, 3600, plc_type="Micro800", map_={0: "OK", 1: "Alarmed"}),
|
||||
PLCChannel(PLC_IP_ADDRESS["vs1"], "vs1_alm_status_failed","ValveStatusFailed","STRING", 0, 3600, plc_type="Micro800", map_={0: "OK", 1: "Failed"}),
|
||||
PLCChannel(PLC_IP_ADDRESS["vs1"], "vs1_valve_permissive","ValveOpenPermissive","BOOL", 0, 3600, plc_type="Micro800", map_={0: "Blocked", 1: "OK"}),
|
||||
PLCChannel(PLC_IP_ADDRESS["vs1"], "vs1_alm_plc_halt","PLC_Halt","STRING", 0, 3600, plc_type="Micro800", map_={0: "OK", 1: "Halted"}),
|
||||
PLCChannel(PLC_IP_ADDRESS["swd1"], "swd1_shut_frm_vs","ShutDownFromValveStation","STRING", 0, 3600, plc_type="Micro800", map_={0: "OK", 1: "Alarmed"}),
|
||||
PLCChannel(PLC_IP_ADDRESS["swd1"], "swd1_shut_frm_b","ShutDownFromBooster","STRING", 0, 3600, plc_type="Micro800", map_={0: "OK", 1: "Alarmed"}),
|
||||
PLCChannel(PLC_IP_ADDRESS["swd1"], "swd1_plc_halt","PLC_Halt","STRING", 0, 3600, plc_type="Micro800", map_={0: "OK", 1: "Alarmed"})
|
||||
]
|
||||
14
swdcontroller/config.txt
Normal file
14
swdcontroller/config.txt
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"files": {
|
||||
"file3": "file_logger.py",
|
||||
"file2": "Channel.py",
|
||||
"file1": "swdcontroller.py",
|
||||
"file6": "persistence.py",
|
||||
"file5": "utilities.py",
|
||||
"file4": "Tags.py"
|
||||
},
|
||||
"deviceName": "swdcontroller",
|
||||
"releaseVersion": "1",
|
||||
"driverFileName": "swdcontroller.py",
|
||||
"driverId": "0100"
|
||||
}
|
||||
360
swdcontroller/device_base.py
Normal file
360
swdcontroller/device_base.py
Normal 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)))
|
||||
|
||||
|
||||
|
||||
|
||||
18
swdcontroller/file_logger.py
Normal file
18
swdcontroller/file_logger.py
Normal file
@@ -0,0 +1,18 @@
|
||||
"""Logging setup for swdcontroller"""
|
||||
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 = './swdcontroller.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('swdcontroller')
|
||||
filelogger.setLevel(logging.INFO)
|
||||
filelogger.addHandler(my_handler)
|
||||
|
||||
console_out = logging.StreamHandler(sys.stdout)
|
||||
console_out.setFormatter(log_formatter)
|
||||
filelogger.addHandler(console_out)
|
||||
21
swdcontroller/persistence.py
Normal file
21
swdcontroller/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
|
||||
435
swdcontroller/swdcontroller.py
Normal file
435
swdcontroller/swdcontroller.py
Normal file
@@ -0,0 +1,435 @@
|
||||
"""Driver for swdcontroller"""
|
||||
|
||||
import threading
|
||||
import json
|
||||
import time
|
||||
from random import randint
|
||||
import os
|
||||
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
|
||||
from file_logger import filelogger as log
|
||||
# PERSISTENCE FILE
|
||||
PERSIST = persistence.load('persist.json')
|
||||
if not PERSIST:
|
||||
PERSIST = {"b1":"192.168.1.10", "b2":"192.168.1.20", "vs1": "192.168.1.14", "swd1":"192.168.1.15"}
|
||||
persistence.store(PERSIST, 'persist.json')
|
||||
PLC_IP_ADDRESS = PERSIST
|
||||
from Tags import tags
|
||||
|
||||
_ = None
|
||||
|
||||
log.info("swdcontroller startup")
|
||||
|
||||
# GLOBAL VARIABLES
|
||||
WAIT_FOR_CONNECTION_SECONDS = 20
|
||||
IP_CHECK_PERIOD = 60
|
||||
|
||||
|
||||
CHANNELS = tags
|
||||
|
||||
# PERSISTENCE FILE
|
||||
PERSIST = persistence.load()
|
||||
|
||||
|
||||
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 = "1"
|
||||
self.finished = threading.Event()
|
||||
self.force_send = False
|
||||
self.public_ip_address = ""
|
||||
self.public_ip_address_last_checked = 0
|
||||
self.plc_ping_status = {"b1": "", "b2": "", "vs1":"", "swd1": ""}
|
||||
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("swdcontroller driver will start in {} seconds".format(WAIT_FOR_CONNECTION_SECONDS - i))
|
||||
time.sleep(1)
|
||||
log.info("BOOM! Starting swdcontroller driver...")
|
||||
|
||||
self._check_ip_address()
|
||||
|
||||
self.nodes["swdcontroller_0199"] = self
|
||||
|
||||
send_loops = 0
|
||||
|
||||
while True:
|
||||
now = time.time()
|
||||
if self.force_send:
|
||||
log.warning("FORCE SEND: TRUE")
|
||||
|
||||
for chan in CHANNELS:
|
||||
val = chan.read()
|
||||
if chan.check(val, self.force_send):
|
||||
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'swdcontroller')
|
||||
time.sleep(TAG_DATAERROR_SLEEPTIME) # sleep to allow Micro800 to handle ENET requests
|
||||
|
||||
# print("swdcontroller driver still alive...")
|
||||
if self.force_send:
|
||||
if send_loops > 2:
|
||||
log.warning("Turning off force_send")
|
||||
self.force_send = False
|
||||
send_loops = 0
|
||||
else:
|
||||
send_loops += 1
|
||||
|
||||
|
||||
if (now - self.public_ip_address_last_checked) > IP_CHECK_PERIOD:
|
||||
self._check_ip_address()
|
||||
self._check_devices()
|
||||
|
||||
|
||||
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, 'swdcontroller')
|
||||
self.public_ip_address = test_public_ip
|
||||
hostname = "google.com"
|
||||
response = os.system("ping -c 1 " + hostname)
|
||||
|
||||
#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:
|
||||
log.info("Rebooting because no internet detected")
|
||||
os.system('reboot')
|
||||
|
||||
def _check_devices(self):
|
||||
name = {
|
||||
"b1": "Booster #1",
|
||||
"b2": "Booster #2",
|
||||
"vs1": "Valve Station",
|
||||
"swd1": "SWD"
|
||||
}
|
||||
for device in PLC_IP_ADDRESS:
|
||||
try:
|
||||
plc_ping = os.system("ping -c 1 " + PLC_IP_ADDRESS[device] + " > /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[device] == "OK":
|
||||
self.sendtodbDev(1, device + "_ping","OK", 0, 'swdcontroller')
|
||||
self.plc_ping_status[device] = "OK"
|
||||
else:
|
||||
if not self.plc_ping_status[device] == "Comms Error to PLC":
|
||||
self.sendtodbDev(1, device + '_ping', "Comms Error to " + name[device],0, 'swdcontroller')
|
||||
self.plc_ping_status[device] = 'Comms Error to PLC'
|
||||
|
||||
def swdcontroller_sync(self, name, value):
|
||||
"""Sync all data from the driver."""
|
||||
self.force_send = True
|
||||
# self.sendtodb("log", "synced", 0)
|
||||
return True
|
||||
|
||||
def swdcontroller_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="CLX")
|
||||
print("Result of swdcontroller_writeplctag(self, {}, {}) = {}".format(name, value, write_res))
|
||||
if write_res is None:
|
||||
write_res = "Error writing to PLC..."
|
||||
return write_res
|
||||
|
||||
def swdcontroller_b1_cmd_start(self, name, value):
|
||||
write_res = write_tag(str(PLC_IP_ADDRESS["b1"]), "cmd_Start", 1, plc_type="CLX")
|
||||
print("Result of swdcontroller_b1_start(self, {}, {}) = {}".format(name, value, write_res))
|
||||
if write_res is None:
|
||||
write_res = "Error writing to PLC..."
|
||||
return write_res
|
||||
|
||||
def swdcontroller_b1_cmd_stop(self, name, value):
|
||||
write_res = write_tag(str(PLC_IP_ADDRESS["b1"]), "cmd_Stop", 1, plc_type="CLX")
|
||||
print("Result of swdcontroller_b1_stop(self, {}, {}) = {}".format(name, value, write_res))
|
||||
if write_res is None:
|
||||
write_res = "Error writing to PLC..."
|
||||
return write_res
|
||||
|
||||
def swdcontroller_b1_spt_pid_manual(self,name,value):
|
||||
value = float(value)
|
||||
if 0.0 < value < 100.0:
|
||||
write_res = write_tag(str(PLC_IP_ADDRESS["b1"]), "cfg_PID_ManualSP", value, plc_type="CLX")
|
||||
print("Result of swdcontroller_b1_spt_manual(self, {}, {}) = {}".format(name, value, write_res))
|
||||
if write_res is None:
|
||||
write_res = "Error writing to PLC..."
|
||||
for chan in CHANNELS:
|
||||
if chan.mesh_name == "b1_spt_pid_manual":
|
||||
val = value
|
||||
if chan.check(val, True):
|
||||
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'swdcontroller')
|
||||
else:
|
||||
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'swdcontroller')
|
||||
return write_res
|
||||
|
||||
def swdcontroller_b1_spt_pid_discharge(self,name,value):
|
||||
value = float(value)
|
||||
if 0.0 < value < 300.0:
|
||||
write_res = write_tag(str(PLC_IP_ADDRESS["b1"]), "cfg_PID_DischargePressureSP", value, plc_type="CLX")
|
||||
print("Result of swdcontroller_b1_spt_discharge(self, {}, {}) = {}".format(name, value, write_res))
|
||||
if write_res is None:
|
||||
write_res = "Error writing to PLC..."
|
||||
for chan in CHANNELS:
|
||||
if chan.mesh_name == "b1_spt_pid_discharge":
|
||||
val = value
|
||||
if chan.check(val, True):
|
||||
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'swdcontroller')
|
||||
else:
|
||||
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'swdcontroller')
|
||||
return write_res
|
||||
|
||||
def swdcontroller_b1_spt_pid_suction(self,name,value):
|
||||
value = float(value)
|
||||
if 0.0 < value < 100.0:
|
||||
write_res = write_tag(str(PLC_IP_ADDRESS["b1"]), "cfg_PID_SuctionPressureSP", value, plc_type="CLX")
|
||||
print("Result of swdcontroller_b1_spt_suction(self, {}, {}) = {}".format(name, value, write_res))
|
||||
if write_res is None:
|
||||
write_res = "Error writing to PLC..."
|
||||
for chan in CHANNELS:
|
||||
if chan.mesh_name == "b1_spt_pid_suction":
|
||||
val = value
|
||||
if chan.check(val, True):
|
||||
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'swdcontroller')
|
||||
else:
|
||||
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'swdcontroller')
|
||||
return write_res
|
||||
|
||||
def swdcontroller_b1pidmanual(self,name,value):
|
||||
write_res = write_tag(str(PLC_IP_ADDRESS["b1"]), "cfg_PID_Manual", 1, plc_type="CLX")
|
||||
print("Result of swdcontroller_b1_pid_manual(self, {}, {}) = {}".format(name, value, write_res))
|
||||
if write_res is None:
|
||||
write_res = "Error writing to PLC..."
|
||||
return write_res
|
||||
|
||||
def swdcontroller_b1piddischarge(self,name,value):
|
||||
write_res = write_tag(str(PLC_IP_ADDRESS["b1"]), "cfg_PID_DischargePressure", 1, plc_type="CLX")
|
||||
print("Result of swdcontroller_b1_pid_discharge(self, {}, {}) = {}".format(name, value, write_res))
|
||||
if write_res is None:
|
||||
write_res = "Error writing to PLC..."
|
||||
return write_res
|
||||
|
||||
def swdcontroller_b1pidsuction(self,name,value):
|
||||
write_res = write_tag(str(PLC_IP_ADDRESS["b1"]), "cfg_PID_SuctionPressure", 1, plc_type="CLX")
|
||||
print("Result of swdcontroller_b1_pid_suction(self, {}, {}) = {}".format(name, value, write_res))
|
||||
if write_res is None:
|
||||
write_res = "Error writing to PLC..."
|
||||
return write_res
|
||||
|
||||
def swdcontroller_b1_pid_control(self, name, value):
|
||||
resp = False
|
||||
if value == "manual":
|
||||
resp = self.swdcontroller_b1pidmanual(name, value)
|
||||
elif value == "discharge":
|
||||
resp = self.swdcontroller_b1piddischarge(name, value)
|
||||
elif value == "suction":
|
||||
resp = self.swdcontroller_b1pidsuction(name, value)
|
||||
else:
|
||||
return False
|
||||
demap = {"suction": 0, "discharge": 1, "manual": 2}
|
||||
for chan in CHANNELS:
|
||||
if chan.mesh_name == "b1_pid_control":
|
||||
val = demap[value]
|
||||
if chan.check(val, True):
|
||||
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'swdcontroller')
|
||||
else:
|
||||
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'swdcontroller')
|
||||
return resp
|
||||
|
||||
def swdcontroller_b2_cmd_start(self, name, value):
|
||||
write_res = write_tag(str(PLC_IP_ADDRESS["b2"]), "cmd_Start", 1, plc_type="CLX")
|
||||
print("Result of swdcontroller_b2_start(self, {}, {}) = {}".format(name, value, write_res))
|
||||
if write_res is None:
|
||||
write_res = "Error writing to PLC..."
|
||||
return write_res
|
||||
|
||||
def swdcontroller_b2_cmd_stop(self, name, value):
|
||||
write_res = write_tag(str(PLC_IP_ADDRESS["b2"]), "cmd_Stop", 1, plc_type="CLX")
|
||||
print("Result of swdcontroller_b2_stop(self, {}, {}) = {}".format(name, value, write_res))
|
||||
if write_res is None:
|
||||
write_res = "Error writing to PLC..."
|
||||
return write_res
|
||||
|
||||
def swdcontroller_b2_spt_pid_manual(self,name,value):
|
||||
value = float(value)
|
||||
if 0.0 < value < 100.0:
|
||||
write_res = write_tag(str(PLC_IP_ADDRESS["b2"]), "cfg_PID_ManualSP", value, plc_type="CLX")
|
||||
print("Result of swdcontroller_b2_spt_manual(self, {}, {}) = {}".format(name, value, write_res))
|
||||
if write_res is None:
|
||||
write_res = "Error writing to PLC..."
|
||||
for chan in CHANNELS:
|
||||
if chan.mesh_name == "b2_spt_pid_manual":
|
||||
val = value
|
||||
if chan.check(val, True):
|
||||
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'swdcontroller')
|
||||
else:
|
||||
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'swdcontroller')
|
||||
return write_res
|
||||
|
||||
def swdcontroller_b2_spt_pid_discharge(self,name,value):
|
||||
value = float(value)
|
||||
if 0.0 < value < 300.0:
|
||||
write_res = write_tag(str(PLC_IP_ADDRESS["b2"]), "cfg_PID_DischargePressureSP", value, plc_type="CLX")
|
||||
print("Result of swdcontroller_b2_spt_discharge(self, {}, {}) = {}".format(name, value, write_res))
|
||||
if write_res is None:
|
||||
write_res = "Error writing to PLC..."
|
||||
for chan in CHANNELS:
|
||||
if chan.mesh_name == "b2_spt_pid_discharge":
|
||||
val = value
|
||||
if chan.check(val, True):
|
||||
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'swdcontroller')
|
||||
else:
|
||||
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'swdcontroller')
|
||||
return write_res
|
||||
|
||||
def swdcontroller_b2_spt_pid_suction(self,name,value):
|
||||
value = float(value)
|
||||
if 0.0 < value < 100.0:
|
||||
write_res = write_tag(str(PLC_IP_ADDRESS["b2"]), "cfg_PID_SuctionPressureSP", value, plc_type="CLX")
|
||||
print("Result of swdcontroller_b2_spt_suction(self, {}, {}) = {}".format(name, value, write_res))
|
||||
if write_res is None:
|
||||
write_res = "Error writing to PLC..."
|
||||
for chan in CHANNELS:
|
||||
if chan.mesh_name == "b2_spt_pid_suction":
|
||||
val = value
|
||||
if chan.check(val, True):
|
||||
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'swdcontroller')
|
||||
else:
|
||||
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'swdcontroller')
|
||||
return write_res
|
||||
|
||||
def swdcontroller_b2pidmanual(self,name,value):
|
||||
write_res = write_tag(str(PLC_IP_ADDRESS["b2"]), "cfg_PID_Manual", 1, plc_type="CLX")
|
||||
print("Result of swdcontroller_b2_pid_manual(self, {}, {}) = {}".format(name, value, write_res))
|
||||
if write_res is None:
|
||||
write_res = "Error writing to PLC..."
|
||||
return write_res
|
||||
|
||||
def swdcontroller_b2piddischarge(self,name,value):
|
||||
write_res = write_tag(str(PLC_IP_ADDRESS["b2"]), "cfg_PID_DischargePressure", 1, plc_type="CLX")
|
||||
print("Result of swdcontroller_b2_pid_discharge(self, {}, {}) = {}".format(name, value, write_res))
|
||||
if write_res is None:
|
||||
write_res = "Error writing to PLC..."
|
||||
return write_res
|
||||
|
||||
def swdcontroller_b2pidsuction(self,name,value):
|
||||
write_res = write_tag(str(PLC_IP_ADDRESS["b2"]), "cfg_PID_SuctionPressure", 1, plc_type="CLX")
|
||||
print("Result of swdcontroller_b2_pid_suction(self, {}, {}) = {}".format(name, value, write_res))
|
||||
if write_res is None:
|
||||
write_res = "Error writing to PLC..."
|
||||
return write_res
|
||||
|
||||
def swdcontroller_b2_pid_control(self, name, value):
|
||||
resp = False
|
||||
if value == "manual":
|
||||
resp = self.swdcontroller_b2pidmanual(name, value)
|
||||
elif value == "discharge":
|
||||
resp = self.swdcontroller_b2piddischarge(name, value)
|
||||
elif value == "suction":
|
||||
resp = self.swdcontroller_b2pidsuction(name, value)
|
||||
else:
|
||||
return False
|
||||
demap = {"suction": 0, "discharge": 1, "manual": 2}
|
||||
for chan in CHANNELS:
|
||||
if chan.mesh_name == "b2_pid_control":
|
||||
val = demap[value]
|
||||
if chan.check(val, True):
|
||||
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'swdcontroller')
|
||||
else:
|
||||
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'swdcontroller')
|
||||
return resp
|
||||
|
||||
def swdcontroller_vs1_spt_hi_pressure(self,name,value):
|
||||
value = float(value)
|
||||
if 0.0 < value < 200.0:
|
||||
write_res = write_tag(str(PLC_IP_ADDRESS["vs1"]), "PT_High_Alarm_SP", value, plc_type="Micro800")
|
||||
print("Result of swdcontroller_vs1_hi_pressure(self, {}, {}) = {}".format(name, value, write_res))
|
||||
if write_res is None:
|
||||
write_res = "Error writing to PLC..."
|
||||
for chan in CHANNELS:
|
||||
if chan.mesh_name == "vs1_spt_hi_pressure":
|
||||
val = value
|
||||
if chan.check(val, True):
|
||||
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'swdcontroller')
|
||||
else:
|
||||
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'swdcontroller')
|
||||
return write_res
|
||||
|
||||
def swdcontroller_vs1_spt_lo_pressure(self,name,value):
|
||||
value = float(value)
|
||||
if 0.0 < value < 200.0:
|
||||
write_res = write_tag(str(PLC_IP_ADDRESS["vs1"]), "PT_Low_Alarm_SP", value, plc_type="Micro800")
|
||||
print("Result of swdcontroller_vs1_lo_pressure(self, {}, {}) = {}".format(name, value, write_res))
|
||||
if write_res is None:
|
||||
write_res = "Error writing to PLC..."
|
||||
for chan in CHANNELS:
|
||||
if chan.mesh_name == "vs1_spt_lo_pressure":
|
||||
val = value
|
||||
if chan.check(val, True):
|
||||
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'swdcontroller')
|
||||
else:
|
||||
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'swdcontroller')
|
||||
return write_res
|
||||
|
||||
def swdcontroller_vs1_spt_hi_flow(self,name,value):
|
||||
value = float(value)
|
||||
if 0.0 < value < 1500.0:
|
||||
write_res = write_tag(str(PLC_IP_ADDRESS["vs1"]), "FM_High_Alarm_SP", value, plc_type="Micro800")
|
||||
print("Result of swdcontroller_vs1_hi_flow(self, {}, {}) = {}".format(name, value, write_res))
|
||||
if write_res is None:
|
||||
write_res = "Error writing to PLC..."
|
||||
for chan in CHANNELS:
|
||||
if chan.mesh_name == "vs1_spt_hi_flow":
|
||||
val = value
|
||||
if chan.check(val, True):
|
||||
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'swdcontroller')
|
||||
else:
|
||||
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'swdcontroller')
|
||||
return write_res
|
||||
|
||||
def swdcontroller_vs1_spt_lo_flow(self,name,value):
|
||||
value = float(value)
|
||||
if 0.0 < value < 1500.0:
|
||||
write_res = write_tag(str(PLC_IP_ADDRESS["vs1"]), "FM_Low_Alarm_SP", value, plc_type="Micro800")
|
||||
print("Result of swdcontroller_vs1_lo_flow(self, {}, {}) = {}".format(name, value, write_res))
|
||||
if write_res is None:
|
||||
write_res = "Error writing to PLC..."
|
||||
for chan in CHANNELS:
|
||||
if chan.mesh_name == "vs1_spt_lo_flow":
|
||||
val = value
|
||||
if chan.check(val, True):
|
||||
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'swdcontroller')
|
||||
else:
|
||||
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'swdcontroller')
|
||||
return write_res
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
64
swdcontroller/utilities.py
Normal file
64
swdcontroller/utilities.py
Normal 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."""
|
||||
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()[:-1]
|
||||
except Exception as e:
|
||||
print("Could not resolve address: {}".format(e))
|
||||
return ip_address
|
||||
return ip_address
|
||||
|
||||
|
||||
|
||||
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
|
||||
@@ -103,7 +103,7 @@ class start(threading.Thread, deviceBase):
|
||||
val = chan.read()
|
||||
if chan.mesh_name == "total_in_flowrate":
|
||||
val = sum(self.flowrates)
|
||||
if chan.check(val, self.force_send):
|
||||
if chan.check(val, self.force_send) or self.check_new_day(chan.mesh_name[:-9]):
|
||||
if chan.mesh_name in PERSIST["ignore_list"]:
|
||||
if "lifetime" in chan.mesh_name and chan.mesh_name not in ['forward_out_lifetime', 'reverse_out_lifetime', 'net_out_lifetime']:
|
||||
self.totalizer_null(chan.mesh_name[:-9])
|
||||
@@ -134,6 +134,12 @@ class start(threading.Thread, deviceBase):
|
||||
if (now - self.public_ip_address_last_checked) > IP_CHECK_PERIOD:
|
||||
self._check_ip_address()
|
||||
|
||||
def check_new_day(self, totalizer):
|
||||
right_now = dt.today()
|
||||
day = right_now.day
|
||||
if not(day == TOTALIZERS[totalizer]['Day']):
|
||||
return True
|
||||
return False
|
||||
|
||||
def _check_ip_address(self):
|
||||
"""Check the public IP address and send to Meshify if changed."""
|
||||
|
||||
Reference in New Issue
Block a user