Files
board-mate/rpi/controllers/mqtt_forwarder.py
2025-12-30 14:42:53 +01:00

37 lines
1.1 KiB
Python

import datetime
import json
import time
from services.mqtt_service import MQTTService
class MQTTForwarder:
client_id : str
local_broker : MQTTService
central_broker : MQTTService
def __init__(self, client_id : str, local_mqtt: MQTTService, central_mqtt: MQTTService):
self.client_id = client_id
self.local_broker = local_mqtt
self.central_broker = central_mqtt
def start(self, src_topic: str, dst_topic: str):
try:
def forward_handler(topic: str, msg: str):
forwarded_msg = self.__wrap_data(msg)
self.central_broker.publish(dst_topic, forwarded_msg)
self.local_broker.subscribe(src_topic, forward_handler)
except Exception as e:
print(f"An error occurred while forwarding from {src_topic} to {dst_topic}: {e}")
def __wrap_data(self, msg : str):
print(msg)
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]
return result