Home / Learn / Code for makers

MQTT explained: topics, brokers and QoS for ESP32, Pico W and Home Assistant

New to this? Read from the top. Already know the basics? Jump to Going deeper for intermediate and advanced detail.

An MQTT broker in the middle, with an ESP32 sensor publishing a temperature on the left and a phone and Home Assistant subscribed on the right
Beginner

MQTT is a lightweight messaging protocol designed for small devices on unreliable networks. It's how many ESP32 and Pico W sensors send readings, how Home Assistant talks to Zigbee2MQTT and ESPHome-style devices, and how industrial sensors report to the cloud. It's simple once you see the one big idea: devices never talk to each other directly.

Publish and subscribe

brokere.g. Mosquittogarden sensorpublish: home/garden/temperaturedoor sensorpublish: home/hall/doorphone dashboardsubscribe: home/garden/#Home Assistantsubscribe: home/#
Everything goes through the broker. A sensor doesn't know or care who's listening.

In the middle is a broker, a server program such as Mosquitto, often running on a Raspberry Pi or inside Home Assistant. Devices connect to it as clients. A client can:

  • publish a message to a topic, such as home/garden/temperature;
  • subscribe to topics it's interested in, and the broker sends it every message published to them.

The sensor doesn't need to know the dashboard exists. Add a second dashboard, a logger or an automation and the sensor doesn't change at all. MQTT normally runs over TCP on port 1883, or 8883 when it's encrypted with TLS.

Topics and wildcards

Topics are text strings with levels separated by /, like file paths: home/kitchen/light/state. You design them yourself; keep them consistent, from general to specific. Subscribers can use two wildcards:

MQTT topic wildcards (subscribe only)
WildcardMatchesExample
+Exactly one levelhome/+/temperature gets the temperature from every room
#Any number of levels, at the end onlyhome/garden/# gets everything under garden

Topics starting with $, such as $SYS/, are used by the broker for its own statistics.

Quality of service (QoS)

MQTT QoS levels
QoSPromiseUse for
0At most once: sent, not acknowledged, may be lostFrequent sensor readings, where the next one is coming soon
1At least once: acknowledged and resent until it is, so it may arrive twiceMost commands and events
2Exactly once: a four-step handshakeWhere a duplicate would cause a problem, such as counting

Retained messages and last will

  • A message published with the retain flag is kept by the broker as the last known value for that topic. A client that subscribes later gets it straight away, so a dashboard shows the light is on without waiting for the next change.
  • A client can register a last will message when it connects. If it disappears without disconnecting properly, for example the power fails, the broker publishes the will for it, typically offline on a status topic.

Publishing from an ESP32 or Pico W

# MicroPython (ESP32 or Pico W): publish a temperature every 10 seconds
import time
from umqtt.simple import MQTTClient

client = MQTTClient("garden-sensor", "192.168.1.20")   # client ID, broker address
client.connect()

while True:
    temp = 21.5                                         # read your sensor here
    client.publish(b"home/garden/temperature", str(temp).encode())
    time.sleep(10)

Connect to Wi-Fi first (see ESP32 first steps or the Pico W web switch project). The umqtt.simple module is part of many MicroPython builds; if yours doesn't have it, install it with mip. Each client needs a unique client ID: two devices with the same ID keep kicking each other off the broker.

Subscribing from Python

# Python on a PC or Raspberry Pi (paho-mqtt 2.x): print every garden reading
import paho.mqtt.client as mqtt

def on_message(client, userdata, msg):
    print(msg.topic, msg.payload.decode())

client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
client.on_message = on_message
client.connect("192.168.1.20", 1883)
client.subscribe("home/garden/#")
client.loop_forever()

The paho-mqtt library is installed with pip install paho-mqtt; version 2 needs the CallbackAPIVersion argument shown. Run it inside a virtual environment.

Security

  • Don't leave a broker open to anonymous clients. Set up usernames and passwords, and give each device only the topics it needs.
  • Never expose port 1883 to the internet. For access from outside, use TLS on 8883 with proper certificates, or a VPN.
  • Remember that anything able to publish to a topic can control whatever subscribes to it. See smart home security.
Intermediate and advanced

Going deeper

Keep-alive

Each client tells the broker a keep-alive interval when it connects. If the broker hears nothing for one and a half times that interval, it treats the client as gone and sends its last will. Clients send small ping packets when they have nothing else to say.

Clean and persistent sessions

A client can ask the broker to remember its subscriptions and queue QoS 1 and 2 messages while it's offline, so a device that sleeps to save battery doesn't miss commands. In MQTT 5 this is controlled by the clean start flag and a session expiry interval.

Payloads

MQTT doesn't care what's in a message: it's just bytes. Plain numbers are simplest for one value; JSON is common when a message carries several values, such as temperature and humidity together.

Sources

The main references behind this guide. Numbers we worked out ourselves, such as the code outputs, come from running the code.