Connect
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.
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.
Publish one reading
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.
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.
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.
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.
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.
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.
Stay connected
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.
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.
What happens
;; step 1/10 · node 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
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.