Paho.mqtt.python
paho.mqtt.python
Install / Use
/learn @eclipse-paho/Paho.mqtt.pythonREADME
Eclipse Paho™ MQTT Python Client
The full documentation is available here <documentation_>_.
Warning breaking change - Release 2.0 contains a breaking change; see the release notes <https://github.com/eclipse/paho.mqtt.python/releases/tag/v2.0.0>_ and migration details <https://eclipse.dev/paho/files/paho.mqtt.python/html/migrations.html>_.
This document describes the source code for the Eclipse Paho <http://eclipse.org/paho/>_ MQTT Python client library, which implements versions 5.0, 3.1.1, and 3.1 of the MQTT protocol.
This code provides a client class which enables applications to connect to an MQTT <http://mqtt.org/>_ broker to publish messages, and to subscribe to topics and receive published messages. It also provides some helper functions to make publishing one off messages to an MQTT server very straightforward.
It supports Python 3.7+.
The MQTT protocol is a machine-to-machine (M2M)/"Internet of Things" connectivity protocol. Designed as an extremely lightweight publish/subscribe messaging transport, it is useful for connections with remote locations where a small code footprint is required and/or network bandwidth is at a premium.
Paho is an Eclipse Foundation <https://www.eclipse.org/org/foundation/>_ project.
Contents
- Installation_
Known limitations_Usage and API_Getting Started_Client_Network loop_Callbacks_Logger_External event loop support_Global helper functions_
Publish_Single_Multiple_
Subscribe_Simple_Using Callback_
Reporting bugs_More information_
Installation
The latest stable version is available in the Python Package Index (PyPi) and can be installed using
::
pip install paho-mqtt
Or with virtualenv:
::
virtualenv paho-mqtt
source paho-mqtt/bin/activate
pip install paho-mqtt
To obtain the full code, including examples and tests, you can clone the git repository:
::
git clone https://github.com/eclipse/paho.mqtt.python
Once you have the code, it can be installed from your repository as well:
::
cd paho.mqtt.python
pip install -e .
To perform all tests (including MQTT v5 tests), you also need to clone paho.mqtt.testing in paho.mqtt.python folder::
git clone https://github.com/eclipse/paho.mqtt.testing.git
cd paho.mqtt.testing
git checkout a4dc694010217b291ee78ee13a6d1db812f9babd
Known limitations
The following are the known unimplemented MQTT features.
When clean_session is False, the session is only stored in memory and not persisted. This means that
when the client is restarted (not just reconnected, the object is recreated usually because the
program was restarted) the session is lost. This results in a possible message loss.
The following part of the client session is lost:
-
QoS 2 messages which have been received from the server, but have not been completely acknowledged.
Since the client will blindly acknowledge any PUBCOMP (last message of a QoS 2 transaction), it won't hang but will lose this QoS 2 message.
-
QoS 1 and QoS 2 messages which have been sent to the server, but have not been completely acknowledged.
This means that messages passed to
publish()may be lost. This could be mitigated by taking care that all messages passed topublish()have a correspondingon_publish()call or usewait_for_publish.It also means that the broker may have the QoS2 message in the session. Since the client starts with an empty session it don't know it and will reuse the mid. This is not yet fixed.
Also, when clean_session is True, this library will republish QoS > 0 message across network
reconnection. This means that QoS > 0 message won't be lost. But the standard says that
we should discard any message for which the publish packet was sent. Our choice means that
we are not compliant with the standard and it's possible for QoS 2 to be received twice.
You should set clean_session = False if you need the QoS 2 guarantee of only one delivery.
Usage and API
Detailed API documentation is available online <documentation_>_ or could be built from docs/ and samples are available in the examples_ directory.
The package provides two modules, a full Client and few helpers for simple publishing or subscribing.
Getting Started
Here is a very simple example that subscribes to the broker $SYS topic tree and prints out the resulting messages:
.. code:: python
import paho.mqtt.client as mqtt
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, reason_code, properties):
print(f"Connected with result code {reason_code}")
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe("$SYS/#")
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
mqttc.on_connect = on_connect
mqttc.on_message = on_message
mqttc.connect("mqtt.eclipseprojects.io", 1883, 60)
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
mqttc.loop_forever()
Client
You can use the client class as an instance, within a class or by subclassing. The general usage flow is as follows:
- Create a client instance
- Connect to a broker using one of the
connect*()functions - Call one of the
loop*()functions to maintain network traffic flow with the broker - Use
subscribe()to subscribe to a topic and receive messages - Use
publish()to publish messages to the broker - Use
disconnect()to disconnect from the broker
Callbacks will be called to allow the application to process events as necessary. These callbacks are described below.
Network loop
These functions are the driving force behind the client. If they are not
called, incoming network data will not be processed and outgoing network data
will not be sent. There are four options for managing the
network loop. Three are described here, the fourth in "External event loop
support" below. Do not mix the different loop functions.
loop_start() / loop_stop()
''''''''''''''''''''''''''
.. code:: python
mqttc.loop_start()
while True:
temperature = sensor.blocking_read()
mqttc.publish("paho/temperature", temperature)
mqttc.loop_stop()
These functions implement a threaded interface to the network loop. Calling
`loop_start()` once, before or after ``connect*()``, runs a thread in the
background to call `loop()` automatically. This frees up the main thread for
other work that may be blocking. This call also handles reconnecting to the
broker. Call `loop_stop()` to stop the background thread.
The loop is also stopped if you call `disconnect()`.
loop_forever()
''''''''''''''
.. code:: python
mqttc.loop_forever(retry_first_connection=False)
This is a blocking form of the network loop and will not return until the
client calls `disconnect()`. It automatically handles reconnecting.
Except for the first connection attempt when using `connect_async`, use
``retry_first_connection=True`` to make it retry the first connection.
*Warning*: This might lead to situations where the client keeps connecting to an
non existing host without failing.
loop()
''''''
.. code:: python
run = True
while run:
rc = mqttc.loop(timeout=1.0)
if rc != 0:
# need to handle error, possible reconnecting or stopping the application
Call regularly to process network events. This call waits in ``select()`` until
the network socket is available for reading or writing, if appropriate, then
handles the incoming/outgoing data. This function blocks for up to ``timeout``
seconds. ``timeout`` must not exceed the ``keepalive`` value for the client or
your client will be regularly disconnected by the broker.
Using this kind of loop, require you to handle reconnection strategie.
Callbacks
`````````
The interface to interact with paho-mqtt include various callback that are called by
the library when some events occur.
The callbacks are functions defined in your code, to implement the require action on those events. This could
be simply printing received message or much more complex behaviour.
Callbacks API is versioned, and the selected version is the `CallbackAPIVersion` you provided to `Client`
constructor. Currently two version are supported:
* ``CallbackAPIVersion.VERSION1``: it's the historical version used in paho-mqtt before version 2.0.
It's the API used before the introduction of `CallbackAPIVersion`.
This version is deprecated and will be removed in paho-mqtt version 3.0.
* ``CallbackAPIVersion.VERSION2``: This version is more consistent between protocol MQTT 3.x and MQTT 5.x. It's also
much more usable with MQTT 5.x since reason code and properties are always provided when available.
It's recommended for all user to upgrade to this version. It's highly recommended for MQTT 5.x user.
The following callbacks exists:
* `on_connect()`: called when the CONNACK from the broker is received. The call could be for a refused connection,
check the reason_code to see if the connection is successful or rejected.
* `on_connect_fail()`: called by `loop_forever()` and `loop_start()` when the TCP connection failed to establish.
This callback is not called when using `connect()` or `reconnect()` directly. It's only called following
an automatic (re)connection made by `loop
