This code provides a client class which enable applications to connect to an MQTT 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.
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.
The latest stable version is available in the Python Package Index (PyPi) and can be installed using:
pip install paho-mqtt
Here is a very simple example that subscribes to the broker
$SYS topic tree and prints out the resulting messages:
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, rc): print("Connected with result code "+str(rc)) # 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)) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("mqtt.eclipse.org", 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. client.loop_forever()
You can use the client class as an instance, within a class or by subclassing. The general usage flow is as follows:
loop*()functions to maintain network traffic flow with the broker
subscribe()to subscribe to a topic and receive messages
publish()to publish messages to the broker
disconnect()to disconnect from the broker
Client() constructor takes the following arguments:
Client(client_id="", clean_session=True, userdata=None, protocol=MQTTv311, transport="tcp")
the unique client id string used when connecting to the broker. If clientid is zero length or None, then one will be randomly generated. In this case the cleansession parameter must be True.
a boolean that determines the client type. If True, the broker will remove all information about this client when it disconnects. If False, the client is a durable client and subscription information and queued messages will be retained when the client disconnects.
Note: that a client will never discard its own outgoing messages on disconnect. Calling
reconnect() will cause the messages to be resent. Use
reinitialise() to reset a client to its original state.
user defined data of any type that is passed as the userdata parameter to callbacks. It may be updated at a later point with the
the version of the MQTT protocol to use for this client. Can be either MQTTv31 or MQTTv311
set to "websockets" to send MQTT over WebSockets. Leave at the default of "tcp" to use raw TCP.
import paho.mqtt.client as mqtt mqttc = mqtt.Client()
reinitialise() function resets the client to its starting state as if it had just been created. It takes the same arguments as the
reinitialise(client_id="", clean_session=True, userdata=None)
connect() function connects the client to a broker. This is a blocking function. It takes the following arguments:
connect(host, port=1883, keepalive=60, bind_address="")
the hostname or IP address of the remote broker
the network port of the server host to connect to. Defaults to 1883.
maximum period in seconds allowed between communications with the broker. If no other messages are being exchanged, this controls the rate at which the client will send ping messages to the broker
the IP address of a local network interface to bind this client to, assuming multiple interfaces exist
When the client receives a CONNACK message from the broker in response to the connect it generates an
Subscribe the client to one or more topics.
This function may be called in three different ways:
a string specifying the subscription topic to subscribe to.
the desired quality of service level for the subscription. Defaults to 0.
a tuple of (topic, qos). Both topic and qos must be present in the tuple.
subscribe([("my/topic", 0), ("another/topic", 2)])
This allows multiple topic subscriptions in a single SUBSCRIPTION command, which is more efficient than using multiple calls to
a list of tuple of format (topic, qos). Both topic and qos must be present in all of the tuples.
The function returns a tuple
(result, mid), where result is
MQTT_ERR_SUCCESS to indicate success or
(MQTT_ERR_NO_CONN, None) if the client is not currently connected.
mid is the message ID for the subscribe request. The
mid value can be used to track the subscribe request by checking against the mid argument in the
on_subscribe() callback if it is defined.
qos is not 0, 1 or 2, or if topic is
None or has zero string length, or if topic is not a string, tuple or list.
When the broker has acknowledged the subscription, an
on_subscribe() callback will be generated.
on_connect(client, userdata, flags, rc)
Called when the broker responds to our connection request.
the client instance for this callback
the private user data as set in Client() or userdataset()
response flags sent by the broker
the connection result
def on_connect(client, userdata, flags, rc): print("Connection returned result: "+connack_string(rc)) mqttc.on_connect = on_connect
on_message(client, userdata, message)
Called when a message has been received on a topic that the client subscribes to and the message does not match an existing topic filter callback. Use
message_callback_add() to define a callback that will be called for specific topic filters.
on_message will serve as fallback when none matched.
the client instance for this callback
the private user data as set in
an instance of MQTTMessage. This is a class with members
def on_message(client, userdata, message): print("Received message '" + str(message.payload) + "' on topic '" + message.topic + "' with QoS " + str(message.qos)) mqttc.on_message = on_message
on_subscribe(client, userdata, mid, granted_qos)
Called when the broker responds to a subscribe request. The
mid variable matches the mid variable returned from the corresponding
subscribe() call. The
granted_qos variable is a list of integers that give the QoS level the broker has granted for each of the different subscription requests.