Format JSON payload

This commit is contained in:
2025-12-30 14:13:20 +01:00
parent 4828a70e78
commit 32d6da6f0c
4 changed files with 21 additions and 11 deletions

Binary file not shown.

View File

@@ -276,10 +276,9 @@ char* gps_to_json(char* gps_data) {
longitude = nmea_to_decimal(fields[4], fields[5][0]); longitude = nmea_to_decimal(fields[4], fields[5][0]);
} }
} }
snprintf(json, sizeof(json), "{\"data\":{\"latitude\":%.6f,\"longitude\":%.6f}}", time_t current_time = time(NULL);
latitude, longitude); snprintf(json, sizeof(json), "{\"latitude\":%.6f,\"longitude\":%.6f}", latitude, longitude);
return json; return json;
} }

View File

@@ -1,3 +1,7 @@
import datetime
import json
import time
from services.mqtt_service import MQTTService from services.mqtt_service import MQTTService
class MQTTForwarder: class MQTTForwarder:
@@ -14,8 +18,19 @@ class MQTTForwarder:
def start(self, src_topic: str, dst_topic: str): def start(self, src_topic: str, dst_topic: str):
try: try:
def forward_handler(topic: str, msg: str): def forward_handler(topic: str, msg: str):
self.central_broker.publish(dst_topic, msg) forwarded_msg = self.__wrapData(msg)
self.central_broker.publish(dst_topic, forwarded_msg)
self.local_broker.subscribe(src_topic, forward_handler) self.local_broker.subscribe(src_topic, forward_handler)
except Exception as e: except Exception as e:
print(f"An error occurred while forwarding from {src_topic} to {dst_topic}: {e}") print(f"An error occurred while forwarding from {src_topic} to {dst_topic}: {e}")
def __wrapData(self, msg : str):
result = {}
data = json.loads(msg)
result["timestamp"] = int(time.time())
result["systemId"] = self.client_id
result["data"] = {}
for keys in data:
result["data"][keys] = data[keys]

View File

@@ -65,11 +65,7 @@ class MQTTService:
def publish(self, topic: str, data: str, qos: int = 0): def publish(self, topic: str, data: str, qos: int = 0):
try: try:
self.connect() self.connect()
payload = { result = self.client.publish(topic, json.dumps(data), qos=qos)
"timestamp": int(time.time()),
"data": data
}
result = self.client.publish(topic, json.dumps(payload), qos=qos)
result.wait_for_publish() result.wait_for_publish()
except Exception as e: except Exception as e:
print(f"An error occurred while publishing on {topic} on {self.address} : {e}") print(f"An error occurred while publishing on {topic} on {self.address} : {e}")