import datetime import json import time from services.mqtt_service import MQTTService class MQTTForwarder: _client_id : str _local_broker : MQTTService _central_broker : MQTTService _qos : int def __init__(self, client_id : str, src_mqtt: MQTTService, dst_mqtt: MQTTService, qos : int): self._client_id = client_id self._local_broker = src_mqtt self._central_broker = dst_mqtt self._qos = qos def start(self, src_topic: str, dst_topic: str, sensor_type: str): try: def forward_handler(topic: str, msg: str): forwarded_msg = self.__wrap_data(msg, sensor_type) self._central_broker.publish(dst_topic, forwarded_msg, self._qos) 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, sensor_type: str): print(repr(msg)) result = {} data = json.loads(msg) result["timestamp"] = int(time.time()) result["systemId"] = self._client_id result["type"] = sensor_type result["data"] = {} for keys in data: result["data"][keys] = data[keys] return json.dumps(result)