Added Folders
Add all the driver folders
This commit is contained in:
211
transferstation/Channel.py
Normal file
211
transferstation/Channel.py
Normal file
@@ -0,0 +1,211 @@
|
||||
"""Define Meshify channel class."""
|
||||
from pycomm.ab_comm.clx import Driver as ClxDriver
|
||||
from pycomm.cip.cip_base import CommError, DataError
|
||||
import time
|
||||
|
||||
|
||||
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):
|
||||
"""Read a tag from the PLC."""
|
||||
c = ClxDriver()
|
||||
try:
|
||||
if c.open(addr):
|
||||
try:
|
||||
v = c.read_tag(tag)
|
||||
return v
|
||||
except DataError:
|
||||
c.close()
|
||||
print("Data Error during readTag({}, {})".format(addr, tag))
|
||||
except CommError:
|
||||
# err = c.get_status()
|
||||
c.close()
|
||||
print("Could not connect during readTag({}, {})".format(addr, tag))
|
||||
# print err
|
||||
except AttributeError as e:
|
||||
c.close()
|
||||
print("AttributeError during readTag({}, {}): \n{}".format(addr, tag, e))
|
||||
c.close()
|
||||
return False
|
||||
|
||||
|
||||
def read_array(addr, tag, start, end):
|
||||
"""Read an array from the PLC."""
|
||||
c = ClxDriver()
|
||||
if c.open(addr):
|
||||
arr_vals = []
|
||||
try:
|
||||
for i in range(start, end):
|
||||
tag_w_index = tag + "[{}]".format(i)
|
||||
v = c.read_tag(tag_w_index)
|
||||
# print('{} - {}'.format(tag_w_index, v))
|
||||
arr_vals.append(round(v[0], 4))
|
||||
# print(v)
|
||||
if len(arr_vals) > 0:
|
||||
return arr_vals
|
||||
else:
|
||||
print("No length for {}".format(addr))
|
||||
return False
|
||||
except Exception:
|
||||
print("Error during readArray({}, {}, {}, {})".format(addr, tag, start, end))
|
||||
err = c.get_status()
|
||||
c.close()
|
||||
print err
|
||||
pass
|
||||
c.close()
|
||||
|
||||
|
||||
def write_tag(addr, tag, val):
|
||||
"""Write a tag value to the PLC."""
|
||||
c = ClxDriver()
|
||||
if c.open(addr):
|
||||
try:
|
||||
cv = c.read_tag(tag)
|
||||
wt = c.write_tag(tag, val, cv[1])
|
||||
return wt
|
||||
except Exception:
|
||||
print("Error during writeTag({}, {}, {})".format(addr, tag, val))
|
||||
err = c.get_status()
|
||||
c.close()
|
||||
print err
|
||||
c.close()
|
||||
|
||||
|
||||
class Channel:
|
||||
"""Holds the configuration for a Meshify channel."""
|
||||
|
||||
def __init__(self, ip, mesh_name, plc_tag, data_type, chg_threshold, guarantee_sec, map_=False, write_enabled=False):
|
||||
"""Initialize the channel."""
|
||||
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 __str__(self):
|
||||
"""Create a string for the channel."""
|
||||
return "{}: {}\nvalue: {}, last_send_time: {}".format(self.mesh_name, self.plc_tag, self.value, self.last_send_time)
|
||||
|
||||
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:
|
||||
v = read_tag(self.plc_ip, self.plc_tag)
|
||||
if v:
|
||||
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 not (self.value == v[0]):
|
||||
if self.map_:
|
||||
if not self.value == self.map_[v[0]]:
|
||||
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 - v[0]) > 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_[v[0]]
|
||||
except KeyError:
|
||||
print("Cannot find a map value for {} in {} for {}".format(v[0], self.map_, self.mesh_name))
|
||||
self.value = v[0]
|
||||
else:
|
||||
self.value = v[0]
|
||||
self.last_send_time = time.time()
|
||||
print("Sending {} for {} - {}".format(self.value, self.mesh_name, send_reason))
|
||||
return send_needed
|
||||
|
||||
|
||||
class BoolArrayChannels(Channel):
|
||||
"""Hold the configuration for a set of boolean array channels."""
|
||||
|
||||
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:
|
||||
print("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:
|
||||
v = read_tag(self.plc_ip, self.plc_tag)
|
||||
if v:
|
||||
bool_arr = binarray(v[0])
|
||||
new_val = {}
|
||||
for idx in self.map_:
|
||||
try:
|
||||
new_val[self.map_[idx]] = bool_arr[idx]
|
||||
except KeyError:
|
||||
print("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()
|
||||
print("Sending {} for {} - {}".format(self.value, self.mesh_name, send_reason))
|
||||
return send_needed
|
||||
33
transferstation/Maps.py
Normal file
33
transferstation/Maps.py
Normal file
@@ -0,0 +1,33 @@
|
||||
"""Holds map values for advvfdipp."""
|
||||
|
||||
transferstation_map = {
|
||||
|
||||
'alarm': {0: "OK", 1: "Alarmed"},
|
||||
'lockout': {0: "OK", 1: "Locked Out"},
|
||||
'enable_disable': {0: "Disabled", 1: "Enabled"},
|
||||
'run': {0: "Stopped", 1: "Running"},
|
||||
'bit_channels': {
|
||||
'system_enabled': {
|
||||
1: 'system1_enabled',
|
||||
2: 'system2_enabled',
|
||||
3: 'system3_enabled'
|
||||
},
|
||||
'ft_enabled': {
|
||||
0: 'ft01_enabled',
|
||||
1: 'ft11_enabled',
|
||||
2: 'ft21_enabled',
|
||||
3: 'ft31_enabled'
|
||||
},
|
||||
'lt_enabled': {
|
||||
0: 'lt01_enabled',
|
||||
1: 'lt11_enabled',
|
||||
2: 'lt21_enabled',
|
||||
3: 'lt31_enabled'
|
||||
},
|
||||
'ptx2_enabled': {
|
||||
1: 'pt12_enabled',
|
||||
2: 'pt22_enabled',
|
||||
3: 'pt32_enabled'
|
||||
}
|
||||
}
|
||||
}
|
||||
61
transferstation/Scheduler.py
Normal file
61
transferstation/Scheduler.py
Normal file
@@ -0,0 +1,61 @@
|
||||
"""Hold scheduler classes and functions."""
|
||||
import time
|
||||
from Channel import Channel
|
||||
from Maps import transferstation_map as maps
|
||||
_ = None
|
||||
|
||||
plc_ip_address = "192.168.1.10"
|
||||
|
||||
|
||||
class ScheduleRun:
|
||||
"""Hold config for a schedule history run."""
|
||||
|
||||
def __init__(self, index_, type_="Schedule"):
|
||||
"""Initialize the class."""
|
||||
self.index_ = index_
|
||||
self.json = False
|
||||
if type_ in ["Schedule", "History"]:
|
||||
self.type_ = type_
|
||||
else:
|
||||
self.type_ = "Schedule"
|
||||
print("SERIOUS ERROR! {} IS NOT A VALID TYPE FOR ScheduleRun with Index = {}".format(type_, index_))
|
||||
self.channels = [
|
||||
Channel(plc_ip_address, "sch_{}_id{}".format(self.type_, self.index_),
|
||||
"sch_Run{}[{}].id".format(self.type_, self.index_), "DINT", 0.5, 3600),
|
||||
Channel(plc_ip_address, "sch_{}_controlmode{}".format(self.type_, self.index_),
|
||||
"sch_Run{}[{}].controlmode".format(self.type_, self.index_), "STRING", _, 3600, map_=maps['pid_controlmode']),
|
||||
Channel(plc_ip_address, "sch_{}_controlsp{}".format(self.type_, self.index_),
|
||||
"sch_Run{}[{}].controlSetpoint".format(self.type_, self.index_), "REAL", 0.5, 3600),
|
||||
Channel(plc_ip_address, "sch_{}_complparam{}".format(self.type_, self.index_),
|
||||
"sch_Run{}[{}].completionParameter".format(self.type_, self.index_), "STRING", _, 3600, map_=maps['completion_parameter']),
|
||||
Channel(plc_ip_address, "sch_{}_complcomp{}".format(self.type_, self.index_),
|
||||
"sch_Run{}[{}].completionComparison".format(self.type_, self.index_), "STRING", _, 3600, map_=maps['completion_comparison']),
|
||||
Channel(plc_ip_address, "sch_{}_compltarget{}".format(self.type_, self.index_),
|
||||
"sch_Run{}[{}].completionValueTarget".format(self.type_, self.index_), "REAL", 0.5, 3600),
|
||||
Channel(plc_ip_address, "sch_{}_complactual{}".format(self.type_, self.index_),
|
||||
"sch_Run{}[{}].completionValueCurrent".format(self.type_, self.index_), "REAL", 10.0, 3600),
|
||||
Channel(plc_ip_address, "sch_{}_bbltotal{}".format(self.type_, self.index_),
|
||||
"sch_Run{}[{}].BBLTotal".format(self.type_, self.index_), "REAL", 10.0, 3600)
|
||||
]
|
||||
|
||||
def read(self, force_send=False):
|
||||
"""Read values of the schedule history from the PLC."""
|
||||
new_value = False
|
||||
for c in self.channels:
|
||||
if c.read(force_send):
|
||||
new_value = True
|
||||
return new_value
|
||||
|
||||
def jsonify(self):
|
||||
"""Give a JSON-ready object."""
|
||||
return {
|
||||
"id": self.channels[0].value,
|
||||
"control_mode": self.channels[1].value,
|
||||
"control_setpoint": self.channels[2].value,
|
||||
"completion_parameter": self.channels[3].value,
|
||||
"completion_comparison": self.channels[4].value,
|
||||
"completion_value_target": self.channels[5].value,
|
||||
"completion_value_actual": self.channels[6].value,
|
||||
"completion_bbl_total": self.channels[7].value,
|
||||
"timestamp": time.time()
|
||||
}
|
||||
15
transferstation/config.txt
Normal file
15
transferstation/config.txt
Normal file
@@ -0,0 +1,15 @@
|
||||
{
|
||||
|
||||
"driverFileName":"transferstation.py",
|
||||
"deviceName":"transferstation",
|
||||
"driverId":"0140",
|
||||
"releaseVersion":"3",
|
||||
"files": {
|
||||
"file1":"transferstation.py",
|
||||
"file2":"Channel.py",
|
||||
"file3":"Maps.py",
|
||||
"file4":"Scheduler.py",
|
||||
"file5":"modbusMap.p"
|
||||
}
|
||||
|
||||
}
|
||||
1652
transferstation/modbusMap.p
Normal file
1652
transferstation/modbusMap.p
Normal file
File diff suppressed because it is too large
Load Diff
139
transferstation/transferstation.py
Normal file
139
transferstation/transferstation.py
Normal file
@@ -0,0 +1,139 @@
|
||||
"""Driver for connecting Pond Level to Meshify."""
|
||||
|
||||
import threading
|
||||
from device_base import deviceBase
|
||||
from Channel import Channel, write_tag, BoolArrayChannels
|
||||
from Maps import transferstation_map as maps
|
||||
import json
|
||||
import time
|
||||
|
||||
_ = None
|
||||
|
||||
try:
|
||||
with open("persist.json", 'r') as persist_file:
|
||||
persist = json.load(persist_file)
|
||||
except Exception:
|
||||
persist = {}
|
||||
|
||||
try:
|
||||
persist['last_schedule_history']
|
||||
except KeyError:
|
||||
persist['last_schedule_history'] = {"id": -1}
|
||||
|
||||
_ = None
|
||||
|
||||
plc_ip_address = "192.168.1.10"
|
||||
|
||||
|
||||
def reverse_map(value, map_):
|
||||
"""Perform the opposite of mapping to an object."""
|
||||
for x in map_:
|
||||
if map_[x] == value:
|
||||
return x
|
||||
return None
|
||||
|
||||
|
||||
bit_channels = [
|
||||
BoolArrayChannels(plc_ip_address, 'systemx_enabled', "cfg_SystemEnabled", "BOOL", _, 60*60*60, map_=maps['bit_channels']['system_enabled']),
|
||||
BoolArrayChannels(plc_ip_address, 'ltx1_enabled', "cfg_SystemLTEnabled", "BOOL", _, 60*60*60, map_=maps['bit_channels']['lt_enabled']),
|
||||
BoolArrayChannels(plc_ip_address, 'ftx1_enabled', "cfg_SystemFTEnabled", "BOOL", _, 60*60*60, map_=maps['bit_channels']['ft_enabled']),
|
||||
BoolArrayChannels(plc_ip_address, 'ptx2_enabled', "cfg_SystemBPDischargePTEnabled", "BOOL", _, 60*60*60, map_=maps['bit_channels']['ptx2_enabled']),
|
||||
]
|
||||
|
||||
channels = [
|
||||
Channel(plc_ip_address, "lt01_level", "LTX1_PondLevel[0].Val", "REAL", 0.25, 3600),
|
||||
Channel(plc_ip_address, "lt11_level", "LTX1_PondLevel[1].Val", "REAL", 0.25, 3600),
|
||||
Channel(plc_ip_address, "lt21_level", "LTX1_PondLevel[2].Val", "REAL", 0.25, 3600),
|
||||
Channel(plc_ip_address, "lt31_level", "LTX1_PondLevel[3].Val", "REAL", 0.25, 3600),
|
||||
|
||||
Channel(plc_ip_address, "pt11_pressure", "PTX1_BoosterPumpInlet[1].Val", "REAL", 3.0, 3600),
|
||||
Channel(plc_ip_address, "pt21_pressure", "PTX1_BoosterPumpInlet[2].Val", "REAL", 3.0, 3600),
|
||||
Channel(plc_ip_address, "pt31_pressure", "PTX1_BoosterPumpInlet[3].Val", "REAL", 3.0, 3600),
|
||||
|
||||
Channel(plc_ip_address, "pt12_pressure", "PTX2_BoosterPumpDischarge[1].Val", "REAL", 3.0, 3600),
|
||||
Channel(plc_ip_address, "pt22_pressure", "PTX2_BoosterPumpDischarge[2].Val", "REAL", 3.0, 3600),
|
||||
Channel(plc_ip_address, "pt32_pressure", "PTX2_BoosterPumpDischarge[3].Val", "REAL", 3.0, 3600),
|
||||
|
||||
Channel(plc_ip_address, "ft01_flow", "FTX1_SystemOutput[0].Val", "REAL", 5.0, 3600),
|
||||
Channel(plc_ip_address, "ft11_flow", "FTX1_SystemOutput[1].Val", "REAL", 5.0, 3600),
|
||||
Channel(plc_ip_address, "ft21_flow", "FTX1_SystemOutput[2].Val", "REAL", 5.0, 3600),
|
||||
Channel(plc_ip_address, "ft31_flow", "FTX1_SystemOutput[3].Val", "REAL", 5.0, 3600),
|
||||
|
||||
# Channel(plc_ip_address, "run_status", "TransferStation.Running", "BOOL", _, 3600, map_=maps['run']),
|
||||
# Channel(plc_ip_address, "ft21_enabled", "cfg_SystemFTEnabled[2]", "BOOL", _, 3600),
|
||||
# Channel(plc_ip_address, "ft31_enabled", "cfg_SystemFTEnabled[3]", "BOOL", _, 3600),
|
||||
]
|
||||
|
||||
|
||||
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 = "3"
|
||||
self.finished = threading.Event()
|
||||
self.forceSend = False
|
||||
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."""
|
||||
global persist
|
||||
wait_sec = 60
|
||||
for i in range(0, wait_sec):
|
||||
print("transferstation driver will start in {} seconds".format(wait_sec - i))
|
||||
time.sleep(1)
|
||||
print("BOOM! Starting transferstation driver...")
|
||||
# after its booted up assuming that M1 is now reading modbus data
|
||||
# we can replace the reference made to this device name to the M1 driver with this
|
||||
# driver. The 01 in the 0199 below is the device number you referenced in the modbus wizard
|
||||
self.nodes["transferstation_0199"] = self
|
||||
send_loops = 0
|
||||
while True:
|
||||
if self.forceSend:
|
||||
print "FORCE SEND: TRUE"
|
||||
|
||||
# for c in channels:
|
||||
# if c.read(self.forceSend):
|
||||
# self.sendtodb(c.mesh_name, c.value, 0)
|
||||
#
|
||||
# for b in bit_channels:
|
||||
# if b.read(self.forceSend):
|
||||
# for v in b.last_value:
|
||||
# self.sendtodb(v, b.last_value[v], 0)
|
||||
|
||||
# print("transferstation driver still alive...")
|
||||
if self.forceSend:
|
||||
if send_loops > 2:
|
||||
print("Turning off forceSend")
|
||||
self.forceSend = False
|
||||
send_loops = 0
|
||||
else:
|
||||
send_loops += 1
|
||||
|
||||
# def transferstation_sync(self, name, value):
|
||||
# """Sync all data from the driver."""
|
||||
# self.forceSend = True
|
||||
# # self.sendtodb("log", "synced", 0)
|
||||
# return True
|
||||
|
||||
def transferstation_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']
|
||||
w = write_tag(str(plc_ip_address), tag_n, val_n)
|
||||
print("Result of transferstation_writeplctag(self, {}, {}) = {}".format(name, value, w))
|
||||
if w is None:
|
||||
w = "Error writing to PLC..."
|
||||
return w
|
||||
Reference in New Issue
Block a user