Home / Learn Chip Programming / HTTP Server, REST Client and MQTT on ESP32

HTTP Server, REST Client and MQTT on ESP32

Serve a web page from the chip and send data to the cloud.

In shortServe a web page from the chip and send data to the cloud.

Theory in plain words

MQTTESP32 publishes home/temp = 25.3Broker (Mosquitto)Dashboard subscribed to home/#Broker forwards message
MQTT

What it is

ESP-IDF includes an HTTP server (esp_http_server), HTTP/HTTPS client and an MQTT client. MQTT is a lightweight publish/subscribe protocol with topics and QoS levels.

Why we use it

Dashboards, Home Assistant, AWS IoT and Node-RED all speak MQTT or REST. A tiny web server gives configuration pages with no app.

How it works

Register URI handlers (GET /status returns JSON). For MQTT: connect to broker, publish to topic home/livingroom/temp, subscribe to commands.

Where it is used

  • Smart home sensors
  • JSON REST API on the device
  • Remote control with MQTT

MQTT topic and QoS lab

Topic wildcards and delivery guaranteesTry it Yourself

Use QoS 0 for frequent telemetry, QoS 1 for commands. Retained messages let new subscribers get the last value immediately.

HTTP JSON endpoint and MQTT publish
static esp_err_t status_get(httpd_req_t *r) {
    char buf[96]; snprintf(buf, sizeof buf, "{\"temp\":%.1f,\"uptime\":%lu}", read_temp(), (unsigned long)(esp_timer_get_time() / 1000000));
    httpd_resp_set_type(r, "application/json"); return httpd_resp_send(r, buf, HTTPD_RESP_USE_STRLEN);
}
httpd_uri_t u = { .uri = "/status", .method = HTTP_GET, .handler = status_get };
httpd_register_uri_handler(server, &u);

esp_mqtt_client_handle_t c = esp_mqtt_client_init(&(esp_mqtt_client_config_t){ .broker.address.uri = "mqtt://192.168.1.10" });
esp_mqtt_client_start(c);
esp_mqtt_client_publish(c, "home/livingroom/temp", "25.3", 0, 1, 1);   // qos 1, retain 1
Careful:Never expose a device web server directly to the Internet without authentication and TLS. Use MQTT over TLS (port 8883) with a username and password.

Quick quiz

1. MQTT wildcard "+" matches...

2. QoS 1 means...