The Paho MQTT python client version 2 introduced some changes that break easier scripts.
All of the scripts currently available on this site used the 1.5 to 1.6 client version and so if you upgrade to the new version you will need to make changes to these scripts.
The changes revolve around the callback functions which have been changed to take into account the properties feature of MQTTv5.
Previously when using version 1.x with MQTTv5 you would need to add the properties object to some of the callbacks as scripts written for MQTTv3.1 would fail because they didn’t have the properties object.
As an illustration the callback function for on_connect
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)
Notice the extra properties field.
However existing code written for v3.1.1 used the following callback signature:
connect(client, userdata, flags, rc)
This will still work with MQTTv3.1.1 but you will get an error with MQTTv5
To make the callback work with v3.1.1 and v5 connections use:
on_connect(client, userdata, flags, rc, properties=None)
Version 2 Changes
In version all callbacks that require the properties field have one.
This means that it works with both MQTTv3.1 and MQTTv5.
In addition a flag has been added so that old code written for MQTTv3.1 and version 1.x client will still work with the version2 client.
The flag is shown below:
mqtt.CallbackAPIVersion.VERSION1
and
mqtt.CallbackAPIVersion.VERSION2
This is set at client creation so instead of:
client = mqtt.Client(client_name)
you need to use:
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION1,client_name)
if you are still using old callbacks or
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2,client_name)
for new callbacks.
In addition the reason code (rc) returned in callbacks was previously an integer, but is now an instance of ReasonCode.
Finally new properties have been added to the client class which might be an issue if you have sub classed or added additional properties.
I use a connected_flag in many of my scripts and there is no conflict with the new ones.
You can find all the details and example code on the migration page here
I did an article on python client changes for MQTTv5 a while ago and it is here.
Related tutorial and Resources:
- Paho Python MQTT Client – Understanding Callbacks
- Paho Python MQTT Client-Understanding The Loop
- Paho Python MQTT Client Objects