Eclipse Paho MQTT Python Client
The Eclipse Paho MQTT Python Client library provides classes for applications to connect to an MQTT broker, publish messages, and subscribe to topics to receive messages. It supports MQTT versions 5.0, 3.1.1, and 3.1, and is designed for lightweight publish/subscribe messaging, suitable for IoT and M2M communication where bandwidth or code footprint is a concern. The current stable version is 2.1.0, with regular updates and an active development cadence as part of the Eclipse Foundation projects.
Warnings
- breaking Version 2.0.0 introduced versioned user callbacks. If you omit the `callback_api_version` argument when creating `mqtt_client.Client`, it might default to `VERSION1` for positional arguments, leading to `Unsupported callback API version` errors, especially when migrating. In v2.1.0, it defaults to `VERSION1` if positional arguments are used, but `VERSION2` is recommended.
- breaking Version 2.0.0 dropped official support for Python 2.7, 3.5, and 3.6. The minimum supported Python version is now 3.7.
- breaking The `connect_srv()` method signature changed in version 2.0.0 to include an additional `bind_port` parameter.
- gotcha When checking return codes (e.g., from `on_connect` or `publish`), version 2.0.0 introduced `IntEnum` objects (like `ReasonCode` and `MQTT_ERR_SUCCESS`) instead of raw integers. Direct comparison using `is` (e.g., `rc is 0`) will likely fail, while `==` (e.g., `rc == 0`) will work correctly.
- gotcha For non-durable MQTT clients, subscriptions are lost if the connection to the broker drops and is re-established. Placing subscription logic outside the `on_connect` callback can lead to missed messages after a reconnection.
- deprecated The `CallbackAPIVersion.VERSION1` (the historical API used before v2.0.0) is deprecated and is scheduled for removal in `paho-mqtt` version 3.0.
Install
-
pip install paho-mqtt
Imports
- Client
from paho.mqtt import client as mqtt_client
- CallbackAPIVersion
from paho.mqtt import client as mqtt_client
- publish.single
from paho.mqtt import publish
- subscribe.simple
from paho.mqtt import subscribe
Quickstart
import os
import time
from paho.mqtt import client as mqtt_client
broker = os.environ.get('MQTT_BROKER_HOST', 'broker.hivemq.com')
port = int(os.environ.get('MQTT_BROKER_PORT', 1883))
topic = os.environ.get('MQTT_TOPIC', "python/mqtt/test")
client_id = f'python-mqtt-subscriber-{time.time()}'
def on_connect(client, userdata, flags, rc, properties=None):
if rc == 0:
print("Connected to MQTT Broker!")
client.subscribe(topic)
else:
print(f"Failed to connect, return code {rc}\n")
def on_message(client, userdata, msg):
print(f"Received `{msg.payload.decode()}` from `{msg.topic}`")
def run():
# Use CallbackAPIVersion.VERSION2 for MQTTv5 compatibility and future-proofing
client = mqtt_client.Client(mqtt_client.CallbackAPIVersion.VERSION2, client_id)
# Optional: Set username/password if your broker requires it
# client.username_pw_set(os.environ.get('MQTT_USERNAME', ''), os.environ.get('MQTT_PASSWORD', ''))
client.on_connect = on_connect
client.on_message = on_message
client.connect(broker, port)
client.loop_start() # Start background thread for network traffic
# Publish a message after connection is established
msg_count = 0
while True:
time.sleep(1)
msg = f"messages: {msg_count}"
result = client.publish(topic, msg)
status = result[0]
if status == 0:
print(f"Sent `{msg}` to topic `{topic}`")
else:
print(f"Failed to send message to topic {topic}")
msg_count += 1
if msg_count >= 5: # Stop after 5 messages for quickstart example
break
client.loop_stop() # Stop the background thread
client.disconnect()
print("Disconnected from MQTT Broker.")
if __name__ == '__main__':
run()