177 lines
6.5 KiB
Python
177 lines
6.5 KiB
Python
"""Driver for rigpump_w_valve."""
|
|
|
|
import threading
|
|
import sys
|
|
import json
|
|
import time
|
|
import logging
|
|
from device_base import deviceBase
|
|
from Channel import PLCChannel, write_tag, BoolArrayChannels, read_tag, TAG_DATAERROR_SLEEPTIME
|
|
from Maps import rigpump_map as maps
|
|
from random import randint
|
|
import json
|
|
import time
|
|
import socket
|
|
|
|
_ = None
|
|
|
|
try:
|
|
with open("persist.json", 'r') as persist_file:
|
|
persist = json.load(persist_file)
|
|
except Exception:
|
|
persist = {}
|
|
|
|
# LOGGING SETUP
|
|
from logging.handlers import RotatingFileHandler
|
|
|
|
log_formatter = logging.Formatter('%(asctime)s %(levelname)s %(funcName)s(%(lineno)d) %(message)s')
|
|
logFile = './rigpump_w_valve.log'
|
|
my_handler = RotatingFileHandler(logFile, mode='a', maxBytes=500*1024, backupCount=2, encoding=None, delay=0)
|
|
my_handler.setFormatter(log_formatter)
|
|
my_handler.setLevel(logging.INFO)
|
|
logger = logging.getLogger('rigpump_w_valve')
|
|
logger.setLevel(logging.INFO)
|
|
logger.addHandler(my_handler)
|
|
|
|
console_out = logging.StreamHandler(sys.stdout)
|
|
console_out.setFormatter(log_formatter)
|
|
logger.addHandler(console_out)
|
|
|
|
logger.info("rigpump_w_valve startup")
|
|
|
|
#GLOBAL VARIABLES
|
|
PLC_IP_ADDRESS = "192.168.1.10"
|
|
WATCHDOG_SEND_PERIOD = 3600 # seconds
|
|
channels = [
|
|
PLCChannel(PLC_IP_ADDRESS, "valve1open", "valve1openfbk", "BOOL", 1, 600, map_=False, write_enabled=False, plc_type="Micro800"),
|
|
PLCChannel(PLC_IP_ADDRESS, "valve1close", "valve1closefbk", "BOOL", 1, 600, map_=False, write_enabled=False, plc_type="Micro800")
|
|
]
|
|
|
|
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
|
|
|
|
|
|
def get_public_ip_address():
|
|
"""Find the public IP Address of the host device."""
|
|
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
s.connect(("8.8.8.8", 80))
|
|
ip = s.getsockname()[0]
|
|
s.close()
|
|
return ip
|
|
|
|
|
|
|
|
|
|
|
|
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 = "7"
|
|
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)
|
|
logger.info("Registered!")
|
|
pass
|
|
|
|
def run(self):
|
|
"""Actually run the driver."""
|
|
global persist
|
|
|
|
wait_sec = 60
|
|
for i in range(0, wait_sec):
|
|
logger.info("rigpump_w_valve driver will start in {} seconds".format(wait_sec - i))
|
|
time.sleep(1)
|
|
logger.info("BOOM! Starting rigpump_w_valve 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["rigpump_w_valve_0199"] = self
|
|
|
|
public_ip_address = get_public_ip_address()
|
|
self.sendtodbDev(1, 'public_ip_address', public_ip_address, 0, 'rigpump_w_valve')
|
|
|
|
watchdog = self.rigpump_w_valve_watchdog()
|
|
self.sendtodbDev(1, 'watchdog', watchdog, 0, 'rigpump_w_valve')
|
|
watchdog_send_timestamp = time.time()
|
|
|
|
send_loops = 0
|
|
watchdog_loops = 0
|
|
watchdog_check_after = 5000
|
|
while True:
|
|
if self.forceSend:
|
|
logger.info( "FORCE SEND: TRUE")
|
|
|
|
for c in channels:
|
|
v = c.read()
|
|
if v is not None: # read returns None if it fails
|
|
if c.check(v, self.force_send):
|
|
self.sendtodbDev(1, c.mesh_name, c.value, 0, 'rigpump_w_valve')
|
|
time.sleep(TAG_DATAERROR_SLEEPTIME) # sleep to allow Micro800 to handle ENET requests
|
|
|
|
logger.info("rigpump_w_valve_w_valve driver still alive...")
|
|
if self.forceSend:
|
|
if send_loops > 2:
|
|
logger.info("Turning off forceSend")
|
|
self.forceSend = False
|
|
send_loops = 0
|
|
else:
|
|
send_loops += 1
|
|
|
|
watchdog_loops += 1
|
|
if (watchdog_loops >= watchdog_check_after):
|
|
test_watchdog = self.rigpump_w_valve_watchdog()
|
|
if test_watchdog != watchdog or (time.time() - watchdog_send_timestamp) > WATCHDOG_SEND_PERIOD:
|
|
self.sendtodbDev(1, 'watchdog', test_watchdog, 0, 'rigpump_w_valve')
|
|
watchdog_send_timestamp = time.time()
|
|
watchdog = test_watchdog
|
|
|
|
test_public_ip = get_public_ip_address()
|
|
if not test_public_ip == public_ip_address:
|
|
self.sendtodbDev(1, 'public_ip_address', test_public_ip, 0, 'rigpump_w_valve')
|
|
public_ip_address = test_public_ip
|
|
watchdog_loops = 0
|
|
|
|
def rigpump_w_valve_watchdog(self):
|
|
"""Write a random integer to the PLC and then 1 seconds later check that it has been decremented by 1."""
|
|
randval = randint(0, 32767)
|
|
write_tag(str(PLC_IP_ADDRESS), 'watchdog_INT', randval, plc_type="Micro800")
|
|
time.sleep(1)
|
|
watchdog_val = read_tag(str(PLC_IP_ADDRESS), 'watchdog_INT', plc_type="Micro800")
|
|
try:
|
|
return (randval - 1) == watchdog_val[0]
|
|
except (KeyError, TypeError):
|
|
return False
|
|
|
|
def rigpump_w_valve_sync(self, name, value):
|
|
"""Sync all data from the driver."""
|
|
self.forceSend = True
|
|
# self.sendtodb("log", "synced", 0)
|
|
return True
|
|
|
|
def rigpump_w_valve_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)
|
|
logger.info("Result of rigpump_w_valve_writeplctag(self, {}, {}) = {}".format(name, value, w))
|
|
if w is None:
|
|
w = "Error writing to PLC..."
|
|
return w
|