ENع
→MQTT from an ESP32
الدرس 49 · Connectivity and the capstone node

Publishing sensor data with MQTT

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

12 دقيقة10 خطوات5 أسئلةAdvanced
عن هذا الدرس

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.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 49 · تفاعلي
01 / 10

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
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. 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
  2. Connect 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 it
  3. Read 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 works
  4. Turn 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 it
  5. Publish 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)
  6. 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 yet
  7. The 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 go
  8. PUBACK: 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 event
  9. Sleep 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 send
  10. Wi-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

اختبار يتاح بعد الخطوة الأخيرة.