89 lines
3.0 KiB
Python
89 lines
3.0 KiB
Python
# Enter your python code.
|
|
import json, time
|
|
from datetime import datetime as dt
|
|
from common.Logger import logger
|
|
from quickfaas.remotebus import publish
|
|
|
|
report_period = 600
|
|
|
|
def chunk_payload(payload, chunk_size=20):
|
|
if "values" in payload:
|
|
# Original format: {"ts": ..., "values": {...}}
|
|
chunked_values = list(payload["values"].items())
|
|
for i in range(0, len(chunked_values), chunk_size):
|
|
yield {
|
|
"ts": payload["ts"],
|
|
"values": dict(chunked_values[i:i+chunk_size])
|
|
}
|
|
else:
|
|
# New format: {"key1": "value1", "key2": "value2"}
|
|
chunked_keys = list(payload.keys())
|
|
for i in range(0, len(chunked_keys), chunk_size):
|
|
yield {k: payload[k] for k in chunked_keys[i:i+chunk_size]}
|
|
|
|
def sendData(message):
|
|
#logger.debug(message)
|
|
payload = {"ts": (round(dt.timestamp(dt.now())/report_period)*report_period)*1000, "values": {}}
|
|
attributes_payload = {}
|
|
for measure in message["measures"]:
|
|
try:
|
|
logger.debug(measure)
|
|
if measure["health"] == 1:
|
|
if measure["name"] in ["auto_manual", "system1_hasleveltransmitter", "system2_hasleveltransmitter", "state_supervisor", "state_system1", "state_system2"]:
|
|
logger.debug("Converting DINT/BOOL to STRING")
|
|
payload["values"][measure["name"]] = convert_int(measure["name"], measure["value"])
|
|
payload["values"][measure["name"] + "_int"] = measure["value"]
|
|
else:
|
|
payload["values"][measure["name"]] = measure["value"]
|
|
except Exception as e:
|
|
logger.error(e)
|
|
|
|
for chunk in chunk_payload(payload=payload):
|
|
publish(__topic__, json.dumps(chunk), __qos__, cloud_name="ThingsBoard")
|
|
time.sleep(2)
|
|
|
|
attributes_payload["latestReportTime"] = (round(dt.timestamp(dt.now())/report_period)*report_period)*1000
|
|
for chunk in chunk_payload(payload=attributes_payload):
|
|
publish("v1/devices/me/attributes", json.dumps(chunk), __qos__, cloud_name="ThingsBoard")
|
|
time.sleep(2)
|
|
|
|
def convert_int(plc_tag, value):
|
|
|
|
|
|
TRUE_FALSE = {
|
|
0: "false",
|
|
1: "true"
|
|
}
|
|
|
|
AUTO_MANUAL = {
|
|
0: "Auto",
|
|
1: "Manual"
|
|
}
|
|
|
|
PHASE_STATES = {
|
|
1: "Running",
|
|
2: "Holding",
|
|
4: "Restarting",
|
|
8: "Stopping",
|
|
16: "Aborting",
|
|
32: "Resetting",
|
|
64: "Idle",
|
|
128: "Held",
|
|
256: "Complete",
|
|
512: "Stopped",
|
|
1024: "Aborted"
|
|
}
|
|
|
|
|
|
plc_tags = {
|
|
"auto_manual": AUTO_MANUAL.get(value, "Invalid Code"),
|
|
"system1_hasleveltransmitter": TRUE_FALSE.get(value, "Invalid Code"),
|
|
"system2_hasleveltransmitter": TRUE_FALSE.get(value, "Invalid Code"),
|
|
"state_supervisor": PHASE_STATES.get(value, "Invalid Code"),
|
|
"state_system1": PHASE_STATES.get(value, "Invalid Code"),
|
|
"state_system2": PHASE_STATES.get(value, "Invalid Code")
|
|
}
|
|
|
|
return plc_tags.get(plc_tag, "Invalid Tag")
|
|
|
|
|