327 lines
16 KiB
Python
327 lines
16 KiB
Python
"""Driver for advvfdipppond"""
|
|
|
|
import threading
|
|
import json
|
|
import os
|
|
import time
|
|
from random import randint
|
|
# PERSISTENCE FILE
|
|
import persistence
|
|
PERSIST = persistence.load("extra_data.json")
|
|
if not PERSIST:
|
|
PERSIST = {'ip_address': '192.168.1.10', 'download_pycomm': True, 'flowmeter_units': 'GPM'}
|
|
persistence.store(PERSIST, "extra_data.json")
|
|
os.system('echo "" > /root/python_firmware/drivers/modbusMap.p')
|
|
PLC_IP_ADDRESS = PERSIST['ip_address']
|
|
from device_base import deviceBase
|
|
import urllib
|
|
if PERSIST['download_pycomm']:
|
|
try:
|
|
urllib.urlretrieve('http://s3.amazonaws.com/pocloud-drivers/pycomm/clx.py', '/root/python_firmware/pycomm/ab_comm/clx.py')
|
|
urllib.urlretrieve('http://s3.amazonaws.com/pocloud-drivers/pycomm/cip_base.py', '/root/python_firmware/pycomm/cip/cip_base.py')
|
|
PERSIST['download_pycomm'] = False
|
|
persistence.store(PERSIST, "extra_data.json")
|
|
except Exception as e:
|
|
print("Could not download latest pycomm update: {}".format(e))
|
|
|
|
from Channel import PLCChannel, ModbusChannel,read_tag, write_tag, TAG_DATAERROR_SLEEPTIME
|
|
from utilities import get_public_ip_address, get_private_ip_address, get_additional_tags, convert_int
|
|
from file_logger import filelogger as log
|
|
from Tags import tags
|
|
from datetime import datetime as dt
|
|
|
|
|
|
path = "/root/python_firmware/drivers/additional_tags.py"
|
|
|
|
f = open(path, "a+")
|
|
f.seek(0)
|
|
if os.stat(path).st_size == 0:
|
|
f.write("from Channel import PLCChannel, ModbusChannel\n")
|
|
f.write("from advvfdipppond import PLC_IP_ADDRESS\n")
|
|
f.write("additional_tags = []")
|
|
f.close()
|
|
|
|
|
|
from additional_tags import additional_tags
|
|
|
|
_ = None
|
|
|
|
log.info("advvfdipppond startup")
|
|
|
|
# GLOBAL VARIABLES
|
|
WAIT_FOR_CONNECTION_SECONDS = 30
|
|
IP_CHECK_PERIOD = 60
|
|
|
|
CHANNELS = tags + additional_tags
|
|
|
|
TOTALIZERS = persistence.load("totalizers.json")
|
|
if not TOTALIZERS:
|
|
TOTALIZERS = {}
|
|
for x in ['total_in','fm1', 'fm2', 'fm3', 'fm4', 'fm5', 'fm6']:
|
|
TOTALIZERS[x] = {
|
|
'Todays': 0,
|
|
'Yesterdays': 0,
|
|
'Current Months': 0,
|
|
'Previous Months': 0,
|
|
'Monthly Holding': 0,
|
|
'Daily Holding': 0,
|
|
'Lifetime': 0,
|
|
'Day': 0,
|
|
'Month': 0,
|
|
'Last Report': 0
|
|
}
|
|
persistence.store(TOTALIZERS, "totalizers.json")
|
|
|
|
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.force_send = False
|
|
self.public_ip_address = ""
|
|
self.private_ip_address = ""
|
|
self.public_ip_address_last_checked = 0
|
|
self.ping_counter = 0
|
|
deviceMap = {}
|
|
with open("drivers/deviceMap.json", "r") as dm:
|
|
deviceMap = json.load(dm)
|
|
with open("provision.json", "w+") as creds:
|
|
p = {
|
|
"deviceName": deviceMap[mac],
|
|
"provisionDeviceKey": "lkc7ra5l4dnyp782d3px",
|
|
"provisionDeviceSecret": "p6olkitsteiwkf1pv7m5"
|
|
}
|
|
json.dump(p, creds, indent=4)
|
|
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("advvfdipppond driver will start in {} seconds".format(WAIT_FOR_CONNECTION_SECONDS - i))
|
|
time.sleep(1)
|
|
log.info("BOOM! Starting advvfdipppond driver...")
|
|
|
|
|
|
|
|
self._check_ip_address()
|
|
|
|
self.nodes["advvfdipppond_0199"] = self
|
|
try:
|
|
if PERSIST['flowmeter_units']:
|
|
self.sendtodbDev(1, 'flowunits', PERSIST['flowmeter_units'], 0, 'advvfdipppond')
|
|
else:
|
|
PERSIST['flowmeter_units'] = "GPM"
|
|
persistence.store(PERSIST, "extra_data.json")
|
|
self.sendtodbDev(1, 'flowunits', PERSIST['flowmeter_units'], 0, 'advvfdipppond')
|
|
except:
|
|
PERSIST['flowmeter_units'] = "GPM"
|
|
persistence.store(PERSIST, "extra_data.json")
|
|
self.sendtodbDev(1, 'flowunits', PERSIST['flowmeter_units'], 0, 'advvfdipppond')
|
|
send_loops = 0
|
|
convert_list = ["Device_Status_INT","sts_PID_Control","Downhole_Sensor_Status_INT","alarm_Flowmeter","alarm_IntakePressure",
|
|
"alarm_IntakeTemperature","alarm_TubingPressure","alarm_VFD","alarm_Lockout","alarm_FluidLevel","Run_Permissive_INT",
|
|
"Start_Permissive_INT","PowerFlex755.Val_LastFaultCode","sts_CurrentVFDFaultCode"]
|
|
while True:
|
|
now = time.time()
|
|
if self.force_send:
|
|
log.warning("FORCE SEND: TRUE")
|
|
|
|
for chan in CHANNELS:
|
|
try:
|
|
val = chan.read()
|
|
if "hart" in chan.mesh_name and val == None:
|
|
val = 0.0
|
|
if chan.check(val, self.force_send):
|
|
if chan.plc_tag in convert_list:
|
|
converted_value = convert_int(chan.plc_tag, val)
|
|
self.sendtodbDev(1, chan.mesh_name, converted_value, 0, 'advvfdipppond')
|
|
elif "lifetime" in chan.mesh_name:
|
|
self.totalize(val,chan.mesh_name[:-9])
|
|
else:
|
|
self.sendtodbDev(1, chan.mesh_name, chan.value, 0, 'advvfdipppond')
|
|
#time.sleep(TAG_DATAERROR_SLEEPTIME) # sleep to allow Micro800 to handle ENET requests
|
|
except Exception as e:
|
|
log.info("Error: {}".format(e))
|
|
time.sleep(30) #sleep for 30 seconds after a full poll
|
|
# print("advvfdipppond 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, 'advvfdipppond')
|
|
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, 'advvfdipppond')
|
|
self.private_ip_address = test_private_ip
|
|
hostname = "google.com"
|
|
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:
|
|
log.info("Rebooting because no internet detected")
|
|
os.system('reboot')
|
|
|
|
|
|
def advvfdipppond_sync(self, name, value):
|
|
"""Sync all data from the driver."""
|
|
self.force_send = True
|
|
# self.sendtodb("log", "synced", 0)
|
|
return True
|
|
|
|
def advvfdipppond_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 advvfdipppond_writeplctag(self, {}, {}) = {}".format(name, value, write_res))
|
|
if write_res is None:
|
|
write_res = "Error writing to PLC..."
|
|
return write_res
|
|
|
|
def advvfdipppond_startcmd(self,name, value):
|
|
write_res = write_tag(str(PLC_IP_ADDRESS), "cmd_Start" , 1, plc_type="CLX")
|
|
print("Result of advvfdipppond_writeplctag(self, {}, {}) = {}".format(name, value, write_res))
|
|
if write_res is None:
|
|
write_res = "Error writing to PLC..."
|
|
return write_res
|
|
|
|
def advvfdipppond_stopcmd(self,name, value):
|
|
write_res = write_tag(str(PLC_IP_ADDRESS), "cmd_Stop" , 1, plc_type="CLX")
|
|
print("Result of advvfdipppond_writeplctag(self, {}, {}) = {}".format(name, value, write_res))
|
|
if write_res is None:
|
|
write_res = "Error writing to PLC..."
|
|
return write_res
|
|
|
|
def advvfdipppond_flowunits(self, name, value):
|
|
new_val = json.loads(str(value).replace("'", '"'))
|
|
PERSIST['flowmeter_units'] = new_val
|
|
persistence.store(PERSIST, "extra_data.json")
|
|
self.sendtodbDev(1, 'flowunits', PERSIST['flowmeter_units'], 0, 'advvfdipppond')
|
|
|
|
def totalize(self, val, totalizer):
|
|
right_now = dt.today()
|
|
month = right_now.month
|
|
day = right_now.day
|
|
#Totalize Today, Yesterday, Month, Last Month
|
|
#if the stored day is 0 then it's a fresh run of this should initalize values now
|
|
if TOTALIZERS[totalizer]['Day'] == 0:
|
|
TOTALIZERS[totalizer]['Day'] = day
|
|
TOTALIZERS[totalizer]['Month'] = month
|
|
TOTALIZERS[totalizer]['Daily Holding'] = val
|
|
TOTALIZERS[totalizer]['Monthly Holding'] = val
|
|
persistence.store(TOTALIZERS, 'totalizers.json')
|
|
#Communication error during initialization check if lifetime has reported properly and update holdings
|
|
if TOTALIZERS[totalizer]['Daily Holding'] == None and not(val == None):
|
|
TOTALIZERS[totalizer]['Daily Holding'] = val
|
|
TOTALIZERS[totalizer]['Monthly Holding'] = val
|
|
|
|
try:
|
|
if val - TOTALIZERS[totalizer]['Daily Holding'] - TOTALIZERS[totalizer]['Todays'] > 500 or time.time() - TOTALIZERS[totalizer]['Last Report'] > 3600 or self.force_send:
|
|
TOTALIZERS[totalizer]['Todays'] = val - TOTALIZERS[totalizer]['Daily Holding']
|
|
TOTALIZERS[totalizer]['Current Months'] = val - TOTALIZERS[totalizer]['Monthly Holding']
|
|
TOTALIZERS[totalizer]['Lifetime'] = val
|
|
self.sendtodbDev(1, '{}_todays'.format(totalizer), TOTALIZERS[totalizer]['Todays'], 0, 'advvfdipppond')
|
|
if totalizer == "total_in":
|
|
self.sendtodbDev(1, '{}_months'.format(totalizer), TOTALIZERS[totalizer]['Current Months'], 0, 'advvfdipppond')
|
|
else:
|
|
self.sendtodbDev(1, '{}_month'.format(totalizer), TOTALIZERS[totalizer]['Current Months'], 0, 'advvfdipppond')
|
|
self.sendtodbDev(1, '{}_yesterdays'.format(totalizer), TOTALIZERS[totalizer]['Yesterdays'], 0, 'advvfdipppond')
|
|
self.sendtodbDev(1, '{}_lifetime'.format(totalizer), TOTALIZERS[totalizer]['Lifetime'], 0, 'advvfdipppond')
|
|
if self.force_send:
|
|
self.sendtodbDev(1, '{}_lastmonths'.format(totalizer), TOTALIZERS[totalizer]['Previous Months'], 0, 'advvfdipppond')
|
|
TOTALIZERS[totalizer]['Last Report'] = time.time()
|
|
except:
|
|
if time.time() - TOTALIZERS[totalizer]['Last Report'] > 3600 or self.force_send:
|
|
self.sendtodbDev(1, '{}_todays'.format(totalizer), TOTALIZERS[totalizer]['Todays'], 0, 'advvfdipppond')
|
|
if totalizer == "total_in":
|
|
self.sendtodbDev(1, '{}_months'.format(totalizer), TOTALIZERS[totalizer]['Current Months'], 0, 'advvfdipppond')
|
|
else:
|
|
self.sendtodbDev(1, '{}_month'.format(totalizer), TOTALIZERS[totalizer]['Current Months'], 0, 'advvfdipppond')
|
|
self.sendtodbDev(1, '{}_yesterdays'.format(totalizer), TOTALIZERS[totalizer]['Yesterdays'], 0, 'advvfdipppond')
|
|
self.sendtodbDev(1, '{}_lifetime'.format(totalizer), TOTALIZERS[totalizer]['Lifetime'], 0, 'advvfdipppond')
|
|
if self.force_send:
|
|
self.sendtodbDev(1, '{}_lastmonths'.format(totalizer), TOTALIZERS[totalizer]['Previous Months'], 0, 'advvfdipppond')
|
|
TOTALIZERS[totalizer]['Last Report'] = time.time()
|
|
|
|
#If the current day doesn't equal the stored day roll the dailies over
|
|
if not(day == TOTALIZERS[totalizer]['Day']):
|
|
#if a comms error use the stored values else use the latested values
|
|
if val == None:
|
|
TOTALIZERS[totalizer]['Yesterdays'] = TOTALIZERS[totalizer]['Todays']
|
|
TOTALIZERS[totalizer]['Todays'] = 0
|
|
TOTALIZERS[totalizer]['Daily Holding'] = TOTALIZERS[totalizer]['Lifetime']
|
|
else:
|
|
TOTALIZERS[totalizer]['Yesterdays'] = val - TOTALIZERS[totalizer]['Daily Holding']
|
|
TOTALIZERS[totalizer]['Todays'] = 0
|
|
TOTALIZERS[totalizer]['Daily Holding'] = val
|
|
TOTALIZERS[totalizer]['Lifetime'] = val
|
|
TOTALIZERS[totalizer]['Day'] = day
|
|
self.sendtodbDev(1, '{}_todays'.format(totalizer), TOTALIZERS[totalizer]['Todays'], 0, 'advvfdipppond')
|
|
self.sendtodbDev(1, '{}_yesterdays'.format(totalizer), TOTALIZERS[totalizer]['Yesterdays'], 0, 'advvfdipppond')
|
|
self.sendtodbDev(1, '{}_lifetime'.format(totalizer), TOTALIZERS[totalizer]['Lifetime'], 0, 'advvfdipppond')
|
|
TOTALIZERS[totalizer]['Last Report'] = time.time()
|
|
#the day has rolled over if the month also rolls over
|
|
if not(month == TOTALIZERS[totalizer]['Month']):
|
|
#if a comms error use the stored values else use the latested values
|
|
if val == None:
|
|
TOTALIZERS[totalizer]['Previous Months'] = TOTALIZERS[totalizer]['Current Months']
|
|
TOTALIZERS[totalizer]['Current Months'] = 0
|
|
TOTALIZERS[totalizer]['Monthly Holding'] = TOTALIZERS[totalizer]['Lifetime']
|
|
else:
|
|
TOTALIZERS[totalizer]['Previous Months'] = val - TOTALIZERS[totalizer]['Monthly Holding']
|
|
TOTALIZERS[totalizer]['Current Months'] = 0
|
|
TOTALIZERS[totalizer]['Monthly Holding'] = val
|
|
TOTALIZERS[totalizer]['Month'] = month
|
|
if totalizer == "total_in":
|
|
self.sendtodbDev(1, '{}_months'.format(totalizer), TOTALIZERS[totalizer]['Current Months'], 0, 'advvfdipppond')
|
|
else:
|
|
self.sendtodbDev(1, '{}_month'.format(totalizer), TOTALIZERS[totalizer]['Current Months'], 0, 'advvfdipppond')
|
|
self.sendtodbDev(1, '{}_lastmonths'.format(totalizer), TOTALIZERS[totalizer]['Previous Months'], 0, 'advvfdipppond')
|
|
self.sendtodbDev(1, '{}_lifetime'.format(totalizer), TOTALIZERS[totalizer]['Lifetime'], 0, 'advvfdipppond')
|
|
TOTALIZERS[totalizer]['Last Report'] = time.time()
|
|
persistence.store(TOTALIZERS, 'totalizers.json') |