archive2022

MQTT retained messages and last will: knowing when a sensor is gone

How retained messages and the last will work in MQTT, how to combine them into an online/offline status, and the traps with stale retained values.

3 min read#edge#mqtt#iot

My dashboard showed 21.4 °C for the balcony sensor for three days before I noticed the battery was dead. The balcony node was a quick test build, and I had left out the status topic that all my other nodes have. Plain MQTT does not tell you that a value is old. Two features help: retained messages and the last will. This is the version I now point people to, with the traps I have seen since.

Retained messages

A normal message goes to the clients that are subscribed at that moment, and then it is gone. A retained message is also stored by the broker, one per topic, and a client that subscribes later gets it at once.

mosquitto_pub -h 192.168.1.10 -t home/livingroom/temp -m 21.4 -r
mosquitto_sub -h 192.168.1.10 -t home/livingroom/temp -v
# prints at once: home/livingroom/temp 21.4

Retain state: the current value, a setting, online or offline. Do not retain events like “button pressed” or “door opened”, because a new subscriber would see an old event as if it just happened.

Last will

When a client connects, it can give the broker a “will”: a topic, a payload, QoS and a retain flag. If the client goes away without a clean DISCONNECT (power loss, network down, crash), the broker publishes the will.

The broker notices a dead client when the keepalive time runs out, after about 1.5 times the keepalive interval. With keepalive=60, expect up to about 90 seconds before the will is sent.

Online/offline status

The two together give a status topic that is always current, also for clients that subscribe later. Set the will to offline, retained. Right after connecting, publish online, retained. On a planned shutdown, publish offline yourself before you disconnect.

With paho-mqtt in Python:

import paho.mqtt.client as mqtt

STATUS = "home/sensor-01/status"

def on_connect(client, userdata, flags, rc):
    if rc == 0:
        client.publish(STATUS, "online", qos=1, retain=True)

client = mqtt.Client(client_id="sensor-01")
client.will_set(STATUS, "offline", qos=1, retain=True)
client.on_connect = on_connect
client.connect("192.168.1.10", 1883, keepalive=60)
client.loop_start()

The online publish belongs in on_connect. paho reconnects on its own after a network problem and runs on_connect again, so the status goes back to online. If it comes right after connect() instead, the status stays offline after the first reconnect. It is the same rule as for subscriptions.

Stale retained values

A retained message stays on the broker until it is replaced, also after the sensor is removed for good. To delete it, publish an empty retained message:

mosquitto_pub -h 192.168.1.10 -t home/livingroom/temp -r -n

I also put a timestamp in the data messages, so the dashboard can mark old values:

{"value": 21.4, "ts": 1665830400}

One side effect: when Telegraf subscribes, it gets all retained messages first, so each restart writes one extra old data point. That has not bothered me. If it does bother you, retain only the status topics and not the data.