Skip to content
GEEKnodes

Electronics

MQTT Explained for Home Automation: Broker, Topics and ESP32

What MQTT is and how it works in home automation: broker, topics, wildcards, QoS and retained messages, with an ESP32 example that publishes the temperature.

MQTT is the language thousands of sensors, smart plugs and light bulbs use to talk to each other. It’s lightweight, runs on very small boards like the ESP32 and doesn’t depend on any cloud: everything stays inside your network. If you’re into home automation, sooner or later you’ll run into it.

In this guide you’ll see what a broker is, how topics are organized and how to get an ESP32 to publish the temperature of a room.

In short

  • MQTT uses the publish/subscribe model: devices don’t talk to each other, they talk to a broker that distributes the messages.
  • Every message goes to a topic, a text path such as casa/salon/temperatura.
  • The wildcards + (one level) and # (everything below) let you listen to many topics at once.
  • QoS decides how strongly delivery is guaranteed, and retain keeps the last value for anyone who connects later.
  • In Home Assistant, the most common broker is Mosquitto, which installs as an app.

What MQTT is and why it’s used in home automation

MQTT (Message Queuing Telemetry Transport) is a messaging protocol designed for devices with little memory and unreliable networks. An MQTT message can have a header of just a few bytes, so an ESP32 handles it effortlessly.

In home automation it has three clear advantages:

  • It’s local: the broker is in your home, usually on the same machine as Home Assistant.
  • It’s universal: Home Assistant, Node-RED, Zigbee2MQTT, Tasmota, ESPHome and almost every programming language understand it.
  • It decouples: the sensor doesn’t need to know who reads its data. You can add receivers without touching the sensor.

How it works: broker, publishers and subscribers

Think of the broker as a post office:

  1. A device publishes a message to a topic: “casa/salon/temperatura is 22.5”.
  2. The broker receives it and checks who is subscribed to that topic.
  3. The subscribers (Home Assistant, your phone, another ESP32) get a copy.

The same device can publish and subscribe at the same time. For example, an ESP32 with a relay publishes its state and subscribes to a command topic to turn on or off.

The connection is always opened by the device toward the broker, on port 1883 (unencrypted) or 8883 (with TLS). That’s why a sensor behind any router works without opening ports.

An ESP32 publishes to the topic casa/salon/temperatura; the broker delivers the message to a subscribed phone and server
The publisher doesn’t know who’s listening: the broker delivers every message.

Topics and wildcards: how to organize messages

A topic is a slash-separated path, similar to a folder path. You don’t need to create them beforehand: they exist as soon as someone publishes to them.

A simple structure that’s easy to maintain (in this example, casa means home, salon living room, cocina kitchen and estado state):

casa/salon/temperatura
casa/salon/humedad
casa/cocina/temperatura
casa/cocina/luz/estado
casa/cocina/luz/set

To subscribe to several at once you have two wildcards:

WildcardMeansExampleReceives
+Any single levelcasa/+/temperaturaThe temperature of every room
#That level and everything below itcasa/#Everything that happens at home

Some good practices:

  • Lowercase, no spaces or accented characters.
  • Don’t start the topic with /: it creates an empty level that causes confusion.
  • Keep state (.../estado) separate from commands (.../set) to avoid loops.
MQTT topic tree with casa, salon and cocina, and wildcard examples casa/+/temperatura and casa/#
Topics form a tree; wildcards choose which branch to listen to.

QoS, retained messages and last will

Three options worth understanding from the start:

OptionWhat it doesWhen to use it
QoS 0At most once, no acknowledgmentFrequent sensor readings
QoS 1At least once; may arrive duplicatedImportant commands (turning something on)
QoS 2Exactly once, with more back-and-forthCases where a duplicate would be a problem
RetainThe broker stores the last message on the topicStates: whoever connects later gets it right away
Last will (LWT)Message the broker publishes if the device disappearsKnowing whether a sensor is online or offline

In home automation, the usual setup is QoS 0 or 1 for almost everything, retain on states and a last will on every device.

The three MQTT QoS levels: QoS 0 at most once, QoS 1 at least once and QoS 2 exactly once
Higher QoS means more guarantees, but also more round-trip messages.

Setting up the broker in Home Assistant

If you use Home Assistant OS (we explain it in the guide to Home Assistant on a Raspberry Pi):

  1. Go to Settings, Apps, search for Mosquitto broker and install it.
  2. Start it and turn on start on boot.
  3. Create a Home Assistant user just for your MQTT devices (for example, mqtt-sensores). Mosquitto accepts Home Assistant users.
  4. In Settings, Devices & services, the MQTT integration will show up as discovered. Click Configure.

If you prefer container installs, Mosquitto has an official Docker image. Keep in mind that, since version 2, it only accepts local connections until you configure a listener and authentication.

To see what’s flowing through the broker from a computer with the Mosquitto clients installed:

mosquitto_sub -h 192.168.1.10 -u mqtt-sensores -P 'your-password' -t 'casa/#' -v

-v shows the topic next to each message. It’s the number one debugging tool.

Example: an ESP32 that publishes the temperature

This Arduino IDE sketch uses the PubSubClient library, which you install from the Library Manager. It publishes a reading every minute with retain and announces whether it’s connected using the last will.

#include <WiFi.h>
#include <PubSubClient.h>

const char* WIFI_SSID = "YourWiFi";
const char* WIFI_PASS = "YourWiFiPassword";
const char* MQTT_HOST = "192.168.1.10";
const char* MQTT_USER = "mqtt-sensores";
const char* MQTT_PASS = "your-password";

WiFiClient red;
PubSubClient mqtt(red);
unsigned long ultimaLectura = 0;

float leerTemperatura() {
  return 22.5;  // replace with your sensor reading
}

void conectarMqtt() {
  while (!mqtt.connected()) {
    if (mqtt.connect("sensor-salon", MQTT_USER, MQTT_PASS,
                     "casa/salon/estado", 0, true, "offline")) {
      mqtt.publish("casa/salon/estado", "online", true);
    } else {
      delay(5000);
    }
  }
}

void setup() {
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  while (WiFi.status() != WL_CONNECTED) delay(500);
  mqtt.setServer(MQTT_HOST, 1883);
}

void loop() {
  if (!mqtt.connected()) conectarMqtt();
  mqtt.loop();

  if (millis() - ultimaLectura > 60000) {
    ultimaLectura = millis();
    char texto[8];
    snprintf(texto, sizeof(texto), "%.1f", leerTemperatura());
    mqtt.publish("casa/salon/temperatura", texto, true);
  }
}

For the real reading, pick a sensor with our DHT22 vs DS18B20 comparison. And if the sensor is going to run on batteries, combine MQTT with the deep sleep we explain in powering an ESP32 from a battery.

For Home Assistant to create the entity automatically, the device can publish a configuration message using MQTT discovery (topics starting with homeassistant/). Otherwise, you can declare the sensor manually in the configuration.

MQTT, ESPHome native API or HTTP

MQTTESPHome native APIHTTP
Needs a brokerYesNoNo
Understood by other systemsAlmost allMainly Home AssistantAll, but not real time
Real time and two-wayYesYesNo (you ask and wait)
EffortMediumMinimalMedium

If you only use Home Assistant and don’t want to write code, ESPHome with its native API is the most convenient option. MQTT shines when several systems need to share the same data or when you write your own firmware.

Frequently asked questions

Does MQTT need internet access? No. The broker can live on your local network and everything works without an outside connection. You only need internet if you use a cloud broker.

Is MQTT secure? It is if you set it up properly: a username and password for each client, no anonymous access and port 1883 not exposed to the internet. For remote access, a WireGuard VPN is better than opening ports.

What’s the difference between MQTT and Zigbee? Zigbee is a radio network between devices; MQTT is a messaging protocol over your IP network. They work together: Zigbee2MQTT translates Zigbee devices into MQTT messages.

Why does my ESP32 keep disconnecting from the broker? The usual causes are mqtt.loop() not being called often enough (because of a long delay), two devices with the same client ID or weak Wi-Fi.

Where do I start if I’ve never used an ESP32? With the basics: our Arduino and ESP32 getting started guide takes you from your first LED to connected projects.

Accessibility preferences

Quick profiles

Text and reading

Text size
Default
Line height
Default
Letter spacing
Default
Word spacing
Default

Colour

Motion and orientation

Cursor