1#!/usr/local/bin/python3.8
2# -*- coding: utf-8 -*-
3
4# Copyright (c) 2014 Roger Light <roger@atchoo.org>
5#
6# All rights reserved. This program and the accompanying materials
7# are made available under the terms of the Eclipse Distribution License v1.0
8# which accompanies this distribution.
9#
10# The Eclipse Distribution License is available at
11#   http://www.eclipse.org/org/documents/edl-v10.php.
12#
13# Contributors:
14#    Roger Light - initial implementation
15# All rights reserved.
16
17# This shows a simple example of an MQTT subscriber using a per-subscription message handler.
18
19import context  # Ensures paho is in PYTHONPATH
20import paho.mqtt.client as mqtt
21
22
23def on_message_msgs(mosq, obj, msg):
24    # This callback will only be called for messages with topics that match
25    # $SYS/broker/messages/#
26    print("MESSAGES: " + msg.topic + " " + str(msg.qos) + " " + str(msg.payload))
27
28
29def on_message_bytes(mosq, obj, msg):
30    # This callback will only be called for messages with topics that match
31    # $SYS/broker/bytes/#
32    print("BYTES: " + msg.topic + " " + str(msg.qos) + " " + str(msg.payload))
33
34
35def on_message(mosq, obj, msg):
36    # This callback will be called for messages that we receive that do not
37    # match any patterns defined in topic specific callbacks, i.e. in this case
38    # those messages that do not have topics $SYS/broker/messages/# nor
39    # $SYS/broker/bytes/#
40    print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload))
41
42
43mqttc = mqtt.Client()
44
45# Add message callbacks that will only trigger on a specific subscription match.
46mqttc.message_callback_add("$SYS/broker/messages/#", on_message_msgs)
47mqttc.message_callback_add("$SYS/broker/bytes/#", on_message_bytes)
48mqttc.on_message = on_message
49mqttc.connect("mqtt.eclipse.org", 1883, 60)
50mqttc.subscribe("$SYS/#", 0)
51
52mqttc.loop_forever()
53