Last Updated: May 1, 2025
MQTT Concepts
| Item | Description |
|---|---|
Broker | Central server that routes messages between publishers and subscribers |
Topic | Hierarchical string (e.g., sensors/temperature/bedroom) — subscribers filter by topic |
Publish | Send a message to a topic on the broker |
Subscribe | Express interest in a topic (with optional wildcards) |
Client ID | Unique identifier for each MQTT client connection |
Keep Alive | Max idle time (seconds) — client sends PINGREQ to stay connected |
Quality of Service (QoS)
| Item | Description |
|---|---|
QoS 0: At most once | Fire-and-forget — no acknowledgment, no retry. Fast, unreliable. |
QoS 1: At least once | Message acknowledged (PUBACK). Retransmit until ACK received. |
QoS 2: Exactly once | Four-way handshake — guaranteed exactly-once delivery. Slow but reliable. |
QoS is per-message | Publisher and subscriber can have different QoS levels |
Downgrade rule | Subscriber gets min(published QoS, subscribed QoS) |
Advanced MQTT Features
| Item | Description |
|---|---|
Retained Messages | Broker stores last message on a topic — new subscribers get it immediately |
Last Will and Testament | Pre-set message sent by broker if client disconnects unexpectedly |
Persistent Session | Broker remembers subscriptions and queues messages for offline clients |
Clean Session = false | Enable persistent session (messages queued between connections) |
Wildcard: + | Single-level wildcard: sensors/+/temperature matches any sensor name |
Wildcard: # | Multi-level wildcard: sensors/# matches everything under sensors/ |
Mosquitto Broker Quick Start
mosquitto -p 1883Start broker on default MQTT port
mosquitto_sub -t 'sensors/#' -vSubscribe to all sensor topics (verbose)
mosquitto_pub -t 'sensors/temp' -m '22.5'Publish a temperature reading
mosquitto_pub -t 'alerts' -m 'OFFLINE' --will-topic 'alerts' --will-payload 'OFFLINE'Publish with Last Will
mosquitto_pub -t 'config' -m 'v3' -rPublish retained message (new subs get it)
mosquitto_sub -t '#' --qos 2Subscribe with QoS 2 (exactly once)
Pro Tip: MQTT is the standard IoT messaging protocol — lightweight, binary, works over TCP or WebSocket. QoS 0 = fire-and-forget, QoS 1 = at-least-once, QoS 2 = exactly-once (slowest).