added new drivers

This commit is contained in:
Nico Melone
2022-10-05 12:31:47 -05:00
parent 55f34b5c08
commit 701376b848
14 changed files with 5855 additions and 10 deletions

BIN
Pub_Sub/.DS_Store vendored

Binary file not shown.

Binary file not shown.

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,29 @@
# Enter your python code.
import json, time
from quickfaas.measure import recall, write
from quickfaas.remotebus import publish
from common.Logger import logger
def writeplctag(value):
#value in the form {"measurement": <measurement_name>, "value": <value to write>}
try:
#value = json.loads(value.replace("'",'"'))
logger.info(value)
#payload format: [{"name": "advvfdipp", "measures": [{"name": "manualfrequencysetpoint", "value": 49}]}]
message = [{"name": "advvfdipp", "measures":[{"name":value["measurement"], "value": value["value"]}]}]
resp = write(message)
logger.info("RETURN FROM WRITE: {}".format(resp))
return True
except Exception as e:
logger.info(e)
return False
def sendToPLC(message):
logger.info(message)
for measure in message["measures"]:
logger.info(measure)
#{'ctrlName': 'modbus_converter', 'name': 'SRU_Data[1]', 'health': 1, 'timestamp': 1664894200, 'value': 47}
writeplctag({"measurement": measure["name"], "value": measure["value"]})
#time.sleep(2)

View File

@@ -2,7 +2,7 @@
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
@@ -12,15 +12,16 @@
},
{
"cell_type": "code",
"execution_count": 2,
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"root = \"/Users/nico/Documents/GitHub/HP_InHand_IG502/Pub_Sub/\"\n",
"devicetype = \"flowmeterskid\"\n",
"platform = \"thingsboard\" #\"mistaway\"\n",
"devicetype = \"dual_flowmeter\"\n",
"platform = \"mistaway\" #\"thingsboard\"\n",
"platform_short = \"tb\" if platform == \"thingsboard\" else \"ma\" \n",
"startversion = 0\n",
"deviceconfig = devicetype + \"_tb_\" +\"v\" + str(startversion) + \".cfg\"\n"
"deviceconfig = devicetype + \"_\" + platform_short + \"_\" +\"v\" + str(startversion) + \".cfg\"\n"
]
},
{
@@ -36,15 +37,15 @@
},
{
"cell_type": "code",
"execution_count": 3,
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"\n",
"convert_config.write_config(root + \"/\" + devicetype + \"/thingsboard/v\" + str(startversion + 1) + \"/\" + devicetype + \"_tb_v\" + str(startversion + 1) + \".cfg\", \n",
" convert_config.get_config(root + \"/\" + devicetype + \"/thingsboard/v\" + str(startversion) + \"/\" + devicetype + \"_tb_v\" + str(startversion) + \".cfg\"),\n",
" root + \"/\" + devicetype + \"/thingsboard/v\" + str(startversion + 1) + \"/pub\" , \n",
" root + \"/\" + devicetype + \"/thingsboard/v\" + str(startversion + 1) + \"/sub\")"
"convert_config.write_config(root + \"/\" + devicetype + \"/\" + platform + \"/v\" + str(startversion + 1) + \"/\" + devicetype + \"_\" + platform_short + \"_v\" + str(startversion + 1) + \".cfg\", \n",
" convert_config.get_config(root + \"/\" + devicetype + \"/\" + platform + \"/v\" + str(startversion) + \"/\" + devicetype + \"_\" + platform_short + \"_v\" + str(startversion) + \".cfg\"),\n",
" root + \"/\" + devicetype + \"/\" + platform + \"/v\" + str(startversion + 1) + \"/pub\" , \n",
" root + \"/\" + devicetype + \"/\" + platform + \"/v\" + str(startversion + 1) + \"/sub\")"
]
}
],

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,174 @@
import json, uuid, os
from common.Logger import logger
from quickfaas.remotebus import publish
from paho.mqtt import client
from quickfaas.global_dict import get as get_params
from quickfaas.global_dict import _set_global_args
def reboot():
logger.info("!" * 10 + "REBOOTING DEVICE" + "!"*10)
r = os.popen("kill -s SIGHUP `cat /var/run/python/supervisord.pid`").read()
logger.info(f"REBOOT : {r}")
def checkFileExist(filename):
path = "/var/user/files"
if not os.path.exists(path):
logger.info("no folder making files folder in var/user")
os.makedirs(path)
with open(path + "/" + filename, "a") as f:
json.dump({}, f)
if not os.path.exists(path + "/" + filename):
logger.info("no creds file making creds file")
with open(path + "/" + filename, "a") as f:
json.dump({}, f)
def convertDStoJSON(ds):
j = dict()
for x in ds:
j[x["key"]] = x["value"]
return j
def convertJSONtoDS(j):
d = []
for key in j.keys():
d.append({"key": key, "value": j[key]})
return d
def checkCredentialConfig():
logger.info("CHECKING CONFIG")
cfgpath = "/var/user/cfg/device_supervisor/device_supervisor.cfg"
credspath = "/var/user/files/creds.json"
cfg = dict()
with open(cfgpath, "r") as f:
cfg = json.load(f)
clouds = cfg.get("clouds")
logger.info(clouds)
#if not configured then try to configure from stored values
if clouds[0]["args"]["clientId"] == "unknown" or clouds[0]["args"]["username"] == "unknown" or not clouds[0]["args"]["passwd"] or clouds[0]["args"]["passwd"] == "unknown":
checkFileExist("creds.json")
with open(credspath, "r") as c:
creds = json.load(c)
if creds:
logger.info("updating config with stored data")
clouds[0]["args"]["clientId"] = creds["clientId"]
clouds[0]["args"]["username"] = creds["userName"]
clouds[0]["args"]["passwd"] = creds["password"]
cfg["clouds"] = clouds
cfg = checkParameterConfig(cfg)
with open(cfgpath, "w", encoding='utf-8') as n:
json.dump(cfg, n, indent=1, ensure_ascii=False)
reboot()
else:
#assuming clouds is filled out, if data is different then assume someone typed in something new and store it, if creds is empty fill with clouds' data
checkFileExist("creds.json")
with open(credspath, "r") as c:
logger.info("updating stored file with new data")
cfg = checkParameterConfig(cfg)
with open(cfgpath, "w", encoding='utf-8') as n:
json.dump(cfg, n, indent=1, ensure_ascii=False)
creds = json.load(c)
if creds:
if creds["clientId"] != clouds[0]["args"]["clientId"]:
creds["clientId"] = clouds[0]["args"]["clientId"]
if creds["userName"] != clouds[0]["args"]["username"]:
creds["userName"] = clouds[0]["args"]["username"]
if creds["password"] != clouds[0]["args"]["passwd"]:
creds["password"] = clouds[0]["args"]["passwd"]
else:
creds["clientId"] = clouds[0]["args"]["clientId"]
creds["userName"] = clouds[0]["args"]["username"]
creds["password"] = clouds[0]["args"]["passwd"]
with open(credspath, "w") as cw:
json.dump(creds,cw)
def checkParameterConfig(cfg):
logger.info("Checking Parameters!!!!")
paramspath = "/var/user/files/params.json"
cfgparams = convertDStoJSON(cfg.get("labels"))
#check stored values
checkFileExist("params.json")
with open(paramspath, "r") as f:
logger.info("Opened param storage file")
params = json.load(f)
if params:
if cfgparams != params:
#go through each param
#if not "unknown" and cfg and params aren't the same take from cfg likely updated manually
#if key in cfg but not in params copy to params
logger.info("equalizing params between cfg and stored")
for key in cfgparams.keys():
try:
if cfgparams[key] != params[key] and cfgparams[key] != "unknown":
params[key] = cfgparams[key]
except:
params[key] = cfgparams[key]
cfg["labels"] = convertJSONtoDS(params)
_set_global_args(convertJSONtoDS(params))
with open(paramspath, "w") as p:
json.dump(params, p)
else:
with open(paramspath, "w") as p:
logger.info("initializing param file with params in memory")
json.dump(convertDStoJSON(get_params()), p)
cfg["labels"] = get_params()
return cfg
lwtData = {
"init":False,
"client": client.Client(client_id=str(uuid.uuid4()), clean_session=True, userdata=None, protocol=client.MQTTv311, transport="tcp")
}
def lwt(mac):
try:
#if not lwtData["connected"]:
if not lwtData["init"]:
print("INITIALIZING LWT CLIENT")
lwtData["client"].username_pw_set(username="admin", password="columbus")
lwtData["client"].will_set("meshify/db/194/_/mainHP/" + mac + ":00:00/connected",json.dumps([{"value":False}]))
lwtData["client"].reconnect_delay_set(min_delay=10, max_delay=120)
lwtData["init"] = True
print("Connecting to MQTT Broker for LWT purposes!!!!!!!")
lwtData["client"].connect("mq194.imistaway.net",1883, 600)
lwtData["client"].reconnect()
lwtData["client"].publish("meshify/db/194/_/mainHP/" + mac + ":00:00/connected", json.dumps([{"value":True}]))
except Exception as e:
print("LWT DID NOT DO THE THING")
print(e)
def sendData(message):
#logger.debug(message)
mac = __topic__.split("/")[-1]
lwt(mac)
checkCredentialConfig()
for measure in message["measures"]:
try:
logger.debug(measure)
if measure["name"] in ["pump_1_run_status", "pump_2_run_status", "charge_pump_run_status"]:
logger.debug("Converting DINT/BOOL to STRING")
value = convert_int(measure["name"], measure["value"])
logger.debug("Converted {} to {}".format(measure["value"], value))
publish(__topic__ + ":01:99/" + measure["name"], json.dumps({"value": value}), __qos__)
else:
publish(__topic__ + ":01:99/" + measure["name"], json.dumps({"value": measure["value"]}), __qos__)
except Exception as e:
logger.error(e)
def convert_int(plc_tag, value):
status_codes = {
0: "Off",
1: "On"
}
plc_tags = {
"pump_1_run_status": status_codes.get(value, "Invalid Code"),
"pump_2_run_status": status_codes.get(value, "Invalid Code"),
"charge_pump_run_status": status_codes.get(value, "Invalid Code")
}
return plc_tags.get(plc_tag, "Invalid Tag")

View File

@@ -0,0 +1,73 @@
# Enter your python code.
import json
from quickfaas.measure import recall
from common.Logger import logger
def sync(mac,value, wizard_api):
#get new values and send
try:
data = recall()#json.loads(recall().decode("utf-8"))
except Exception as e:
logger.error(e)
logger.info(data)
for controller in data:
for measure in controller["measures"]:
#publish measure
topic = "meshify/db/194/_/dual_flowmeter/" + mac + "/" + measure["name"]
if measure["name"] in ["pump_1_run_status", "pump_2_run_status", "charge_pump_run_status"]:
payload = [{"value": convert_int(measure["name"], measure["value"])}]
else:
payload = [{"value": measure["value"]}]
logger.debug("Sending on topic: {}".format(topic))
logger.debug("Sending value: {}".format(payload))
wizard_api.mqtt_publish(topic, json.dumps(payload))
def writeplctag(mac, value, wizard_api):
try:
value = json.loads(value.replace("'",'"'))
logger.debug(value)
message = {"advvfdipp":{value["tag"]: value["val"]}}
wizard_api.write_plc_values(message)
except Exception as e:
logger.debug(e)
def receiveCommand(topic, payload, wizard_api):
logger.debug(topic)
logger.debug(json.loads(payload))
p = json.loads(payload)[0]
command = p["payload"]["name"].split(".")[1]
commands = {
"sync": sync,
"writeplctag": writeplctag,
}
commands[command](p["mac"].lower(),p["payload"]["value"], wizard_api)
#logger.debug(command)
ack(p["msgId"], p["mac"], command, p["payload"]["name"].split(".")[1], p["payload"]["value"], wizard_api)
def ack(msgid, mac, name, command, value, wizard_api):
#logger.debug(mac)
macsquish = "".join(mac.split(":")[:-2])
maclower = ":".join(mac.split(":")[:-2])
maclower = maclower.lower()
#logger.debug(msgid)
#logger.debug(mac)
#logger.debug(name)
#logger.debug(value)
wizard_api.mqtt_publish("meshify/responses/" + str(msgid), json.dumps([{"value": "{} Success Setting: {} To: {}".format(macsquish,name, value), "msgid": str(msgid)}]))
wizard_api.mqtt_publish("meshify/db/194/_/mainMeshify/" + maclower + ":00:00/commands", json.dumps([{"value": {"status": "success", "value": str(value), "channel": command}, "msgid": str(msgid)}]))
def convert_int(plc_tag, value):
status_codes = {
0: "Off",
1: "On"
}
plc_tags = {
"pump_1_run_status": status_codes.get(value, "Invalid Code"),
"pump_2_run_status": status_codes.get(value, "Invalid Code"),
"charge_pump_run_status": status_codes.get(value, "Invalid Code")
}
return plc_tags.get(plc_tag, "Invalid Tag")

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,12 @@
# Enter your python code.
import json, time
from common.Logger import logger
from quickfaas.remotebus import publish
def sendAlarm(message):
logger.info(message)
payload = {}
payload["ts"] = time.time()*1000
payload["values"] = {message["measureName"]: message["value"]}
publish(__topic__, json.dumps(payload), __qos__)

View File

@@ -0,0 +1,135 @@
# Enter your python code.
import json, os
from datetime import datetime as dt
from common.Logger import logger
from quickfaas.remotebus import publish
from quickfaas.global_dict import get as get_params
from quickfaas.global_dict import _set_global_args
def reboot():
#basic = Basic()
logger.info("!" * 10 + "REBOOTING DEVICE" + "!"*10)
r = os.popen("kill -s SIGHUP `cat /var/run/python/supervisord.pid`").read()
logger.info(f"REBOOT : {r}")
def checkFileExist(filename):
path = "/var/user/files"
if not os.path.exists(path):
logger.info("no folder making files folder in var/user")
os.makedirs(path)
with open(path + "/" + filename, "a") as f:
json.dump({}, f)
if not os.path.exists(path + "/" + filename):
logger.info("no creds file making creds file")
with open(path + "/" + filename, "a") as f:
json.dump({}, f)
def convertDStoJSON(ds):
j = dict()
for x in ds:
j[x["key"]] = x["value"]
return j
def convertJSONtoDS(j):
d = []
for key in j.keys():
d.append({"key": key, "value": j[key]})
return d
def checkCredentialConfig():
logger.info("CHECKING CONFIG")
cfgpath = "/var/user/cfg/device_supervisor/device_supervisor.cfg"
credspath = "/var/user/files/creds.json"
cfg = dict()
with open(cfgpath, "r") as f:
cfg = json.load(f)
clouds = cfg.get("clouds")
logger.info(clouds)
#if not configured then try to configure from stored values
if clouds[0]["args"]["clientId"] == "unknown" or clouds[0]["args"]["username"] == "unknown" or not clouds[0]["args"]["passwd"] or clouds[0]["args"]["passwd"] == "unknown":
checkFileExist("creds.json")
with open(credspath, "r") as c:
creds = json.load(c)
if creds:
logger.info("updating config with stored data")
clouds[0]["args"]["clientId"] = creds["clientId"]
clouds[0]["args"]["username"] = creds["userName"]
clouds[0]["args"]["passwd"] = creds["password"]
cfg["clouds"] = clouds
cfg = checkParameterConfig(cfg)
with open(cfgpath, "w", encoding='utf-8') as n:
json.dump(cfg, n, indent=1, ensure_ascii=False)
reboot()
else:
#assuming clouds is filled out, if data is different then assume someone typed in something new and store it, if creds is empty fill with clouds' data
checkFileExist("creds.json")
with open(credspath, "r") as c:
logger.info("updating stored file with new data")
cfg = checkParameterConfig(cfg)
with open(cfgpath, "w", encoding='utf-8') as n:
json.dump(cfg, n, indent=1, ensure_ascii=False)
creds = json.load(c)
if creds:
if creds["clientId"] != clouds[0]["args"]["clientId"]:
creds["clientId"] = clouds[0]["args"]["clientId"]
if creds["userName"] != clouds[0]["args"]["username"]:
creds["userName"] = clouds[0]["args"]["username"]
if creds["password"] != clouds[0]["args"]["passwd"]:
creds["password"] = clouds[0]["args"]["passwd"]
else:
creds["clientId"] = clouds[0]["args"]["clientId"]
creds["userName"] = clouds[0]["args"]["username"]
creds["password"] = clouds[0]["args"]["passwd"]
with open(credspath, "w") as cw:
json.dump(creds,cw)
def checkParameterConfig(cfg):
logger.info("Checking Parameters!!!!")
paramspath = "/var/user/files/params.json"
cfgparams = convertDStoJSON(cfg.get("labels"))
#check stored values
checkFileExist("params.json")
with open(paramspath, "r") as f:
logger.info("Opened param storage file")
params = json.load(f)
if params:
if cfgparams != params:
#go through each param
#if not "unknown" and cfg and params aren't the same take from cfg likely updated manually
#if key in cfg but not in params copy to params
logger.info("equalizing params between cfg and stored")
for key in cfgparams.keys():
try:
if cfgparams[key] != params[key] and cfgparams[key] != "unknown":
params[key] = cfgparams[key]
except:
params[key] = cfgparams[key]
cfg["labels"] = convertJSONtoDS(params)
_set_global_args(convertJSONtoDS(params))
with open(paramspath, "w") as p:
json.dump(params, p)
else:
with open(paramspath, "w") as p:
logger.info("initializing param file with params in memory")
json.dump(convertDStoJSON(get_params()), p)
cfg["labels"] = get_params()
return cfg
def sendData(message):
#logger.debug(message)
try:
checkCredentialConfig()
except Exception as e:
logger.error(e)
payload = {"ts": (round(dt.timestamp(dt.now())/600)*600)*1000, "values": {}}
for measure in message["measures"]:
try:
logger.debug(measure)
payload["values"][measure["name"]] = measure["value"]
except Exception as e:
logger.error(e)
publish(__topic__, json.dumps(payload), __qos__)
publish("v1/devices/me/attributes", json.dumps({"latestReportTime": (round(dt.timestamp(dt.now())/600)*600)*1000}), __qos__)

View File

@@ -0,0 +1,66 @@
import json, time
from quickfaas.measure import recall, write
from quickfaas.remotebus import publish
from common.Logger import logger
def sync():
#get new values and send
payload = {}
topic = "v1/devices/me/telemetry"
try:
data = recall()#json.loads(recall().decode("utf-8"))
except Exception as e:
logger.error(e)
logger.debug(data)
for controller in data:
for measure in controller["measures"]:
#publish measure
payload[measure["name"]] = measure["value"]
logger.debug("Sending on topic: {}".format(topic))
logger.debug("Sending value: {}".format(payload))
publish(topic, json.dumps(payload), 1)
def writeplctag(value):
#value in the form {"measurement": <measurement_name>, "value": <value to write>}
try:
#value = json.loads(value.replace("'",'"'))
logger.debug(value)
#payload format: [{"name": "advvfdipp", "measures": [{"name": "manualfrequencysetpoint", "value": 49}]}]
message = [{"name": "hrtankbattery", "measures":[{"name":value["measurement"], "value": value["value"]}]}]
resp = write(message)
logger.debug("RETURN FROM WRITE: {}".format(resp))
return True
except Exception as e:
logger.debug(e)
return False
def receiveCommand(topic, payload):
try:
logger.debug(topic)
logger.debug(json.loads(payload))
p = json.loads(payload)
command = p["method"]
commands = {
"sync": sync,
"writeplctag": writeplctag,
}
if command == "setPLCTag":
try:
result = commands["writeplctag"](p["params"])
logger.debug(result)
except Exception as e:
logger.error(e)
#logger.debug(command)
ack(topic.split("/")[-1])
time.sleep(5)
sync()
except Exception as e:
logger.debug(e)
def ack(msgid):
#logger.debug(msgid)
#logger.debug(mac)
#logger.debug(name)
#logger.debug(value)
publish("v1/devices/me/rpc/response/" + str(msgid), json.dumps({"msg": {"time": time.time()}, "metadata": "", "msgType": ""}), 1)