MQTT using Python

Posted by Afsal on 20-May-2022

MQTT (message queueing telemetry transport) is a lightweight messaging protocol. It works on publish/subscribe model. It requires less bandwidth hence it is commonly used for IoT devices.

How does it work?

MQTT broker is the heart of this architecture. It receives the message and passes the message to the proper client. All clients are connected to brokers. A client can publish, subscribe or do both. Some common in MQTT is

  • Publish - Process of sending messages to brokers for the client. The client can be a sensor, mobile phone, computer, etc
  • Subscribe - Process of receiving messages from the broker. The client can be a sensor, mobile phone, computer, etc
  • Message - Data or command send to the broker
  • Topic - Topics are strings used by brokers to filter down the clients. The topic contains one or more levels. Each level is separated by a slash(/). Eg: home/groundfloor/kitchen/bulb

MQTT in Python example

We are using paho-mqtt package. We can install it using the command

pip install paho-mqtt

I am using mosquito broker installed on my local machine for this demo. Also, there are some free services available please visit here for more details

Let's dive into code

Create an MQTT client and connect

import paho.mqtt.client as mqtt

mqttc = mqtt.Client()

mqttc.connect("localhost", 1883, 60)

Parameters are

Hostname or IP of the broker

Port of the broker

Keepalive seconds

When the connect function called the on_connect is triggered

Assign callback function

mqttc.on_message = on_message # trigger when message is recieved

mqttc.on_connect = on_connect # trigger when connected to broker

mqttc.on_publish = on_publish # trigger when message is published

mqttc.on_subscribe = on_subscribe # trigger when a client subscribed

Call back functions

def on_connect(client, user_data, flag, rc):
    print("\nOn connect callback")
    print("\nrc: " + str(rc))
    print("\nEnd on connect")

def on_message(client, user_data, message):
    print(f"{message.payload} : is published on {message.topic}\n")

def on_publish(client, user_data, message_id):
    print(f"publishing message with id: {message_id}")

def on_subscribe(client, obj, mid, granted_qos):
    print(f"Subscribed: {mid} {granted_qos}")

For this example we are only printing some details to learn more about each call back please click here

Subscribe to a topic

mqttc.subscribe("maintopic/subtopic")

Here we subscribe to a topic called “maintopic/subtopic”. When this is called the on_subscibe function is triggered

Publish a message on a topic

mqttc.publish("maintopic/subtopic", counter)

Parameters  are

Topic name

Message to pass

Here we publish the value of the counter to a topic called “maintopic/subtopic”

Code for publishing and subscribe to a counter varable

import paho.mqtt.client as mqtt
import time

def on_connect(client, user_data, flag, rc):
    print("\nOn connect callback")
    print("\nrc: " + str(rc))
    print("\nEnd on connect")

def on_message(client, user_data, message):
    print(f"{message.payload} : is published on {message.topic}\n")

def on_publish(client, user_data, message_id):
    print(f"publishing message with id: {message_id}")

def on_subscribe(client, obj, mid, granted_qos):
    print(f"Subscribed: {mid} {granted_qos}")

mqttc = mqtt.Client()
# Assign event callbacks
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_publish = on_publish
mqttc.on_subscribe = on_subscribe

# Connect
mqttc.connect("localhost", 1883, 60)
mqttc.subscribe("maintopic/subtopic", 0)

# Continue the network loop, exit when an error occurs
rc = 0
counter = 0
while rc == 0:
   rc = mqttc.loop()
   mqttc.publish("maintopic/subtopic", counter)
   counter += 1
   time.sleep(1)

print("rc: " + str(rc))

Output

On connect callback
rc: 0

End on connect
publishing message with id: 2
Subscribed: 1 (0,)
publishing message with id: 3
b'0' : is published on maintopic/subtopic
publishing message with id: 4
b'1' : is published on maintopic/subtopic
publishing message with id: 5
b'2' : is published on maintopic/subtopic
publishing message with id: 6
b'3' : is published on maintopic/subtopic
publishing message with id: 7
b'4' : is published on maintopic/subtopic


I hope you have learned from this post please share your valuable feedback to afsal@parseltongue.co.in