From 2a77a4f4b4e2d03a8587c48257a72e98cb5fc933 Mon Sep 17 00:00:00 2001 From: Laurent Date: Fri, 26 Dec 2025 17:21:29 +0100 Subject: [PATCH] Updates MQTT service --- rpi/services/mqtt_service.py | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/rpi/services/mqtt_service.py b/rpi/services/mqtt_service.py index da3d74cc..a69525e9 100644 --- a/rpi/services/mqtt_service.py +++ b/rpi/services/mqtt_service.py @@ -1,32 +1,35 @@ import paho.mqtt.client as mqtt import json import time +import base64 class MQTTService: - address : str = None - port : int = None - - def __init__(self, address : str, port : int): + def __init__(self, address: str, port: int): self.address = address self.port = port - def publish(self, client_id : str, topic: str, data: bytes, qos: int = 0): + def publish(self, client_id: str, topic: str, message: str, qos: int = 0): client = mqtt.Client(client_id=client_id) - try : + try: client.connect(self.address, self.port) + client.loop_start() + data = str(message).encode() + payload = { "timestamp": int(time.time()), - "data": data, + "data": base64.b64encode(data).decode('utf-8') } - client.publish(topic, json.dumps(payload), qos) + result = client.publish(topic, json.dumps(payload), qos=qos) + result.wait_for_publish() except Exception as e: - print(e) + print("Erreur MQTT:", e) finally: client.loop_stop() client.disconnect() if __name__ == "__main__": - pass \ No newline at end of file + service = MQTTService("127.0.0.1", 1883) + service.publish("test", "test", "Hello from MQTT", 1) \ No newline at end of file