{"id":1852,"library":"paho-mqtt","title":"Eclipse Paho MQTT Python Client","description":"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.","status":"active","version":"2.1.0","language":"en","source_language":"en","source_url":"https://github.com/eclipse/paho.mqtt.python","tags":["mqtt","iot","messaging","publish-subscribe","client"],"install":[{"cmd":"pip install paho-mqtt","lang":"bash","label":"Install stable version"}],"dependencies":[{"reason":"Requires Python 3.7 or newer. Support for Python 2.7, 3.5, and 3.6 was dropped in version 2.0.0.","package":"python","optional":false}],"imports":[{"note":"Aliasing `paho.mqtt.client` to `mqtt_client` is a common convention for brevity and clarity.","wrong":"import paho.mqtt.client","symbol":"Client","correct":"from paho.mqtt import client as mqtt_client"},{"symbol":"CallbackAPIVersion","correct":"from paho.mqtt import client as mqtt_client"},{"symbol":"publish.single","correct":"from paho.mqtt import publish"},{"symbol":"subscribe.simple","correct":"from paho.mqtt import subscribe"}],"quickstart":{"code":"import os\nimport time\nfrom paho.mqtt import client as mqtt_client\n\nbroker = os.environ.get('MQTT_BROKER_HOST', 'broker.hivemq.com')\nport = int(os.environ.get('MQTT_BROKER_PORT', 1883))\ntopic = os.environ.get('MQTT_TOPIC', \"python/mqtt/test\")\nclient_id = f'python-mqtt-subscriber-{time.time()}'\n\ndef on_connect(client, userdata, flags, rc, properties=None):\n    if rc == 0:\n        print(\"Connected to MQTT Broker!\")\n        client.subscribe(topic)\n    else:\n        print(f\"Failed to connect, return code {rc}\\n\")\n\ndef on_message(client, userdata, msg):\n    print(f\"Received `{msg.payload.decode()}` from `{msg.topic}`\")\n\ndef run():\n    # Use CallbackAPIVersion.VERSION2 for MQTTv5 compatibility and future-proofing\n    client = mqtt_client.Client(mqtt_client.CallbackAPIVersion.VERSION2, client_id)\n    # Optional: Set username/password if your broker requires it\n    # client.username_pw_set(os.environ.get('MQTT_USERNAME', ''), os.environ.get('MQTT_PASSWORD', ''))\n    client.on_connect = on_connect\n    client.on_message = on_message\n    client.connect(broker, port)\n    client.loop_start() # Start background thread for network traffic\n\n    # Publish a message after connection is established\n    msg_count = 0\n    while True:\n        time.sleep(1)\n        msg = f\"messages: {msg_count}\"\n        result = client.publish(topic, msg)\n        status = result[0]\n        if status == 0:\n            print(f\"Sent `{msg}` to topic `{topic}`\")\n        else:\n            print(f\"Failed to send message to topic {topic}\")\n        msg_count += 1\n        if msg_count >= 5: # Stop after 5 messages for quickstart example\n            break\n    \n    client.loop_stop() # Stop the background thread\n    client.disconnect()\n    print(\"Disconnected from MQTT Broker.\")\n\nif __name__ == '__main__':\n    run()","lang":"python","description":"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."},"warnings":[{"fix":"Initialize the client with `mqtt_client.Client(mqtt_client.CallbackAPIVersion.VERSION2, client_id)`. If you need to retain older callback signatures, explicitly use `mqtt_client.Client(mqtt_client.CallbackAPIVersion.VERSION1, client_id)` but plan for migration to `VERSION2` as `VERSION1` is deprecated and will be removed in v3.0.","message":"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.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Upgrade your Python environment to version 3.7 or newer.","message":"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.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Update calls to `connect_srv()` to include the `bind_port` argument.","message":"The `connect_srv()` method signature changed in version 2.0.0 to include an additional `bind_port` parameter.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Always use `==` for comparison with return codes (e.g., `if rc == 0:`).","message":"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.","severity":"gotcha","affected_versions":">=2.0.0"},{"fix":"Always include `client.subscribe()` calls within your `on_connect` callback function. This ensures that subscriptions are automatically renewed upon successful reconnection to the broker.","message":"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.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Migrate your callback functions to use the `CallbackAPIVersion.VERSION2` signature and explicitly pass `mqtt_client.CallbackAPIVersion.VERSION2` to the `Client` constructor to prepare for future library updates.","message":"The `CallbackAPIVersion.VERSION1` (the historical API used before v2.0.0) is deprecated and is scheduled for removal in `paho-mqtt` version 3.0.","severity":"deprecated","affected_versions":">=2.0.0"}],"env_vars":null,"last_verified":"2026-04-09T00:00:00.000Z","next_check":"2026-07-08T00:00:00.000Z"}