MQTT Messaging: Lightweight Publish/Subscribe for IoT
MQTT (Message Queuing Telemetry Transport) is a lightweight messaging protocol designed for constrained devices and unreliable networks — perfect for IoT.
Key idea:
MQTT uses a publish/subscribe model. Clients publish messages to topics, and the broker delivers them to all clients subscribed to those topics.
MQTT Architecture
Publisher ──▶ Broker ◀── Subscriber
│
▼
[Topic: home/livingroom/temp]
MQTT Brokers
| Broker | Type | Use Case |
|---|---|---|
| Mosquitto | Local/Cloud | Self-hosted, free, popular |
| HiveMQ Cloud | Cloud | Managed MQTT, free tier |
| EMQX | Local/Cloud | Enterprise-grade |
| Adafruit IO | Cloud | Includes dashboard |
Core Concepts
| Concept | Description |
|---|---|
| Topic | Hierarchical string: home/livingroom/temperature |
| QoS 0 | At most once (fire and forget) |
| QoS 1 | At least once (acknowledged) |
| QoS 2 | Exactly once (guaranteed delivery) |
| Retained | Last message stored for new subscribers |
| Last Will | Message sent if client disconnects unexpectedly |
Example: Home Automation Topics
home/livingroom/temperature → Temperature sensor publishes here
home/livingroom/humidity → Humidity sensor publishes here
home/livingroom/light/set → Commands to control light
home/livingroom/light/status → Light reports state
QoS Levels Explained
// QoS 0: Fire and forget
client.publish("topic", "data", 0);
// QoS 1: Acknowledged delivery
client.publish("topic", "data", 1);
// QoS 2: Guaranteed delivery (slowest)
client.publish("topic", "data", 2);Key Takeaways
- MQTT uses publish/subscribe via a central broker
- Topics are hierarchical strings with
/separators - Three QoS levels: 0 (at most once), 1 (at least once), 2 (exactly once)
- Retained messages give new subscribers the last value
- Last Will handles unexpected disconnections
Resources
- MQTT Essentials (HiveMQ): https://mqttessentials.com/
- Video: MQTT Explained - https://www.youtube.com/watch?v=3rw6YwNlzqQ
- Mosquitto Broker: https://mosquitto.org/
- MQTT 5.0 Specification: https://docs.oasis-open.org/mqtt/mqtt/v5.0/mqtt-v5.0.html