In this tutorial we will look at how you publish messages using the Paho Python MQTT client.
We will use an example python script to publish messages, process the publish acknowledgements and examine QOS (quality of service) settings.
To publish a messages you use the publish method of the Paho MQTT Class object.
The publish method accepts 4 parameters. The parameters are shown below with their default values.
The only parameters you must supply are the topic, and the payload.
The payload is the message you want to publish.
Publishing a Message
To publish a message you need to:
- Create a client object.
- Create a client connection.
- publish the message
- Examine the return code of the publish request
- Examine the publish acknowledgement using the on_publish callback
Example code: import paho.mqtt.client as paho broker="192.168.1.184" port=1883 def on_publish(client,userdata,result): #create function for callback print("data published \n") pass client1= paho.Client("control1") #create client object client1.on_publish = on_publish #assign function to callback client1.connect(broker,port) #establish connection ret= client1.publish("house/bulb1","on") #publish
Note 1: you don’t appear to need a client loop to process the on_publish callback.
Note2: When you publish a message the publish method returns a tuple (result, mid).
The result is the error code. A result of 0 indicates success.
The mid value is an integer that corresponds to the published message number as assigned by the client.
The mid value can be used with the on_publish callback to check that the messages was published even when publishing with a qos of 0.
If you publish with a qos of 0 the published message has a mid of 0 but internally it has a mid just like qos 1,2 messages.
So on the broker you see a mid of 0 but on the client you see an incrementing mid.
When the message has been published to the Broker an acknowledgement is sent that results in the on_publish callback being called.
The on_publish callback function must receive three parameters
on_publish(client, userdata, mid)
The client is the client object, and is useful when you have multiple clients that are publishing data.
The userdata is user defined data which isn’t normally used.
The mid value is the message id and can be used with the mid value returned from the publish method to check that a particular message has been published.
In the screen shot below I have printed the mid value from the publish message and on publish callback.
You can see that the numbers match which indicated that both messages were published OK
The on_publish callback is triggered even for a qos of 0 which doesn’t get an acknowledgement from the broker but the client generates a local one.
Message Flow and Quality of Service Example
If you want to try and ensure that the subscriber gets a message even though they might not be online then you need to publish with a quality of service of 1 or 2.
The schematic below shows the message flow between client and broker for messages with QOS of 0, 1 and 2.
The screen shot below shows the results of running a test Python script that publishes 3 messages with QOS of 0,1 and 2 respectively
Notice with QOS set to 2 there are more messages generated.
In addition messages sent with QOS of 0 are not acknowledged by the broker but instead by the sending client.
There is no guarantee that the broker received them. See:
Publishing on Restricted Topics
You may not be allowed to publish messages on certain topics.
This is controlled by the broker See Configuring Topic Restriction on Mosquitto.
However what happens if you do publish on a restricted topic?
Well as far as the client is concerned the publish succeeds, and if I run the previous script but restrict the topic then my client output would be identical to that shown above.
However this is what I would see on the Sever (broker)
Notice the denied publish message on the server console. Also notice the normal publish acknowledgement sequence.
However when using MQTTv5 you do get a error message in the reason code.
Retain Message Flag
When publishing a message you can also set the retain message flag.
This flag tells the broker to store the last message that you sent.
This is very useful if you only publish messages at infrequent intervals- See Retained messages-Example’
Disconnecting After Publish
If you only publish messages at infrequent intervals then you will probably want to disconnect the client between publishing.
You can use the disconnect method along with the on_disconnect callback for this.
This type of disconnect does not result in a last will and testament message.
def on_disconnect(client, userdata, rc): print("client disconnected ok") client1.on_disconnect = on_disconnect client1.disconnect()
Publishing To Multiple Topic
You cannot use a wild card when publishing a message and so you cannot publish to multiple topics with a single publish.
If you need to publish to 10 different topics then you will need 10 separate publish messages.
Publishing and The Loop
Although you can publish messages without starting a loop (See the Loop) you will need to start a loop or call the loop to send automatic ping messages.
Therefore you may find that your client gets disconnected , and without the loop you don’t see the disconnect message.
Therefore if you do this you will need to consider setting the keepalive to a higher value (60 seconds by default).
Note: If you publish messages inside the keep alive value then the connection isn’t closed by the server/broker.
Publishing Using SSL
You will need to add a broker/server CA key to the client, See Configuring Mosquitto for SSL for details about keys.
You then use the client.tls_set function before you connect. E.G.
Depending on how you’ve configured the broker you may need to use the TLS version parameter (code below set client to use TLSv1.2.
Because SSL normally uses port 8883 you will also need to change the port when connecting.
Publishing Using WebSockets
You can also publish messages over webSockets. You need to tell the client to use Websockets when creating the client object as show below:
Use the command
instead of simply
The publish uses the same procedure and process as standard MQTT. See My MQTT WebSockets Notes
Here is a video that I created that covers the main points from above. Grateful of any feedback
Common Questions and Answers
Q- Do I know if and when my published messages have been received by a client?
A- No. You only know that the broker has received them, and then only if the QOS is set to 1 or above.
Q- What happens if I publish on the wrong topic?
A- Generally unless the topic has an invalid topic address you wont know.
Q- What happens if I publish on a restricted topic?
A- You wont know as it will appear to succeed.
Q- How do I know that no one else is using that topic?
A- You don’t. You could subscribe to the topic beforehand and look for activity.
Q- Can I publish on any topic that I want to?
A- Yes unless the broker administrator has configured topic restrictions.
- Introduction to the Paho Python MQTT Client
- Introduction to the Client Class
- Connecting to a Broker
- Publishing Using The Paho Python MQTT Client
- –Subscribing using The Paho Python Client
- Receiving Messages with the Paho MQTT Python Client
- Understanding The Loop
- Understanding Callbacks
- Handling Multiple Client Connections