35 lines
1004 B
Python
35 lines
1004 B
Python
import paho.mqtt.client as mqtt
|
|
import json
|
|
import time
|
|
import base64
|
|
|
|
class MQTTService:
|
|
|
|
def __init__(self, address: str, port: int):
|
|
self.address = address
|
|
self.port = port
|
|
|
|
def publish(self, client_id: str, topic: str, message: str, qos: int = 0):
|
|
client = mqtt.Client(client_id=client_id)
|
|
try:
|
|
client.connect(self.address, self.port)
|
|
client.loop_start()
|
|
data = str(message).encode()
|
|
|
|
payload = {
|
|
"timestamp": int(time.time()),
|
|
"data": base64.b64encode(data).decode('utf-8')
|
|
}
|
|
result = client.publish(topic, json.dumps(payload), qos=qos)
|
|
result.wait_for_publish()
|
|
|
|
except Exception as e:
|
|
print("Erreur MQTT:", e)
|
|
finally:
|
|
client.loop_stop()
|
|
client.disconnect()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
service = MQTTService("127.0.0.1", 1883)
|
|
service.publish("test", "test", "Hello from MQTT", 1) |