0
0
Drone-programmingHow-ToBeginner · 4 min read

How to Use MQTT with Python: Simple Guide and Example

To use MQTT with Python, install the paho-mqtt library and create a client that connects to an MQTT broker. Use client.publish() to send messages and client.subscribe() to receive messages asynchronously.
📐

Syntax

The basic steps to use MQTT in Python with paho-mqtt are:

  • Import the library: import paho.mqtt.client as mqtt
  • Create a client: client = mqtt.Client()
  • Connect to broker: client.connect('broker_address', port)
  • Subscribe to topics: client.subscribe('topic')
  • Publish messages: client.publish('topic', 'message')
  • Start loop: client.loop_start() to process network events

Callbacks like on_connect and on_message handle connection and incoming messages.

python
import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    print(f"Connected with result code {rc}")
    client.subscribe("test/topic")

def on_message(client, userdata, msg):
    print(f"Received message: {msg.payload.decode()} on topic {msg.topic}")

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("broker.hivemq.com", 1883, 60)
client.loop_start()

client.publish("test/topic", "Hello MQTT")
Output
Connected with result code 0 Received message: Hello MQTT on topic test/topic
💻

Example

This example connects to a public MQTT broker, subscribes to a topic, and publishes a message. It prints connection status and any received messages.

python
import time
import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    print(f"Connected with result code {rc}")
    client.subscribe("home/temperature")

def on_message(client, userdata, msg):
    print(f"Topic: {msg.topic}, Message: {msg.payload.decode()}")

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("broker.hivemq.com", 1883, 60)
client.loop_start()

# Publish a temperature reading
client.publish("home/temperature", "22.5")

# Wait to receive messages
time.sleep(2)
client.loop_stop()
Output
Connected with result code 0 Topic: home/temperature, Message: 22.5
⚠️

Common Pitfalls

  • Not calling loop_start() or loop_forever() causes no message processing.
  • Forgetting to set callbacks like on_connect or on_message means you won't handle events.
  • Using wrong broker address or port leads to connection failure.
  • Publishing before connection is established can drop messages.

Always ensure the client is connected before publishing or subscribing.

python
import paho.mqtt.client as mqtt

client = mqtt.Client()
# Missing on_connect callback
client.connect("wrong.broker.address", 1883)
client.loop_start()
client.publish("topic", "message")  # May fail silently

# Correct way

def on_connect(client, userdata, flags, rc):
    print(f"Connected with result code {rc}")
    client.subscribe("topic")

client = mqtt.Client()
client.on_connect = on_connect
client.connect("broker.hivemq.com", 1883, 60)
client.loop_start()
client.publish("topic", "message")
📊

Quick Reference

Here is a quick summary of key paho-mqtt methods:

MethodPurpose
Client()Create MQTT client instance
connect(host, port, keepalive)Connect to MQTT broker
subscribe(topic)Subscribe to a topic
publish(topic, payload)Send a message to a topic
loop_start()Start background network loop
loop_stop()Stop background network loop
on_connectCallback for connection event
on_messageCallback for incoming messages

Key Takeaways

Install and import paho-mqtt to use MQTT in Python.
Set up callbacks and start the network loop to handle messages.
Connect to a broker before publishing or subscribing.
Use client.publish() to send and client.subscribe() to receive messages.
Common errors include missing loop calls and wrong broker details.