Publishing sensor data with MQTT
About this lesson
Your ESP32-DevKitC is on Wi-Fi; now make it report. Follow one temperature reading through Espressif's esp-mqtt client: connect once to a broker, read the sensor, turn 21.5 into the text "21.5", publish a 27-byte packet at QoS 1, and wait for the PUBACK while a copy waits in the outbox. Then see what the client does when Wi-Fi drops. The lesson “Joining Wi-Fi from an ESP32” gets the board online, and the Networking lesson “IoT: MQTT and constrained devices” explains the protocol in depth; here you drive it from firmware.
A sensor node on the network
Our ESP32-DevKitC has already joined Wi-Fi. Now it should report the kitchen temperature. It will not send to the dashboard directly: it sends to a broker, a server in the middle, using MQTT, and the broker passes it on.
board ESP32-DevKitC (ESP-IDF, esp-mqtt client, C) Wi-Fi already joined: an IP address on the home network broker mqtt://192.168.1.20 (TCP port 1883) topic home/kitchen/temp dashboard subscribes to that topic at the broker
Read the lesson step by step
A sensor node on the network
Our ESP32-DevKitC has already joined Wi-Fi. Now it should report the kitchen temperature. It will not send to the dashboard directly: it sends to a broker, a server in the middle, using MQTT, and the broker passes it on.
board ESP32-DevKitC (ESP-IDF, esp-mqtt client, C) Wi-Fi already joined: an IP address on the home network broker mqtt://192.168.1.20 (TCP port 1883) topic home/kitchen/temp dashboard subscribes to that topic at the brokerConnect once, stay connected
esp_mqtt_client_start opens one TCP connection to the broker on port 1883 and sends a CONNECT packet. The broker answers CONNACK, code 0: accepted. The client then calls our handler with MQTT_EVENT_CONNECTED.
line 1 esp_mqtt_client_start(client); TCP ESP32 -> 192.168.1.20:1883 CONNECT client id, keep alive 120 s (the default) CONNACK return code 0 = connection accepted event MQTT_EVENT_CONNECTED -> up = true the connection stays open: every later message reuses itRead the sensor: 21.5
Inside the loop, read_temp() asks the sensor driver for a reading. It returns 21.5 degrees as a float. A float is a binary number, not text yet, so it cannot go into a message as it is.
line 2 float t = read_temp(); t 21.5 (a 4-byte float in RAM) read_temp is your sensor driver; any sensor worksTurn the number into text
MQTT carries bytes; the broker never looks inside. We choose plain text, so any app can read it. snprintf writes "21.5" into buf: 4 characters plus a zero byte that marks the end. The 8 stops it overflowing buf.
line 3 snprintf(buf, 8, "%.1f", t); "%.1f" one digit after the point -> "21.5" buf '2' '1' '.' '5' '\0' payload 4 bytes; '\0' only marks the end in C 8 buf size: snprintf never writes past itPublish at QoS 1
esp_mqtt_client_publish(client, TOPIC, buf, 0, 1, 0): length 0 means "count it from the string", QoS 1, no retain. The client builds a 27-byte PUBLISH packet, keeps a copy in its outbox and returns its id, 1.
lines 4-5 esp_mqtt_client_publish(client, TOPIC, buf, 0, 1, 0); PUBLISH 0x32 type 3, QoS 1, DUP 0, RETAIN 0 25 remaining length (1 byte) 0x00 0x11 topic length 17 home/kitchen/temp 0x00 0x01 packet id 1 (QoS 1 only) 21.5 payload, 4 bytes total 2 + 19 + 2 + 4 = 27 bytes returns msg_id 1 (-1 failure, -2 outbox full)Over Wi-Fi to the broker
The packet leaves over the radio, through the router, along the open TCP connection to the broker. TCP delivers its bytes in order. The topic travels inside the packet, so the broker knows what this message is about.
ESP32 --Wi-Fi--> router --TCP :1883--> broker PUBLISH topic home/kitchen/temp payload "21.5", QoS 1, id 1 outbox still holds a copy: not acknowledged yetThe broker forwards a copy
The dashboard subscribed to home/kitchen/temp earlier. The broker matches the topic and sends it a copy. The ESP32 never knows who is listening: add a second app and the firmware does not change.
match home/kitchen/temp == dashboard's subscription forward PUBLISH "21.5" to every matching subscriber firmware unchanged when subscribers come and goPUBACK: delivered at least once
For QoS 1 the broker answers with a 4-byte PUBACK carrying packet id 1. The client deletes its outbox copy and calls our handler with MQTT_EVENT_PUBLISHED, msg_id 1. Now we know the broker has it.
PUBACK 0x40 0x02 0x00 0x01 (4 bytes, packet id 1) outbox copy of id 1 removed event MQTT_EVENT_PUBLISHED, msg_id 1 QoS 0 would send once, with no PUBACK and no eventSleep the task 10 seconds
vTaskDelay blocks this FreeRTOS task for 10 s; the MQTT client's task keeps running. With a 120 s keep alive, a quiet client must send a ping, or after 180 s of silence the broker drops it. A publish every 10 s keeps it alive.
line 6 vTaskDelay(pdMS_TO_TICKS(10000)); blocked this task sleeps; other tasks run keep alive 120 s (esp-mqtt default) broker drops a client silent for 1.5 x 120 = 180 s PINGREQ sent only when there is nothing else to sendWi-Fi drops: retry and resend
If Wi-Fi drops mid-publish, no PUBACK comes and the copy stays in the outbox. The handler gets MQTT_EVENT_DISCONNECTED. The client retries every 10 s; once reconnected it resends the copy with the DUP flag set. A duplicate is possible, a loss is not.
event MQTT_EVENT_DISCONNECTED -> up = false retry reconnect every 10 s (reconnect_timeout_ms) resend PUBLISH 0x3A: DUP 1, same id 1, same "21.5" PUBACK then the outbox copy is removed QoS 1 at least once: maybe twice, never zero times
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01esp_mqtt_client_publish(client, TOPIC, buf, 0, 1, 0). What does the 0 in the fourth place mean?
The fourth argument is the payload length. The esp-mqtt docs say that if it is 0, the length is calculated from the payload string. The QoS is the fifth argument and retain the sixth.
02Topic "home/kitchen/temp" (17 bytes), payload "21.5", QoS 1. How long is the MQTT 3.1.1 PUBLISH packet?
2 bytes of fixed header, 2 + 17 for the topic, 2 for the packet id (QoS 1 only) and 4 for the payload: 27 bytes. At QoS 0 there is no packet id, so 25.
03The client publishes at QoS 1 and Wi-Fi drops before the PUBACK arrives. What happens to the message?
esp-mqtt keeps unacknowledged QoS 1 and 2 messages in its outbox and retransmits them, with DUP set, after a reconnect. The broker may then see the message twice: at least once, never zero times.
04The keep alive is 120 s. How long can the client stay completely silent before an MQTT 3.1.1 broker disconnects it?
The broker must disconnect a client that sends no packet within one and a half times the keep alive: 1.5 × 120 = 180 s. A client with nothing to publish sends a PINGREQ to stay connected.
05Why does the firmware turn 21.5 into the text "21.5" before publishing?
MQTT carries the payload as bytes and never looks inside. Choosing plain text (or JSON) means a phone app or dashboard can read it without knowing the ESP32's binary float layout. Text is not always shorter: here it is 4 bytes, the same as a float.
Glossary
- MQTT
- A small publish/subscribe protocol over TCP. Clients send messages to a broker under a topic; TCP port 1883, or 8883 with TLS.
- Broker
- The MQTT server in the middle. It receives every published message and forwards a copy to each client subscribed to that topic.
- Topic
- The name a message is published under, with levels split by slashes, such as home/kitchen/temp.
- Payload
- The bytes a message carries. MQTT never looks inside them; here they are the text "21.5".
- QoS 1
- Quality of service level 1, at least once: the receiver answers each PUBLISH with a PUBACK, and an unanswered message is sent again.
- Outbox
- esp-mqtt's store of QoS 1 and 2 messages that are not acknowledged yet, kept for resending.
- Keep alive
- The longest gap the client promises between packets. If nothing arrives for 1.5 times that, the broker disconnects it.
- Event handler
- A function the MQTT client calls when something happens, such as MQTT_EVENT_CONNECTED or MQTT_EVENT_PUBLISHED.
Notes and sources
- The card shows the work of the loop. The full program also sets up the client (esp_mqtt_client_init with the broker URI mqtt://192.168.1.20), registers an event handler that sets up = true on MQTT_EVENT_CONNECTED, and only publishes while up is true.
- The packet sizes follow MQTT 3.1.1, the esp-mqtt default (MQTT 5 can be switched on in menuconfig and adds a properties field). The packet id is chosen by the client; 1 is shown as an example.
- mqtt:// on port 1883 sends everything in clear text. A real device should use mqtts:// on port 8883 (TLS) with its own credentials; the lesson "Securing a device: TLS, secrets and secure boot" covers that.
- The Networking lesson "IoT: MQTT and constrained devices" explains topics, wildcards, QoS 2, retained messages and the last will in depth.
Quiz Unlocks after the last step.