summaryrefslogtreecommitdiff
path: root/mqtt-receiver.py
blob: 3d6cd8ac1eac9c1b0ba7ea62fb5d7ab5639c75e1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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()