added tankalarms
This commit is contained in:
@@ -1,20 +1,10 @@
|
||||
"""Define Meshify channel class."""
|
||||
import time
|
||||
from pycomm.ab_comm.clx import Driver as ClxDriver
|
||||
from pycomm.cip.cip_base import CommError, DataError
|
||||
import time
|
||||
import minimalmodbusM1
|
||||
from file_logger import filelogger as log
|
||||
import minimalmodbusM1
|
||||
from PiFlow import mcug
|
||||
#minimalmodbus.BAUDRATE = 9600
|
||||
#minimalmodbus.STOPBITS = 1
|
||||
connected = False
|
||||
while connected == False:
|
||||
connected = mcug.set485Baud(9600)
|
||||
time.sleep(1)
|
||||
serial = mcug.rs485
|
||||
instrument = minimalmodbusM1.Instrument(1,serial)
|
||||
instrument.address = 2
|
||||
TAG_DATAERROR_SLEEPTIME = 5
|
||||
import struct
|
||||
|
||||
def binarray(intval):
|
||||
"""Split an integer into its bits."""
|
||||
@@ -24,78 +14,69 @@ def binarray(intval):
|
||||
return bin_arr
|
||||
|
||||
|
||||
def read_tag(addr, tag, plc_type="CLX"):
|
||||
def read_tag(addr, tag):
|
||||
"""Read a tag from the PLC."""
|
||||
direct = plc_type == "Micro800"
|
||||
clx = ClxDriver()
|
||||
c = ClxDriver()
|
||||
try:
|
||||
if clx.open(addr, direct_connection=direct):
|
||||
if c.open(addr):
|
||||
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))
|
||||
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()
|
||||
clx.close()
|
||||
log.error("Could not connect during readTag({}, {})".format(addr, tag))
|
||||
except AttributeError as err:
|
||||
clx.close()
|
||||
log.error("AttributeError during readTag({}, {}): \n{}".format(addr, tag, err))
|
||||
clx.close()
|
||||
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, plc_type="CLX"):
|
||||
def read_array(addr, tag, start, end):
|
||||
"""Read an array from the PLC."""
|
||||
direct = plc_type == "Micro800"
|
||||
clx = ClxDriver()
|
||||
if clx.open(addr, direct_connection=direct):
|
||||
c = ClxDriver()
|
||||
if c.open(addr):
|
||||
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()
|
||||
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:
|
||||
log.error("No length for {}".format(addr))
|
||||
clx.close()
|
||||
print("No length for {}".format(addr))
|
||||
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()
|
||||
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, plc_type="CLX"):
|
||||
def write_tag(addr, tag, val):
|
||||
"""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
|
||||
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(object):
|
||||
@@ -121,14 +102,14 @@ class Channel(object):
|
||||
"""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' or type(new_value) == str:
|
||||
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:
|
||||
elif not (self.value == new_value):
|
||||
if self.map_:
|
||||
if not self.value == self.map_[new_value]:
|
||||
send_needed = True
|
||||
@@ -164,12 +145,12 @@ class Channel(object):
|
||||
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))
|
||||
print("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))
|
||||
print("Sending {} for {} - {}".format(self.value, self.mesh_name, send_reason))
|
||||
return send_needed
|
||||
|
||||
def read(self):
|
||||
@@ -181,6 +162,7 @@ def identity(sent):
|
||||
"""Return exactly what was sent to it."""
|
||||
return sent
|
||||
|
||||
|
||||
def volume_units(vunit):
|
||||
units = {
|
||||
0: "cm cubed/s",
|
||||
@@ -320,156 +302,12 @@ def totalizer_units(tunit):
|
||||
}
|
||||
return units[tunit]
|
||||
|
||||
def int_to_bits(n,x):
|
||||
return pad_to_x([int(digit) for digit in bin(n)[2:]],x) # [2:] to chop off the "0b" part
|
||||
|
||||
def pad_to_x(n,x):
|
||||
while len(n) < x:
|
||||
n = [0] + n
|
||||
return n
|
||||
|
||||
def status_codes(n):
|
||||
|
||||
status_array = int_to_bits(n,16)
|
||||
status_low = {
|
||||
0: "Stopped;",
|
||||
1: "Operating in Forward;",
|
||||
2: "Operating in Reverse;",
|
||||
3: "DC operating;"
|
||||
}
|
||||
status_mid = {
|
||||
0: "",
|
||||
1: "Speed searching;",
|
||||
2: "Accelerating;",
|
||||
3: "At constant speed;",
|
||||
4: "Decelerating;",
|
||||
5: "Decelerating to stop;",
|
||||
6: "H/W OCS;",
|
||||
7: "S/W OCS;",
|
||||
8: "Dwell operating;"
|
||||
}
|
||||
status_high = {
|
||||
0: "Normal state",
|
||||
4: "Warning occurred",
|
||||
8: "Fault occurred"
|
||||
}
|
||||
values = {
|
||||
0: 8,
|
||||
1: 4,
|
||||
2: 2,
|
||||
3: 1
|
||||
}
|
||||
|
||||
stats_low = status_array[12:]
|
||||
stats_mid = status_array[8:12]
|
||||
stats_high = status_array[:4]
|
||||
low = 0
|
||||
mid = 0
|
||||
high = 0
|
||||
for x in range(4):
|
||||
if stats_low[x] == 1:
|
||||
low = low + values[x]
|
||||
if stats_mid[x] == 1:
|
||||
mid = mid + values[x]
|
||||
if stats_high[x] == 1:
|
||||
high = high + values[x]
|
||||
|
||||
return status_low[low] + " " + status_mid[mid] + ' ' + status_high[high]
|
||||
|
||||
def fault_code_a(n):
|
||||
|
||||
fault_code_array = int_to_bits(n,16)
|
||||
|
||||
""" fault = {
|
||||
0: "OCT",
|
||||
1: "OVT",
|
||||
2: "EXT-A",
|
||||
3: "EST",
|
||||
4: "COL",
|
||||
5: "GFT",
|
||||
6: "OHT",
|
||||
7: "ETH",
|
||||
8: "OLT",
|
||||
9: "Reserved",
|
||||
10: "EXT-B",
|
||||
11: "EEP",
|
||||
12: "FAN",
|
||||
13: "POT",
|
||||
14: "IOLT",
|
||||
15: "LVT"
|
||||
} """
|
||||
fault = {
|
||||
0: "Overload Trip",
|
||||
1: "Underload Trip",
|
||||
2: "Inverter Overload Trip",
|
||||
3: "E-Thermal Trip",
|
||||
4: "Ground Fault Trip",
|
||||
5: "Output Image Trip",
|
||||
6: "Inmput Imaging Trip",
|
||||
7: "Reserved",
|
||||
8: "Reserved",
|
||||
9: "NTC Trip",
|
||||
10: "Overcurrent Trip",
|
||||
11: "Overvoltage Trip",
|
||||
12: "External Trip",
|
||||
13: "Arm Short",
|
||||
14: "Over Heat Trip",
|
||||
15: "Fuse Open Trip"
|
||||
}
|
||||
|
||||
faults = []
|
||||
counter = 15
|
||||
for x in range(16):
|
||||
if fault_code_array[x] == 1:
|
||||
faults = [fault[counter]] + faults
|
||||
counter = counter - 1
|
||||
return ' '.join(faults)
|
||||
|
||||
def fault_code_b(n):
|
||||
|
||||
fault_code_array = int_to_bits(n,8)
|
||||
|
||||
""" fault = {
|
||||
0: "COM",
|
||||
1: "Reserved",
|
||||
2: "NTC",
|
||||
3: "REEP",
|
||||
4: "OC2",
|
||||
5: "NBR",
|
||||
6: "SAFA",
|
||||
7: "SAFB"
|
||||
} """
|
||||
fault = {
|
||||
0: "Reserved",
|
||||
1: "Reserved",
|
||||
2: "Reserved",
|
||||
3: "FAN Trip",
|
||||
4: "Reserved",
|
||||
5: "Reserved",
|
||||
6: "Pre PID Fail",
|
||||
7: "Bad contact at basic I/O board",
|
||||
8: "External Brake Trip",
|
||||
9: "No Motor Trip",
|
||||
10: "Bad Option Card",
|
||||
11: "Reserved",
|
||||
12: "Reserved",
|
||||
13: "Reserved",
|
||||
14: "Pre Over Heat Trip",
|
||||
15: "Reserved"
|
||||
}
|
||||
|
||||
faults = []
|
||||
counter = 7
|
||||
for x in range(8):
|
||||
if fault_code_array[x] == 1:
|
||||
faults = [fault[counter]] + faults
|
||||
counter = counter - 1
|
||||
return ' '.join(faults)
|
||||
|
||||
class ModbusChannel(Channel):
|
||||
"""Modbus channel object."""
|
||||
|
||||
def __init__(self, mesh_name, register_number, data_type, chg_threshold, guarantee_sec, channel_size=1, map_=False, write_enabled=False, transform_fn=identity, unit_number=1, scaling=0):
|
||||
def __init__(self, mesh_name, register_number, data_type, chg_threshold, guarantee_sec, channel_size=1, map_=False, write_enabled=False, transform_fn=identity, unit_number=1, scaling=0, mcu=None):
|
||||
"""Initialize the channel."""
|
||||
super(ModbusChannel, self).__init__(mesh_name, data_type, chg_threshold, guarantee_sec, map_, write_enabled)
|
||||
self.mesh_name = mesh_name
|
||||
@@ -486,45 +324,63 @@ class ModbusChannel(Channel):
|
||||
self.transform_fn = transform_fn
|
||||
self.unit_number = unit_number
|
||||
self.scaling= scaling
|
||||
self.mcu = mcu
|
||||
|
||||
baud = 9600
|
||||
connected = False
|
||||
while connected == False:
|
||||
try:
|
||||
#print("CONNECTING!!!!!!!!!!!!!!!!!!!!!!!!!")
|
||||
connected = self.mcu.set485Baud(baud)
|
||||
time.sleep(1)
|
||||
except Exception as e:
|
||||
print("Error on connect: ", e)
|
||||
serial4 = self.mcu.rs485
|
||||
|
||||
self.instrument = minimalmodbusM1.Instrument(1, serial4)
|
||||
self.instrument.address = 1
|
||||
|
||||
def read(self):
|
||||
"""Return the transformed read value."""
|
||||
print("ATTEMPTING TO READ ON {}".format(self.mesh_name))
|
||||
if self.data_type == "FLOAT":
|
||||
try:
|
||||
read_value = instrument.read_float(self.register_number,4,self.channel_size)
|
||||
read_value = self.instrument.read_float(self.register_number,4,self.channel_size)
|
||||
except IOError as e:
|
||||
log.info(e)
|
||||
log.error(e)
|
||||
return None
|
||||
|
||||
elif self.data_type == "INTEGER" or self.data_type == "STRING":
|
||||
try:
|
||||
read_value = instrument.read_register(self.register_number, self.scaling, 4)
|
||||
read_value = self.instrument.read_register(self.register_number, self.scaling, 4)
|
||||
except IOError as e:
|
||||
log.info(e)
|
||||
log.error(e)
|
||||
return None
|
||||
elif self.data_type == "FLOATBS":
|
||||
try:
|
||||
t = self.instrument.read_registers(self.register_number, 2, 3)
|
||||
read_value = round(self.byteSwap32(t), 2)
|
||||
except IOError as e:
|
||||
log.error(e)
|
||||
return None
|
||||
read_value = self.transform_fn(read_value)
|
||||
return read_value
|
||||
|
||||
def write(self, value):
|
||||
"""Write a value to a register"""
|
||||
if self.data_type == "FLOAT":
|
||||
value = float(value)
|
||||
elif self.data_type == "INTEGER":
|
||||
value = int(value)
|
||||
else:
|
||||
value = str(value)
|
||||
try:
|
||||
instrument.write_register(self.register_number,value, self.scaling, 16 if self.channel_size > 1 else 6 )
|
||||
return True
|
||||
except Exception as e:
|
||||
log.info("Failed to write value: {}".format(e))
|
||||
return False
|
||||
|
||||
def byteSwap32(self, array):
|
||||
newVal = ""
|
||||
for i in array:
|
||||
i = hex(i).replace('0x', '')
|
||||
while len(i) < 4:
|
||||
i = "0" + i
|
||||
print i
|
||||
newVal = i + newVal
|
||||
print newVal
|
||||
return struct.unpack('!f', newVal.decode('hex'))[0]
|
||||
|
||||
|
||||
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'):
|
||||
def __init__(self, ip, mesh_name, plc_tag, data_type, chg_threshold, guarantee_sec, map_=False, write_enabled=False):
|
||||
"""Initialize the channel."""
|
||||
super(PLCChannel, self).__init__(mesh_name, data_type, chg_threshold, guarantee_sec, map_, write_enabled)
|
||||
self.plc_ip = ip
|
||||
@@ -538,13 +394,12 @@ class PLCChannel(Channel):
|
||||
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)
|
||||
read_value = read_tag(self.plc_ip, self.plc_tag)
|
||||
if read_value:
|
||||
plc_value = read_value[0]
|
||||
|
||||
@@ -556,7 +411,6 @@ class BoolArrayChannels(Channel):
|
||||
|
||||
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
|
||||
@@ -577,7 +431,7 @@ class BoolArrayChannels(Channel):
|
||||
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))
|
||||
print("Key Error in self.compare_values for index {}".format(idx))
|
||||
send = True
|
||||
return send
|
||||
|
||||
@@ -586,15 +440,15 @@ class BoolArrayChannels(Channel):
|
||||
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])
|
||||
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:
|
||||
log.error("Not able to get value for index {}".format(idx))
|
||||
print("Not able to get value for index {}".format(idx))
|
||||
|
||||
if self.last_send_time == 0:
|
||||
send_needed = True
|
||||
@@ -616,5 +470,5 @@ class BoolArrayChannels(Channel):
|
||||
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
|
||||
print("Sending {} for {} - {}".format(self.value, self.mesh_name, send_reason))
|
||||
return send_needed
|
||||
|
||||
Reference in New Issue
Block a user