Eclipse Paho MQTT client

Documentation: https://pypi.org/project/paho-mqtt/

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.

Installation

The latest stable version is available in the Python Package Index (PyPi) and can be installed using:

pip install paho-mqtt

Getting Started

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

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

Constructor

The Client() constructor takes the following arguments:

Client(client_id="", clean_session=True, userdata=None, protocol=MQTTv311, transport="tcp")

client_id

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.

clean_session

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 connect() or reconnect() will cause the messages to be resent. Use reinitialise() to reset a client to its original state.

userdata

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 user_data_set() function.

protocol

the version of the MQTT protocol to use for this client. Can be either MQTTv31 or MQTTv311

transport

set to "websockets" to send MQTT over WebSockets. Leave at the default of "tcp" to use raw TCP.

Constructor Example

import paho.mqtt.client as mqtt

mqttc = mqtt.Client()

The reinitialise() function resets the client to its starting state as if it had just been created. It takes the same arguments as the Client() constructor.

reinitialise(client_id="", clean_session=True, userdata=None)

Reinitialise Example:

mqttc.reinitialise()

Connect

The 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="")

host

the hostname or IP address of the remote broker

port

the network port of the server host to connect to. Defaults to 1883.

keepalive

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

bind_address

the IP address of a local network interface to bind this client to, assuming multiple interfaces exist

Callback (connect)

When the client receives a CONNACK message from the broker in response to the connect it generates an on_connect() callback.

Connect Example

mqttc.connect("mqtt.eclipse.org")

Subscribe

Subscribe the client to one or more topics.

subscribe(topic, qos=0)

This function may be called in three different ways:

Simple string and integer

subscribe("my/topic", 2)

topic

a string specifying the subscription topic to subscribe to.

qos

the desired quality of service level for the subscription. Defaults to 0.

String and integer tuple

subscribe(("my/topic", 1))

topic

a tuple of (topic, qos). Both topic and qos must be present in the tuple.

qos

not used.

List of string and integer tuples

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

topic

a list of tuple of format (topic, qos). Both topic and qos must be present in all of the tuples.

qos

not used.

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.

Raises a ValueError if 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.

Callback (subscribe)

When the broker has acknowledged the subscription, an on_subscribe() callback will be generated.

Callbacks

ON_CONNECT()

on_connect(client, userdata, flags, rc)

Called when the broker responds to our connection request.

client

the client instance for this callback

userdata

the private user data as set in Client() or userdataset()

flags

response flags sent by the broker

rc

the connection result

On Connect Example

def on_connect(client, userdata, flags, rc):
    print("Connection returned result: "+connack_string(rc))

mqttc.on_connect = on_connect

ON_MESSAGE()

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.

client

the client instance for this callback

userdata

the private user data as set in Client() or user_data_set()

message

an instance of MQTTMessage. This is a class with members topic, payload, qos, retain.

On Message Example

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

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.