Updates MQTT service
This commit is contained in:
@@ -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
|
||||
service = MQTTService("127.0.0.1", 1883)
|
||||
service.publish("test", "test", "Hello from MQTT", 1)
|
||||
Reference in New Issue
Block a user