MQTT Tutorial With Python
Contents
Install paho-mqtt Plugin ✈️
pip install paho-mqtt
Or
pip3 install paho-mqtt
Check paho-mqtt Plugin ✈️
C:\>pip list ↩️
Package Version
---------- -------
paho-mqtt 1.6.1 ⬅️ Successfully installed paho-mqtt-1.6.1
pip 22.3.1
setuptools 65.5.0
Getting Started – Create a Subscribe
Use a free MQTT server
- test.mosquitto.org
- ports : 1884
- username : rw
- password : readwrite
import paho.mqtt.client as mqtt
# The callback function that will be executed
# when connecting to the MQTT server
def on_connect(client, userdata, flags, rc):
print("Connected with result code " + str(rc))
# Subscriptions can be set in on_connet,
# and will be re-subscribed if the connection
# is lost or reconnected
client.subscribe("$SYS/#")
# The callback function to be performed
# when receiving a message sent from the MQTT server
def on_message(client, userdata, msg):
# Convert encoding to utf-8 or not
print(msg.topic + " " +
str(msg.payload.decode("utf-8")))
# Initialize the my_client
my_client = mqtt.Client()
# Set the callback function after connection
my_client.on_connect = on_connect
# Set the callback function after receiving
my_client.on_message = on_message
# Set login account and password
my_client.username_pw_set("rw", "readwrite")
# Set connection parameters (IP, Port, connection time)
my_client.connect("test.mosquitto.org", 1884, 60)
# Start the connection, execute the set action
# and loop_forever can handle the reconnection problem
# You can also manually use other loop functions to connect
my_client.loop_forever()
Results
Connected with result code 0
$SYS/broker/bytes/received 1534092578435
$SYS/broker/bytes/sent 32330049071821
$SYS/broker/clients/active 3489
$SYS/broker/clients/connected 3489
$SYS/broker/clients/disconnected 102900
$SYS/broker/clients/inactive 102900
$SYS/broker/clients/total 106389
$SYS/broker/connection/31d8cf14464a.famous/state 1
$SYS/broker/connection/31d8cf14464a.renningen/state 1
$SYS/broker/connection/4de57af3c5ab.mosquitto-bridge/state 0
Getting Started – Create a Publish / Subscribe
First, execute the following “subscribe” code.
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
client.subscribe("mqtt_topic/#")
def on_message(client, userdata, msg):
print("From > " + msg.topic + " : " +
str(msg.payload.decode("utf-8")))
my_client = mqtt.Client()
my_client.on_connect = on_connect
my_client.on_message = on_message
my_client.username_pw_set("rw", "readwrite")
my_client.connect("test.mosquitto.org", 1884, 60)
my_client.loop_forever()
Then execute the following “publish” code.
import paho.mqtt.client as mqtt
import json
msg = "Hello World"
my_client = mqtt.Client()
my_client.username_pw_set("rw", "readwrite")
my_client.connect("test.mosquitto.org", 1884, 60)
# The topic and content to publish
my_client.publish("mqtt_topic", json.dumps(msg))
You will see the following output in the subscribed terminal.
From > mqtt_topic : "Hello World"