Connect to Broker Using MQTTv5 Python Client

In this tutorial we will look at how you connect to a broker using MQTTv5.

The tutorial assumes you are already familiar with the basics after using MQTTv3.1.1.

This is covered in this tutorial:

The main changes to take into account when moving your code to MQTT v5 are the properties object and increased reason codes.

With MQTTv5 The connection packet can indicate to the broker any client side restrictions and the broker can indicate back to the connecting client any broker restrictions using the connect acknowledgement packet.

This is all done using the properties object.

The connection packet also includes the protocol version.-v3 or 5


With the Python client this is set when creating the client.

client = mqtt.Client("subclient",protocol=mqttv5)

Properties Object

This is present in the connect, publish, PubAck messages.


The connect function now looks like this:

connect(host, port=1883, keepalive=60, bind_address="", bind_port=0, clean_start=MQTT_CLEAN_START_FIRST_ONLY, properties=None)

The properties object can is set to None by default as shown above.

To use the properties object you need to create a connection properties object as shown below:


Once we have the properties object we set the attributes as shown in the example code below:

from import Properties
from paho.mqtt.packettypes import PacketTypes 

Note the extra import statements.

As with version 3.1.1 we need the on_connect callback to check the success of the connect.

Again we need to be aware of the properties object in the callback as shown below:

Old signature for MQTT v3.1 and v3.1.1 is:
on_connect(client, userdata, flags, rc)

signature for MQTT v5.0 client:
on_connect(client, userdata, flags, reasonCode, properties=None)

Because the broker can impose connection restrictions it is important to process the properties object to check that none of the restrictions affect the client.

For example if the broker doesn’t support retain messages and the client needs to use them then connection should be terminated.

The screen shot below shows the connection process and the properties return by the broker.


Demo Code- in the zip file.

Related Tutorials and Resources:

Please rate? And use Comments to let me know more

Leave a Reply

Your email address will not be published. Required fields are marked *