From 80f30d90a33464449eb204fc96cbd023599065da Mon Sep 17 00:00:00 2001 From: Gabriel Date: Tue, 7 May 2024 10:31:34 +0200 Subject: [PATCH] 1er commit --- .gitignore | 1 + README.md | 11 ++++++++++ mqtt.py | 47 +++++++++++++++++++++++++++++++++++++++++ mqtt_config_sample.json | 6 ++++++ 4 files changed, 65 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 mqtt.py create mode 100644 mqtt_config_sample.json diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8afb961 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +mqtt_config.json diff --git a/README.md b/README.md new file mode 100644 index 0000000..2430bfd --- /dev/null +++ b/README.md @@ -0,0 +1,11 @@ +# Programme test MQTT + +- S'abonne à un topic +- Récupère la partie "data" du JSON +- Parse et afficher les données encodées en Cayenne LPP puis en base64 + + +## Usage + +- Copier le fichier mqtt_config_sample.json en mqtt_config.json +- Éxécuter le script diff --git a/mqtt.py b/mqtt.py new file mode 100644 index 0000000..de3e888 --- /dev/null +++ b/mqtt.py @@ -0,0 +1,47 @@ +import paho.mqtt.client as mqtt +import json +import base64 +from cayennelpp import LppFrame +import datetime + +def on_connect(client, userdata, flags, rc): + if rc == 0: + print("Connected to MQTT broker") + client.subscribe(topic) + else: + print("Failed to connect, return code %d\n", rc) + +def on_message(client, userdata, message): + #print("Received message: ", str(message.payload.decode("utf-8"))) + parsed_json = json.loads(str(message.payload.decode("utf-8"))) + data_part = parsed_json["data"] + # print("Data:", data_part) + decoded_data = base64.b64decode(data_part) + #print("data :", decoded_data.hex()) + bytearray_data = bytearray.fromhex(decoded_data.hex()) + frame = LppFrame().from_bytes(bytearray_data) + print(datetime.datetime.now()) + for d in frame.data: + print(d) + print("---------------------------------") + +def read_config(config_file): + with open(config_file, 'r') as f: + config = json.load(f) + return config + +if __name__ == "__main__": + config = read_config('mqtt_config.json') + + broker_address = config['broker_address'] + port = config['port'] + topic = config['topic'] + + client = mqtt.Client() + client.on_connect = on_connect + client.on_message = on_message + + client.connect(broker_address, port) + + client.loop_forever() + diff --git a/mqtt_config_sample.json b/mqtt_config_sample.json new file mode 100644 index 0000000..a4fd343 --- /dev/null +++ b/mqtt_config_sample.json @@ -0,0 +1,6 @@ +{ + "broker_address": "", + "port": 1883, + "topic": "" +} +