diff options
| author | pks <pks@pks.rocks> | 2020-09-27 20:55:18 +0200 | 
|---|---|---|
| committer | pks <pks@pks.rocks> | 2020-09-27 20:55:18 +0200 | 
| commit | 1123b0db81b6057e113f16a1ddea15c36b7b3d79 (patch) | |
| tree | b749c4cc5c3a63441ad408d56dd84cc7645a6201 /mqtt-receiver.py | |
init
Diffstat (limited to 'mqtt-receiver.py')
| -rw-r--r-- | mqtt-receiver.py | 27 | 
1 files changed, 27 insertions, 0 deletions
| diff --git a/mqtt-receiver.py b/mqtt-receiver.py new file mode 100644 index 0000000..3d6cd8a --- /dev/null +++ b/mqtt-receiver.py @@ -0,0 +1,27 @@ +import json +import paho.mqtt.client as mqtt +import sys + + +def on_connect(client, userdata, flags, rc): +    client.subscribe("#")  # Subscribe to all topics +    sys.stderr.write("Connected with result code {}\n".format(rc)) +    sys.stderr.flush() + + +def on_message(client, userdata, msg): +    msg_as_str = msg.payload.decode('utf-8') +    try: +        print("{}\t{}\t{}".format(msg.timestamp, msg.topic, json.loads(msg_as_str))) +        sys.stdout.flush() +    except Exception as e: +        sys.stderr.write("Cannot parse message: '{}'\n".format(msg_as_str)) +        sys.stderr.flush() + + +if __name__ == "__main__": +    client = mqtt.Client() +    client.on_connect = on_connect +    client.on_message = on_message +    client.connect("localhost", 1883, 60) +    client.loop_forever() | 
