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.
Theory in plain words
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
Use QoS 0 for frequent telemetry, QoS 1 for commands. Retained messages let new subscribers get the last value immediately.
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 1Quick quiz
1. MQTT wildcard "+" matches...
# matches all remaining levels.
2. QoS 1 means...
Acknowledged delivery, duplicates possible.