MQTT Protocol
Publish-subscribe messaging for IoT — broker, QoS, topics, and Home Assistant integration
Skills taught: embedded.mqtt
How MQTT Works: Broker, Topics, Pub/Sub
MQTT is a publish-subscribe protocol. Publishers send messages to topics (hierarchical paths like home/kitchen/temperature). Subscribers receive messages from topics they've registered interest in. The broker (server) routes all messages between clients. No publisher needs to know who subscribes — full decoupling.
MQTT Topic Structure
────────────────────
home/living-room/temperature → specific sensor
home/living-room/humidity
home/kitchen/temperature
home/# → all home/ subtopics (# wildcard)
home/+/temperature → temperature from any room (+ single-level wildcard)
Common IoT topic conventions:
cmnd/device-id/POWER → Tasmota: command to turn on
stat/device-id/RESULT → Tasmota: status result
homeassistant/sensor/01/state → Home Assistant auto-discovery
Installing Mosquitto Broker on Raspberry Pi
# Install Mosquitto MQTT broker
sudo apt update && sudo apt install -y mosquitto mosquitto-clients
# Start and enable at boot
sudo systemctl enable --now mosquitto
# Configure: allow anonymous connections on localhost
# (add auth for internet-facing brokers)
echo "allow_anonymous true" | sudo tee /etc/mosquitto/conf.d/local.conf
echo "listener 1883" >> /etc/mosquitto/conf.d/local.conf
sudo systemctl restart mosquitto
# Test: open two terminals
# Terminal 1 — subscribe:
mosquitto_sub -h localhost -t "test/#" -v
# Terminal 2 — publish:
mosquitto_pub -h localhost -t "test/hello" -m '{"value": 42}'
# Terminal 1 should receive: test/hello {"value": 42}
Python MQTT Publisher: Sending Sensor Data
import paho.mqtt.client as mqtt
import json
import time
import random
# Install: pip install paho-mqtt
BROKER = "localhost" # or your Pi's IP from other devices
PORT = 1883
CLIENT_ID = "sensor-01"
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, CLIENT_ID)
# Optional: last will message (sent if client disconnects unexpectedly)
client.will_set(
f"home/sensors/{CLIENT_ID}/status",
payload=json.dumps({"online": False}),
qos=1, retain=True
)
client.connect(BROKER, PORT, keepalive=60)
client.loop_start() # start background thread for MQTT
# Publish online status
client.publish(
f"home/sensors/{CLIENT_ID}/status",
json.dumps({"online": True}),
qos=1, retain=True
)
try:
while True:
payload = json.dumps({
"temperature": round(20 + random.uniform(0, 10), 1),
"humidity": round(40 + random.uniform(0, 30), 1),
"uptime": int(time.time())
})
result = client.publish(f"home/sensors/{CLIENT_ID}/data", payload, qos=1)
print(f"Published: {payload} [rc={result.rc}]")
time.sleep(5)
except KeyboardInterrupt:
print("Stopping...")
finally:
client.loop_stop()
client.disconnect()
Python MQTT Subscriber: Receiving and Acting on Data
import paho.mqtt.client as mqtt
import json
BROKER = "localhost"
def on_connect(client, userdata, flags, reason_code, properties):
print(f"Connected: {reason_code}")
# Subscribe in on_connect so it re-subscribes after reconnect
client.subscribe("home/#", qos=1)
print("Subscribed to home/#")
def on_message(client, userdata, msg):
topic = msg.topic
payload = msg.payload.decode("utf-8")
try:
data = json.loads(payload)
if "temperature" in data:
temp = data["temperature"]
print(f"[{topic}] Temperature: {temp}°C", end="")
if temp > 28:
print(" ⚠ HIGH TEMP — triggering cooling fan")
client.publish("home/actuators/fan", json.dumps({"on": True}), qos=1)
else:
print()
except json.JSONDecodeError:
print(f"[{topic}] Raw: {payload}")
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, "dashboard-01")
client.on_connect = on_connect
client.on_message = on_message
client.connect(BROKER, 1883, keepalive=60)
client.loop_forever() # blocking
MQTT QoS Levels
MQTT QoS 0 vs QoS 1 vs QoS 2
- QoS 0 — At Most Once: Fire and forget — no ACK
- QoS 1 — At Least Once: Guaranteed delivery with PUBACK
Tip: Use `retain=True` on status topics (online/offline, current setpoint) so new subscribers immediately get the last value without waiting for the next publish. Retained messages are stored by the broker and delivered instantly on subscribe.
Frequently Asked Questions
What is QoS in MQTT?
Quality of Service: QoS 0 = at most once (no guarantee, fastest), QoS 1 = at least once (may duplicate, guaranteed delivery), QoS 2 = exactly once (slowest, four-way handshake). Use QoS 1 for most IoT data; QoS 2 only for billing or financial messages.
How do I secure my MQTT broker so only my devices can connect?
Add password authentication to Mosquitto: create a password file with `mosquitto_passwd -c /etc/mosquitto/passwd myuser`, add `password_file /etc/mosquitto/passwd` and `allow_anonymous false` to mosquitto.conf. For internet-facing brokers, also enable TLS on port 8883 using Let's Encrypt certificates.
Can I use a cloud MQTT broker instead of running Mosquitto locally?
Yes. HiveMQ Cloud (free tier), EMQX Cloud, and AWS IoT Core offer hosted MQTT brokers. Use them when devices are outside your local network. The paho-mqtt client code is the same — just change the broker hostname, port, and add TLS/authentication.