The main component of the Paho Python MQTT client library is the client class.
The class provides all the necessary functions to connect to an MQTT broker, publish messages, subscribe to topics and receive messages.
To use you will need to create a new client object from the client class.
The client constructor takes 4 optional parameters. The default values are shown below:
To create a new client object you first need to import the Paho MQTT client, and then create the object as shown below:
client1 = mqtt.Client()
The Client name
Although the client name is optional, it is only optional if clean sessions. are True (default).
However even if you don’t provide a client name one is created for you by the client software.
The screen shot below is taken from the MQTT broker console and shows the result of the client connecting first without specifying a client id and then secondly supplying a client id.
In both case the broker sees a client id as the client will auto generate a random one.
The client name is used by the MQTT broker to identify the client.
This is necessary when using persistent connections as the broker needs to store messages for the client when the client isn’t connected.
Duplicate Client ids
If a client connects with a client id that is in use, and also currently connected then the existing connection is closed.
Because the MQTT client may attempt to reconnect following a disconnect this can result in a loop of disconnect and connect.
The screen shots below show what happens when I try and connect a client (client2) to the broker using the same id as an existing client (client1).
Here is the view from the broker:
In the above you can clearly see that when client 2 connects client 1 gets disconnected. Client 1 then attempts a reconnect which in turn disconnects client 2.
Therefore be careful when assigning client IDs.
Clean Session Flag
This flag tells the broker to either
- Remember subscriptions and Store messages that the client has missed because it was offline value =False or
- Not to Remember subscriptions and not to Store messages that the client has missed because it was offline – value =True
By default it is set to True
See persistent connections by example to see how persistent connections and clean sessions work.
The user data and protocol parameters are discussed here and I wont discuss them here as the defaults are normally used.
Auxiliary Functions or Settings
There are several Client settings that may need to be changed before a connection is created.
These settings are changed using auxiliary functions. Here is a list of the functions that are available:
- max_inflight_messages_set() –Affects Message throughput
- max_queued_messages_set() –Affects Message throughput
- message_retry_set(retry) –Affects Message throughput
- tls_set() – Used for SSL security
- tls_insecure_set(value) –Used for SSL security
- username_pw_set() – Used for username and passwords
- will_set() –Used for setting last will and testament
The most common used ones are username_pw_set() ,tls_set(),and will_set().
See the Documentation for details
websocket support is also built into the Paho MQTT client.
To Use Websockets with Python. Create the client object using the transport=websockets argument.
Simple Client Object Modifications I Make
Important- See note below
I usually add additional flags to the Client object and use them for detecting successful connections and subscribes.
This I do before I create the client object. So often in my test scripts you will see an initialise client object function that looks like this.
def Initialise_client_object(): #flags set mqtt.Client.bad_connection_flag=False mqtt.Client.connected_flag=False mqtt.Client.disconnected_flag=False mqtt.Client.suback_flag=False
Note: I don’t use the above any more as you cannot add lists using this method as they can then be changed by any object instance.
Instead I either create the flags as part of the client instance or I sub class the client object.
So I use either
import paho.mqtt.client as mqtt def Initialise_clients(cname): #callback assignment client= mqtt.Client(cname,False) #don't use clean session if mqttclient_log: #enable mqqt client logging client.on_log=on_log client.on_connect= on_connect #attach function to callback client.on_message=on_message #attach function to callback client.on_subscribe=on_subscribe #flags set client.topic_ack= client.run_flag=False client.running_loop=False client.subscribe_flag=False client.bad_connection_flag=False client.connected_flag=False client.disconnect_flag=False return client
or creating a sub class
import paho.mqtt.client as mqtt class MQTTClient(mqtt.Client): def __init__(self,cname,**kwargs): super(MQTTClient, self).__init__(cname,**kwargs) self.last_pub_time=time.time() self.topic_ack= self.run_flag=True self.subscribe_flag=False self.bad_connection_flag=False self.connected_flag=True self.disconnect_flag=False self.disconnect_time=0.0 self.pub_msg_count=0 self.devices=
Common Questions and Answers
Q- Can two clients have the same client ID?
A- No. If a client connects with a client id that is also currently connected then the existing connection is closed.
Once you have a client object you can connect to the broker —> Client Connections
Using The Paho Python MQTT Client Tutorials
- Introduction to the Paho Python MQTT Client
- Subscribing to Topics Using the Paho Python MQTT Client
- Publishing Messages Using The Paho Python MQTT Client
- Understanding The loop and Loop Functions
- Understanding Callback Functions in the Paho MQTT Client
Related tutorials and Resources