MQTT With PYTHON — Part 2

Ashiq KS
4 min readDec 1, 2018

--

A series on the lightweight protocol MQTT with the Python programming language.

This post is the second part of MQTT With PYTHON series. In this part, we will see to how to subscribe and publish messages using Python.

Please refer to Part 1 for understanding MQTT and Part 3 for a more advanced tutorial.

All the codes are available on my GitHub page.

Paho-mqtt

Paho-mqtt-python is a Python implementation of MQTT and we will use python to subscribe and publish messages.

First of all, install paho-mqtt-python, using pip as follows:

pip3 install paho-mqtt==1.3.1

Here we specify the version as 1.3.1 while installing.

Subscribing

Here is a simple to implement how to subscribe using paho-mqtt.

#m.py
import
paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
print("Result from connect: {}".format(
mqtt.connack_string(rc)))
# Subscribe to the senors/alitmeter/1 topic filter

client.subscribe("sensors/altimeter/1")
def on_subscribe(client, userdata, mid, granted_qos):
print("I've subscribed")
def on_message(client, userdata, msg):
print("Message received. Topic: {}. Payload: {}".format(
msg.topic, str(msg.payload)))
if __name__ == "__main__": client = mqtt.Client(protocol=mqtt.MQTTv311)
client.on_connect = on_connect
client.on_subscribe = on_subscribe
client.on_message = on_message
client.connect(host="broker.hivemq.com", port=1883)
client.loop_forever()

First of all, we import the client paho.mqtt.client as client.

Then we define the callback functions which will be called upon specific events.

Our first callback is on_connect function, which will be called when a client’s - either a subscriber or publisher-request has been accepted by the broker/server.

def on_connect(client, userdata, flags, rc):    
print("Result from connect: {}".format(
mqtt.connack_string(rc)))
# Subscribe to the senors/alitmeter/1 topic filter
client.subscribe("sensors/altimeter/1")

So this function takes in 4 arguments - client, userdata, flags, rc - which are the data that come along with the connection acknowledgement from the server. client is the existing client we have. userdata is self-explanatory and rc is the return code sent by the server.

Now we need to subscribe to the topic “sensors/altimeter/1” by writing down

client.subscribe("sensors/altimeter/1")

Later we will use this callback function when the client is connected with the server.

Our next callback function is on_subscribe function which is fired when the client is subscribed to a specific topic.

def on_subscribe(client, userdata, mid, granted_qos):    
print("I've subscribed ")

It has client, userdata, message id - mid, and granted_qos as the arguments. granted_qos tells us the QoS (Quality of Service) provided and since we only have one topic, so we take the first value of the granted_qos array.

Next callback function is on_message function, which is fired upon client receiving messages.

def on_message(client, userdata, msg):    
print("Message received. Topic: {}. Payload: {}".format(
msg.topic, str(msg.payload)))

It has arguments as client, userdata, msg. msg is the message received by the subscriber from the server. msg.topic the topic of the message received and msg.payload is the actual message.

All the arguments need not be the names we have defined, but the format should be the same.

Now we will enter into the main function.

New client is created using paho.mqtt.client.Client class as follows:

client = mqtt.Client(protocol=mqtt.MQTTv311)

We have specified in the MQTT protocol version as 3.1.1while instantiating a client object.

Then we define what happens we the client is connected to the server, i.e our on_connect callback function.

client.on_connect = on_connect

That is whenever a client makes a connection with the server, the client.on_connect method will be executed. So we specify what should be our client.on_connect method by assigning on_connect method.

Then we will tell what should be executed if a client’s subscription has been approved by assigning our on_subscribe function to client.on_subscribe method.

client.on_subscribe = on_subscribe

Lastly, upon receiving a message client.on_message will be executed where we have assigned our on_message function.

client.on_message = on_message

Then we make the connection using client.connect and we specify the required positional parameter host=”broker.hivemq.com”. Here the host parameter is the broker/server we are connecting to. Here we have used HiveMQ’s free broker service for testing. We can use any other host including our localhost.

Then we run our loop forever by running loop_forever() function we want it to be run always in order to receive messages whenever published by publishers.

Before creating publisher using python we test our subscriber using command line tools.

Run our script mqtt_sub.py by typing in the command prompt as python3 mqtt_sub.py

Then we type in another command prompt as follows to publish to the topic sensors/alitmeter/1.

mosquitto_pub -V mqttv311 -t sensors/altimeter/1 -m "200 feet" -d

We can see that the subscriber has successfully received the message.

Let’s build a publisher using Python as follows:

#p.pyimport paho.mqtt.client as mqtttopic = "sensors/altimeter/1"if __name__ == "__main__":        
client = mqtt.Client(protocol=mqtt.MQTTv311)
client.connect(host="broker.hivemq.com", port=1883)
client.publish(topic=topic, payload="300 feet")

We have a variable named topic holding the topic name.

As we connected our subscriber to “broker.hive.mq”, our publisher should publish messages to this broker/server.

We publish a message to the broker/server using the following line of code.

client.publish(topic=topic, payload="300 feet")

We assign our topic variable to the topic parameter and payload parameter takes in our actual message.

Run our subscriber, mqtt_sub.py, after running it, run the publisher script, m.py. We can check if our subscriber has received the message from the publisher.

As we can see our subscriber has successfully received the message.

In the part3 of this series, we will implement a simple real-world application using MQTT utilizing classes of Python to publish and subscribe using Google cloud.

Please comment below your suggestions and thoughts.

--

--