Skip to content

Commit 0c7aa2f

Browse files
authored
Merge pull request #47 from zhongys-c8y/always-add-time
feat: add time into the telemetry payload
2 parents ae286a1 + f4848ce commit 0c7aa2f

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

tedge_modbus/reader/mapper.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,16 @@ class MappedMessage:
2020

2121
data: str = ""
2222
topic: str = ""
23+
time: str = datetime.now(timezone.utc).isoformat()
24+
25+
def serialize(self):
26+
"""Serialize message adding time if not present"""
27+
if "/cmd/" in self.topic:
28+
return self.data
29+
out = json.loads(self.data)
30+
if "time" not in out:
31+
out["time"] = self.time
32+
return json.dumps(out)
2333

2434
def extend_data(self, other_message):
2535
"""Combine Json data of two messages with the same topic"""
@@ -40,6 +50,10 @@ def merge(d1: dict, d2: dict) -> dict:
4050
d2 = json.loads(other_message.data)
4151
# Merge the dictionaries
4252
merged = merge(d1, d2)
53+
54+
if "time" not in merged:
55+
merged["time"] = self.time
56+
4357
# Convert the merged dictionary back to a JSON string and update self.data
4458
self.data = json.dumps(merged)
4559

tedge_modbus/reader/reader.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -407,9 +407,9 @@ def send_tedge_message(
407407
self, msg: MappedMessage, retain: bool = False, qos: int = 0
408408
):
409409
"""Send a thin-edge.io message via MQTT"""
410-
self.logger.debug("sending message %s to topic %s", msg.data, msg.topic)
410+
self.logger.debug("sending message %s to topic %s", msg.serialize(), msg.topic)
411411
self.tedge_client.publish(
412-
topic=msg.topic, payload=msg.data, retain=retain, qos=qos
412+
topic=msg.topic, payload=msg.serialize(), retain=retain, qos=qos
413413
)
414414

415415
def on_connect(

0 commit comments

Comments
 (0)