MQTT Protocol in Python

Loading

MQTT (Message Queuing Telemetry Transport) is a lightweight messaging protocol widely used in IoT, home automation, and real-time applications. It operates on a publish-subscribe model, making it highly efficient for low-bandwidth and high-latency networks.

Why MQTT?
Lightweight & Efficient
Works on low-power devices
Reliable with QoS levels
Supports bi-directional communication


1. Understanding MQTT

MQTT works with three main components:

1️⃣ Broker – Central server managing message distribution. (e.g., Mosquitto, HiveMQ)
2️⃣ Publisher – Sends messages to a topic.
3️⃣ Subscriber – Listens for messages from a topic.

1.1 MQTT Communication Flow

🔹 Publisher sends messages to a topic
🔹 Broker receives and forwards messages
🔹 Subscriber listens for topic updates


2. Setting Up MQTT in Python

We use the paho-mqtt library to implement MQTT in Python.

2.1 Install the Paho-MQTT Library

pip install paho-mqtt

3. Running an MQTT Broker

For testing, install Mosquitto MQTT broker:

On Linux/macOS:

sudo apt install mosquitto mosquitto-clients
sudo systemctl start mosquitto

On Windows: Download from Mosquitto


4. Implementing MQTT in Python

4.1 Writing an MQTT Publisher

import paho.mqtt.client as mqtt

broker = "localhost" # Change to broker IP if remote
port = 1883
topic = "home/temperature"

client = mqtt.Client()
client.connect(broker, port)

for i in range(5):
message = f"Temperature: {20 + i}°C"
client.publish(topic, message)
print(f"Published: {message}")

client.disconnect()

This script sends temperature updates to the broker.


4.2 Writing an MQTT Subscriber

import paho.mqtt.client as mqtt

broker = "localhost"
topic = "home/temperature"

def on_message(client, userdata, message):
print(f"Received: {message.payload.decode()}")

client = mqtt.Client()
client.connect(broker)
client.subscribe(topic)
client.on_message = on_message

client.loop_forever()

This listens for temperature updates.


5. QoS (Quality of Service) Levels

MQTT supports three QoS levels:

QoS LevelDescription
0 (At most once)Message sent without acknowledgment (Fastest, but may be lost).
1 (At least once)Message delivered at least once (May receive duplicates).
2 (Exactly once)Ensures one-time delivery (Most reliable but slowest).

Modify QoS in publish/subscribe:

client.publish(topic, message, qos=1)  
client.subscribe(topic, qos=2)

6. Securing MQTT Communication

🔹 Enable Authentication: Username & Password
🔹 Use TLS Encryption for secure transmission
🔹 Restrict Topics for better security

6.1 Setting Up Authentication

Modify Mosquitto config file (mosquitto.conf):

allow_anonymous false
password_file /etc/mosquitto/passwd

Create a password file:

mosquitto_passwd -c /etc/mosquitto/passwd username

6.2 Connecting with Authentication in Python

client.username_pw_set("username", "password")
client.connect(broker, port)

7. IoT Project: Sending Sensor Data with MQTT

7.1 Simulating a Temperature Sensor

import paho.mqtt.client as mqtt
import random
import time

broker = "localhost"
topic = "sensor/temp"

client = mqtt.Client()
client.connect(broker)

while True:
temp = round(random.uniform(20.0, 30.0), 2)
client.publish(topic, f"Temperature: {temp}°C")
print(f"Sent: {temp}°C")
time.sleep(2)

This script sends random temperature values every 2 seconds.


8. Cloud-Based MQTT Brokers

🔹 HiveMQ – Free public broker: broker.hivemq.com
🔹 EMQX – Scalable MQTT cloud broker
🔹 Adafruit IO – MQTT for IoT projects

Connecting to a Cloud MQTT Broker:

broker = "broker.hivemq.com"
client.connect(broker, 1883)

Leave a Reply

Your email address will not be published. Required fields are marked *