0
0
Raspberry Piprogramming~5 mins

MQTT with QoS levels in Raspberry Pi

Choose your learning style9 modes available
Introduction

MQTT with QoS levels helps control how messages are sent and received reliably between devices.

When you want to make sure a message is delivered at least once.
When you want to avoid duplicate messages.
When you want the fastest message delivery without guarantees.
When you need reliable communication between sensors and a server.
When you want to balance speed and reliability in message delivery.
Syntax
Raspberry Pi
client.publish(topic, message, qos=level)

# qos levels:
# 0 - At most once (fast, no guarantee)
# 1 - At least once (guaranteed delivery, possible duplicates)
# 2 - Exactly once (guaranteed delivery, no duplicates)

The qos parameter controls message delivery quality.

Higher QoS means more reliability but slower delivery.

Examples
Sends temperature once, no guarantee it arrives.
Raspberry Pi
client.publish('home/temperature', '22C', qos=0)
Sends temperature and retries until confirmed received.
Raspberry Pi
client.publish('home/temperature', '22C', qos=1)
Sends temperature exactly once with full handshake.
Raspberry Pi
client.publish('home/temperature', '22C', qos=2)
Sample Program

This program connects to a public MQTT broker and sends three messages with QoS levels 0, 1, and 2. It then disconnects and prints a confirmation.

Raspberry Pi
import paho.mqtt.client as mqtt

# Define MQTT broker address
broker = 'test.mosquitto.org'

# Create MQTT client
client = mqtt.Client()

# Connect to broker
client.connect(broker, 1883, 60)

# Publish messages with different QoS levels
client.publish('test/qos', 'Message with QoS 0', qos=0)
client.publish('test/qos', 'Message with QoS 1', qos=1)
client.publish('test/qos', 'Message with QoS 2', qos=2)

# Disconnect
client.disconnect()

print('Messages sent with QoS 0, 1, and 2')
OutputSuccess
Important Notes

QoS 0 is fastest but may lose messages.

QoS 1 retries sending until acknowledged, so duplicates can happen.

QoS 2 ensures message is received exactly once but is slower.

Summary

MQTT QoS controls message delivery reliability.

Use QoS 0 for speed, QoS 1 for guaranteed delivery, QoS 2 for no duplicates.

Choose QoS based on your application's needs for speed and reliability.