import json, os, uuid 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(): #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 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] #':'.join(re.findall('..', '%012x' % uuid.getnode())) lwt(mac) checkCredentialConfig() plc_ping = os.system("ping -c 1 192.168.1.101 > /dev/null 2>&1") if plc_ping == 0: publish(__topic__ + ":01:99/" + "plc_ping", json.dumps({"value": "OK"}), __qos__) else: publish(__topic__ + ":01:99/" + "plc_ping", json.dumps({"value": "Comms Error to PLC"}), __qos__) for measure in message["measures"]: try: logger.debug(measure) if measure["name"] in ["raw_hand_input", "raw_auto_input", "raw_run_status", "raw_local_start","raw_overload_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): input_codes = { 0: "Off", 1: "On" } run_status_codes = { 0: "Stopped", 1: "Running" } overload_codes = { 0: "Good", 1: "Down on Overload Tripped" } plc_tags = { "raw_hand_input": input_codes.get(value, "Invalid Code"), "raw_auto_input": input_codes.get(value, "Invalid Code"), "raw_run_status": run_status_codes.get(value, "Invalid Code"), "raw_overload_status": overload_codes.get(value, "Invalid Code") } return plc_tags.get(plc_tag, "Invalid Tag")