How to Use MQTT in Python

Installation

MQTT (Message Queuing Telemetry Transport), is a lightweight publish/subscribe messaging protocol.

More information about MQTT: https://en.wikipedia.org/wiki/MQTT

Install paho-mqtt library in Python:

1
pip install paho-mqtt

Example

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
28
29
30
31
32
33
34
import paho.mqtt.client as mqtt


# Callback function for successful connection
def on_connect(client, userdata, flags, rc):
print("Connected with result code " + str(rc))
# Subscribe to a topic, here we take "test/topic" as an example
client.subscribe("test/topic")


# Callback function for receiving messages
def on_message(client, userdata, msg):
print("Topic: " + msg.topic + " Message: " + str(msg.payload))


# Callback function for publishing messages
def on_publish(client, userdata, mid):
print(f"Message {mid} published.")


# Set up MQTT client
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.on_publish = on_publish

# Connect to MQTT broker, here we take localhost as an example, the default port is 1883
client.connect(host="localhost", port=1883, keepalive=60)
# client.username_pw_set("admin", "123456")

# Publish a message to a specified topic
client.publish("test/topic", "MQTT test")

client.loop_forever()