A dashboard that shows 23.4 °C is only useful if you know the sensor is still alive. MQTT has two features built for exactly this: retained messages, so a dashboard that opens later immediately gets the last known value, and the Last Will and Testament (LWT), a message the broker publishes for a device when it disappears without warning.
Quick answer: when the ESP32 connects, register a Last Will of offline, retained, on a status topic such as home/garage/status. Right after connecting, publish online, retained, to the same topic. Every subscriber now always sees the device's real availability. In PubSubClient that's client.connect(id, user, pass, "home/garage/status", 1, true, "offline") followed by client.publish("home/garage/status", "online", true). To delete a retained message, publish an empty retained message to its topic.
Retained Messages in One Minute
Normally the broker forwards a message to whoever is subscribed at that moment, then forgets it. A message published with the retain flag is also kept: the broker stores the last retained message for each topic and sends it straight away to every new subscriber.
| Normal message | Retained message | |
|---|---|---|
| Subscriber connected when it's sent | Receives it | Receives it |
| Subscriber that connects later | Gets nothing until the next message | Gets the last value immediately |
| Stored by the broker | No | Yes, one per topic, the latest |
| Survives a broker restart | — | Yes, if persistence is on (Mosquitto's default on Raspberry Pi OS) |
Retain state, not events. lamp/state = ON, garage/temperature = 21.4 and status = online are good retained topics: they describe how things are now. doorbell/pressed and lamp/toggle are events; retaining them replays the event to anyone who connects later, including the device itself after a reboot.
The Last Will in One Minute
When a client connects it can hand the broker a will: a topic, a message, a QoS and a retain flag. If the client later vanishes without a clean DISCONNECT (power cut, crash, Wi-Fi gone), the broker publishes the will for it. If the client disconnects properly, the will is discarded.
The broker notices a silent client by its missed keep-alive pings, and waits about 1.5 × the keep-alive before acting. PubSubClient's default keep-alive is 15 seconds, so "offline" appears roughly 20–25 seconds after the plug is pulled.
Choosing the Status Topic
Give every device its own status topic at the top of its branch, and keep it separate from readings and commands:
home/garage/status online / offline (retained, also the Last Will)
home/garage/temperature 21.4 (retained: current value)
home/garage/door/state closed (retained: reported state)
home/garage/door/set open (NOT retained: a command)With that layout, one subscription to home/+/status gives a dashboard the availability of every device in the house, and the topic naming stays predictable as you add boards. Use the same two payloads everywhere, online and offline. That's what Home Assistant expects by default, and the same convention used by Tasmota and many other firmwares, so mixed systems agree.
The online message is often called the birth message: the counterpart to the will. Publishing it retained on every connect is what makes the pattern self-healing: the moment a board reconnects, the retained offline left by its will is replaced.
Use QoS 1 for both, so subscribers receive them at least once even over a patchy connection. More on structuring topics in MQTT topic naming best practices.
The ESP32 Code
This is the connect function from a PubSubClient sketch. It registers the will, announces online, and restores subscriptions. The complete sketch around it, with non-blocking reconnects, is in ESP32 MQTT auto-reconnect without blocking.
const char* STATUS_TOPIC = "home/garage/status";
bool connectMqtt() {
String id = "esp32-" + WiFi.macAddress(); // unique per board
id.replace(":", "");
bool ok = mqtt.connect(
id.c_str(),
"esp32-garage", "YOUR_MQTT_PASSWORD", // broker login
STATUS_TOPIC, // will topic
1, // will QoS
true, // retain the will
"offline" // will message
);
if (!ok) return false;
mqtt.publish(STATUS_TOPIC, "online", true); // retained "online" replaces the old "offline"
mqtt.subscribe("home/garage/cmd/#");
return true;
}Planned shutdowns. Because a clean mqtt.disconnect() cancels the will, publish offline yourself before any deliberate disconnect, reboot or OTA update:
mqtt.publish(STATUS_TOPIC, "offline", true);
mqtt.disconnect();
ESP.restart();Clearing and Inspecting Retained Messages
Retained messages stay on the broker until replaced. To see every retained message under a topic, connect a subscriber: the retained ones arrive immediately.
mosquitto_sub -h 192.168.1.20 -u USER -P PASS -t 'home/#' -v --retained-onlyTo delete one, publish an empty message with the retain flag (-n sends a zero-length payload):
mosquitto_pub -h 192.168.1.20 -u USER -P PASS -t 'home/garage/status' -r -nFrom an ESP32, mqtt.publish(topic, "", true) does the same. Clear the status topic when you retire a device, or dashboards keep showing a board that no longer exists. MQTT Explorer also has a delete button for retained topics.
Using the Status Topic
Home Assistant. In an MQTT sensor or switch, point availability_topic at the status topic, with payload_available: "online" and payload_not_available: "offline". Entities then show Unavailable instead of a frozen value when the board disappears. Discovery and full examples are in MQTT with ESP32 and Home Assistant.
Node-RED. An mqtt in node on home/+/status feeds a dashboard text widget or an alert: a switch node routes offline to a Telegram or email notification. The dashboard side is in Node-RED Dashboard 2.0.
Availability isn't freshness. A board can be online while its sensor has failed and it publishes nothing. Track the time of the last valid reading separately (Node-RED can timestamp each message), and show a reading as stale after a sensible timeout, for example three missed reporting intervals.
Test It in Two Minutes
- On a PC or the broker, watch the status topic:
mosquitto_sub -h BROKER -u USER -P PASS -t 'home/garage/status' -v. - Power the ESP32.
home/garage/status onlineappears. - Pull its USB cable. After about 20–25 seconds,
home/garage/status offlineappears: that's the broker publishing the will. - Stop the subscriber and start it again. It immediately prints
offline: the will was retained. - Plug the ESP32 back in.
onlineappears again.
You can also try a will without any hardware: mosquitto_sub -t test/x --will-topic test/status --will-payload offline --will-retain, then kill that terminal's process (closing the window, not Ctrl+C, which disconnects cleanly) and watch test/status in another window.
Deep Sleep and Last Will Don't Mix
A battery sensor that wakes, publishes and goes back to deep sleep drops its connection without a clean disconnect every time, so the broker publishes offline after every reading. Two better options for sleeping devices:
- No will at all. Publish each reading with a timestamp (or retained), and let the dashboard mark the sensor stale if no reading arrives within, say, two wake intervals.
- Disconnect cleanly before sleeping. Call
mqtt.disconnect()beforeesp_deep_sleep_start(). The will is cancelled, and the last retainedonlinestays, so pair it with the staleness check above.
Never Retain One-Shot Commands
A retained UNLOCK, OPEN or TOGGLE is delivered again every time the device reconnects or reboots, and it repeats the action. Send commands without retain, and retain the reported state the device publishes after acting. If you deliberately want a retained "desired state" (for example heating/target = 21), make sure the firmware treats it as a setting to apply, not an action to perform once.
Troubleshooting
| Problem | Cause | Fix |
|---|---|---|
offline never appears | Will not registered, or the device disconnected cleanly | Check the connect() call includes the will; graceful disconnects cancel it |
offline takes minutes | Long keep-alive | mqtt.setKeepAlive(15); the delay is about 1.5 × that |
Status stuck on offline while the board works | online published without retain, or to a different topic | Publish online retained to the exact will topic |
| New subscribers see nothing | Not retained, or a typo or case difference in the topic | Use -r; compare topics character by character |
| Old devices still listed | Their retained status was never cleared | mosquitto_pub -t TOPIC -r -n |
| Retained values gone after a broker reboot | Persistence off | persistence true in mosquitto.conf |
| Two devices overwrite each other's status | Shared topic or client ID | One status topic and one client ID per device |
| Sleeping sensor flips offline every cycle | Deep sleep looks like a crash | Drop the will, or disconnect cleanly before sleeping |
FAQ
What is an MQTT Last Will? A message the client registers when it connects, which the broker publishes on its behalf if the client disappears without disconnecting properly.
Should the Last Will be retained? For status topics, yes: otherwise a dashboard that opens after the device died never learns it's offline.
How do I delete a retained MQTT message? Publish a zero-length message with the retain flag to the same topic: mosquitto_pub -t TOPIC -r -n.
Does disconnect() send the Last Will? No. A clean disconnect cancels it, so publish offline yourself first.
What QoS should the will use? QoS 1 is the usual choice, so the broker makes sure subscribers receive it.
Next Steps
- MQTT explained: broker, topics, QoS, retained and LWT
- MQTT topic naming best practices: where status topics fit in your tree
- Test MQTT without hardware: more
mosquitto_pubandmosquitto_subrecipes




