Eclipse Paho MQTT Python Client

2.1.0 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

This quickstart demonstrates how to connect to an MQTT broker, subscribe to a topic, and publish messages using the `paho-mqtt` client. It configures `on_connect` and `on_message` callbacks and uses `loop_start()` to handle network traffic in a background thread. It explicitly uses `CallbackAPIVersion.VERSION2` for modern MQTTv5 features and future compatibility. Environment variables are used for broker host/port for easy configuration.

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()

view raw JSON →