MQTT basics
Run a password-protected Mosquitto broker on your own computer, publish from the ESP32-C5 with a last will, and see retained messages and QoS behave in a test that runs without hardware.
You will learn
- Explain what a broker, a topic and a wildcard subscription are
- Choose QoS 0, 1 or 2 for a message and predict the QoS a subscriber receives
- Use retained messages and a last will to publish a device's online or offline status
- Run a local Mosquitto broker with passwords and publish to it from the ESP32-C5
In lesson 6 the board asked one server for one page. Most sensors work the other way round: they push readings out, and any number of programs want them. MQTT is the protocol most IoT projects use for that. This lesson sets up a broker on your own computer, has the ESP32-C5 publish to it, and shows three features beginners often misread: quality of service (QoS), retained messages and the last will. Everything here runs on your network, with no cloud account.
Broker, clients and topics
MQTT has one server, the broker, and many clients. A client publishes a message to a topic, a text name such as fieldguide/c5-a1b2c3/temperature. Other clients subscribe to topics, and the broker forwards each message to every matching subscriber. Publishers and subscribers never talk to each other directly and need not be online at the same time.
Topics are levels separated by /. Subscriptions may use two wildcards, defined in section 4.7 of the MQTT 3.1.1 standard:
+matches exactly one level.fieldguide/+/statusmatches every device’s status topic.#matches the level it stands in and everything below, and must come last.fieldguide/#matches everything this course publishes.- Wildcards at the start of a filter do not match topics that begin with
$, so subscribing to#does not pull in the broker’s own$SYS/statistics.
The firmware in this lesson uses two topics per device, and lesson 9 subscribes to the same ones:
| Topic | Payload | QoS | Retained |
|---|---|---|---|
fieldguide/<device>/status |
online or offline |
1 | yes |
fieldguide/<device>/temperature |
text such as 23.4 |
0 | no |
<device> is c5- followed by the last three bytes of the board’s Wi-Fi MAC address, so two boards never share a name.
A broker on your own computer
Eclipse Mosquitto is a small open-source broker. Its download page lists Windows installers, Homebrew for macOS and packages for Debian, Ubuntu and Raspberry Pi, with 2.1.4 as the current version. It is locked down by default: according to its configuration manual, allow_anonymous defaults to false once you define a listener, and with no listener at all it accepts connections only from the same machine. So you need a short configuration file. The example ships this one:
# Minimal Mosquitto 2.x broker for your own network.
# Start it from this folder with: mosquitto -c mosquitto.conf -v
# Create the password file first: mosquitto_passwd -c passwd sensor1
listener 1883
allow_anonymous false
password_file passwd
# Keep retained messages and sessions across broker restarts.
persistence true
Create the password file in the same folder, then start the broker:
cd examples/l07-mqtt/broker
mosquitto_passwd -c passwd sensor1 # asks for a password; -c creates (and overwrites) the file
mosquitto -c mosquitto.conf -v
We ran exactly this with Mosquitto 2.1.4. A client with the right user name and password could publish, and an anonymous client was refused with “not authorised”. persistence true matters for this lesson: the manual says persistence defaults to false, which keeps everything in memory, so retained messages would be lost when the broker restarts. With it on, Mosquitto writes mosquitto.db to the folder it runs in. The passwd file is listed in the example’s .gitignore. Leave out -c when you add a second user, or it replaces the file.
Your firewall may need to allow incoming connections on port 1883 for the ESP32-C5 to reach the broker.
Quality of service
QoS is a promise between one sender and the next hop, set per message:
| QoS | Name in the standard | Packets | What can go wrong |
|---|---|---|---|
| 0 | At most once | PUBLISH only | The message can be lost |
| 1 | At least once | PUBLISH, PUBACK | The message can arrive twice |
| 2 | Exactly once | PUBLISH, PUBREC, PUBREL, PUBCOMP | Nothing, at the cost of four packets |
The trap is that QoS applies to each hop separately. A subscriber asks for a maximum QoS when it subscribes, and section 3.8.4 of the standard says the broker delivers at the lower of the published QoS and the subscription’s granted QoS. A message published at QoS 2 to a subscriber that asked for QoS 0 arrives at QoS 0. The test later in this lesson shows exactly that.
For a sensor that reports every 10 s, QoS 0 is the sensible choice for readings: a lost reading is replaced by the next one, and no acknowledgement is waited for. Use QoS 1 for messages that must arrive, such as a status change or a command, and make the receiver tolerate duplicates. QoS 2 is rarely worth its extra round trips on a small device.
Retained messages
Normally the broker forwards a message and forgets it. A subscriber that connects a minute later sees nothing until the next publish. If the publisher sets the retain flag, the broker also stores that message as the topic’s retained message and sends it to every new subscriber straight away. A new retained message replaces the old one, and a retained message with an empty payload deletes it.
Retain the things that describe the current state of a device: whether it is online, its firmware version, a setpoint. Do not retain fast-changing readings. A retained temperature looks current to a new subscriber even if the sensor died yesterday. Lesson 9 shows how a dashboard handles that.
The last will
When a client connects, it can hand the broker a will: a topic, a payload, a QoS and a retain flag. The broker publishes the will if the connection closes without a proper DISCONNECT packet, for example when the device loses power or Wi-Fi. A clean disconnect discards the will.
The broker notices a silent device through keep-alive. The client promises to send something at least every keep-alive period, and the standard says the broker drops a client that has sent nothing for one and a half periods. The firmware sets 30 s, so a sensor that loses power is marked offline within one and a half keep-alive periods.
Put the pieces together and you get the standard status pattern. The will is offline, retained, on the status topic. Right after connecting, the device publishes online, retained, to the same topic. Any subscriber, at any time, sees the device’s real state.
The ESP32-C5 publisher
In ESP-IDF v6.1.1 the MQTT client is not part of the core tree. It is a managed component, espressif/mqtt, which idf.py fetches from Espressif’s component registry on the first build. The example pins it:
# In ESP-IDF v6.1.1 the MQTT client is not part of the core: idf.py fetches it from the
# component registry on the first build. Pinned to the version this example was built with.
dependencies:
espressif/mqtt: "1.1.0"
idf:
version: ">=6.1"
Our CI build resolved it to version 1.1.0 and recorded that in dependencies.lock, which you commit so every build uses the same code. The Wi-Fi code is lesson 6’s, moved into wifi.c. Copy main/secrets.h.example to main/secrets.h and fill in the Wi-Fi details, the broker address (your computer’s IP and port 1883) and the user you created with mosquitto_passwd.
The client configuration carries the will and the keep-alive:
// target: esp32c5 sdk: esp-idf tier: 1
// examples/l07-mqtt/main/app_main.c (excerpt)
uint8_t mac[6];
esp_read_mac(mac, ESP_MAC_WIFI_STA);
char device[16];
snprintf(device, sizeof(device), "c5-%02x%02x%02x", mac[3], mac[4], mac[5]);
snprintf(s_status_topic, sizeof(s_status_topic), "fieldguide/%s/status", device);
snprintf(s_temp_topic, sizeof(s_temp_topic), "fieldguide/%s/temperature", device);
const esp_mqtt_client_config_t cfg = {
.broker.address.uri = MQTT_BROKER_URI,
.credentials = {
.client_id = device,
.username = MQTT_USERNAME,
.authentication.password = MQTT_PASSWORD,
},
.session = {
.keepalive = 30, // seconds; the broker gives up after 1.5 x this with no traffic
.last_will = {
.topic = s_status_topic,
.msg = "offline",
.qos = 1,
.retain = 1,
},
},
};
esp_mqtt_client_handle_t client = esp_mqtt_client_init(&cfg);
esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, on_mqtt_event, NULL);
The event handler publishes online each time the client connects, including after a reconnect. The component reconnects by itself: in version 1.1.0 auto-reconnect is on by default and it retries after 10 s. Its default keep-alive is 120 s, which is why the example sets 30 s explicitly.
// target: esp32c5 sdk: esp-idf tier: 1
// examples/l07-mqtt/main/app_main.c (excerpt)
static void on_mqtt_event(void *arg, esp_event_base_t base, int32_t id, void *data)
{
esp_mqtt_event_handle_t ev = data;
switch ((esp_mqtt_event_id_t)id) {
case MQTT_EVENT_CONNECTED:
// Replace the retained "offline" (if any) with "online". QoS 1, retain = 1.
esp_mqtt_client_publish(ev->client, s_status_topic, "online", 0, 1, 1);
ESP_LOGI(TAG, "connected to broker");
break;
case MQTT_EVENT_DISCONNECTED:
ESP_LOGW(TAG, "broker connection lost, the client retries on its own");
break;
case MQTT_EVENT_PUBLISHED:
ESP_LOGI(TAG, "broker acknowledged message id %d", ev->msg_id); // QoS 1 and 2 only
break;
default:
break;
}
}
The reading comes from the ESP32-C5’s internal temperature sensor so that the lesson needs no extra parts. ESP-IDF’s documentation is clear that this sensor measures the silicon, not the room, and is not meant for ambient measurement. Replace it with your lesson 5 sensor reading when you have the board wired.
// target: esp32c5 sdk: esp-idf tier: 1
// examples/l07-mqtt/main/app_main.c (excerpt)
wifi_wait_connected(-1);
esp_mqtt_client_start(client);
while (true) {
float t;
char payload[16];
if (temperature_sensor_get_celsius(tsens, &t) == ESP_OK) {
snprintf(payload, sizeof(payload), "%.1f", t);
// QoS 0, not retained: a missed reading is replaced 10 s later.
esp_mqtt_client_publish(client, s_temp_topic, payload, 0, 0, 0);
ESP_LOGI(TAG, "%s = %s", s_temp_topic, payload);
}
vTaskDelay(pdMS_TO_TICKS(10000));
}
}
Build and flash as in lesson 6. On your computer, watch everything under fieldguide/ with the command-line subscriber that comes with Mosquitto:
mosquitto_sub -h 127.0.0.1 -u sensor1 -P '<password>' -t 'fieldguide/#' -v
-v prints the topic before each payload. Start it after the board is running and the first line is the retained online. Unplug the board and, after up to one and a half keep-alive periods, offline appears.
Test it without hardware
The example’s host/retained_and_qos_test.py uses paho-mqtt 2.x, the Eclipse Python client. Version 2.0 changed the callback signatures, so the client is created with mqtt.CallbackAPIVersion.VERSION2 and on_connect receives a ReasonCode object rather than an integer. The test runs in our CI against a throwaway Mosquitto broker and checks five behaviours:
# target: host sdk: python tier: 2
# examples/l07-mqtt/host/retained_and_qos_test.py (excerpt)
# 1. A sensor publishes a retained status (QoS 1) and one ordinary reading (QoS 0).
sensor, _ = make_client("sensor")
sensor.publish(status, "online", qos=1, retain=True).wait_for_publish(timeout=5)
sensor.publish(temp, "21.5", qos=0).wait_for_publish(timeout=5)
time.sleep(0.2)
# 2. A dashboard that connects later gets the retained status at once, but not the old reading.
dash, inbox = make_client("dashboard")
subscribe(dash, f"{BASE}/#", qos=1)
m = get(inbox)
assert m is not None and m.topic == status and m.payload == b"online" and m.retain, m
assert get(inbox, 0.5) is None, "a non-retained message must not be replayed"
print("retained: late subscriber received status=online with retain flag set; old reading not replayed")
# 3. QoS downgrade: published at QoS 2, subscribed at QoS 0, delivered at QoS 0.
low, low_inbox = make_client("low-qos")
subscribe(low, temp, qos=0)
sensor.publish(temp, "21.6", qos=2).wait_for_publish(timeout=5)
m_low, m_dash = get(low_inbox), get(inbox)
assert m_low is not None and m_low.qos == 0, m_low
assert m_dash is not None and m_dash.qos == 1, m_dash
print(f"qos: published at 2, delivered at {m_low.qos} to the QoS 0 subscriber and {m_dash.qos} to the QoS 1 subscriber")
# 4. Last will: a client that vanishes without DISCONNECT gets its will published by the broker.
flaky, _ = make_client("flaky", will=(status, "offline"))
flaky.loop_stop()
flaky.socket().close() # simulate power loss: no DISCONNECT packet is sent
m = get(inbox, timeout=10)
assert m is not None and m.topic == status and m.payload == b"offline", m
print("will: broker published status=offline after the connection dropped")
Run it against your own broker with MQTT_HOST, MQTT_PORT, MQTT_USERNAME and MQTT_PASSWORD set in the environment. It prints one line per check and PASS at the end. To fake a power cut, it closes the client’s socket without sending DISCONNECT, and the broker publishes the will.
For makers
One Mosquitto broker on a computer or a Raspberry Pi that stays on is enough for a house full of sensors. Give each device its own user in the password file so you can lock one out without touching the others. Use QoS 0 for readings, QoS 1 and retain for status, and keep topic names boring and consistent from the start.
For product teams
MQTT 3.1.1 leaves encryption to the transport and names TCP port 8883 for MQTT over TLS. On plain port 1883 everything, including the password in the CONNECT packet, crosses the network unencrypted. Anything beyond a lab network needs TLS with certificate checks, unique credentials per device and broker access-control lists that limit each device to its own topics. Treat the topic tree as an interface with a version, because renaming topics across a deployed fleet is painful. Size the broker for retained messages and persistent sessions, and decide who may clear a retained message. Check that the MQTT client component version is pinned in dependencies.lock and tracked like any other dependency.
Exercise
- With the board running, publish a retained message to
fieldguide/test/hellowithmosquitto_pub -r, then start a newmosquitto_sub. Clear it again with an empty retained message (mosquitto_pub -r -n). - Change the firmware’s keep-alive to 10 s, unplug the board, and time how long
offlinetakes to appear. - Subscribe with
mosquitto_sub -q 0 -dand publish at-q 2. The subscriber’s debug linereceived PUBLISH (d0, q0, ...)shows the QoS that arrived.
Summary
- A broker routes messages by topic.
+matches one level,#matches the rest, and wildcards skip$topics. - QoS is per hop, and a subscriber receives the lower of the published and the granted QoS.
- Retained messages give new subscribers the current state. Retain status, not readings.
- A retained
offlinewill plus a retainedonlineon connect gives every subscriber the device’s real state. - In ESP-IDF v6.1.1 the MQTT client is the managed component
espressif/mqtt, pinned throughidf_component.ymlanddependencies.lock.
Further reading
- MQTT Version 3.1.1, OASIS Standard, 29 October 2014: sections 3.1.2 (connect, will, keep-alive), 3.3.1 (retain) and 4.3 (QoS).
- mosquitto.conf manual, Eclipse Mosquitto.
- Paho MQTT Python client documentation, Eclipse Foundation, including the 1.x to 2.0 migration notes.
- espressif/mqtt in the ESP Component Registry, Espressif.