如何通过 HTTP POST 执行 ESP32 固件 OTA 升级

本文展示如何在跑 ESP-IDF HTTP 服务器的 ESP32 上实现固件 OTA(over-the-air)升级端点:客户端用简单 POST 请求上传原始 .bin 固件镜像。还讲了两个耗掉我大量调试时间的坑:chunked 传输编码和静默失败的重启任务。

概览

流程分三部分:

  1. 设备侧: HTTP handler 接收二进制 body,用 esp_ota_begin()/esp_ota_write()/esp_ota_end() 写进非活动 OTA 分区,设为启动分区并重启。
  2. 客户端侧: 任何 HTTP 客户端(curl、Python requests、CI 任务)带正确 Content-Length 头 POST .bin 文件。
  3. 重启: 响应发出后,设备重启进新固件。

设备侧:HTTP handler

注册一个 POST URI handler,如 /api/firmware/update。handler 必须用 httpd_req_recv() 循环读满 req->content_len 字节,因为即使总长度提前已知,body 也是分块到达的:

HTTPHandlersFirmwareUpdate.cpp
#include <esp_http_server.h>
#include <esp_log.h>
#include <esp_ota_ops.h>
#include <esp_system.h>
#include <esp_timer.h>
#include <cJSON.h>

static const char *TAG = "fw_update";

static void reboot_after_update(void *) {
    esp_restart();
}

static esp_err_t firmware_update_handler(httpd_req_t *req) {
    if (req->content_len <= 0) {
        httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Missing Content-Length");
        return ESP_OK;
    }

    const esp_partition_t *update_partition = esp_ota_get_next_update_partition(nullptr);
    if (!update_partition) {
        httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "No OTA partition");
        return ESP_OK;
    }

    esp_ota_handle_t ota_handle;
    esp_err_t err = esp_ota_begin(update_partition, req->content_len, &ota_handle);
    if (err != ESP_OK) {
        httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "esp_ota_begin failed");
        return ESP_OK;
    }

    // 分块接收 body 直到读满 content_len 字节
    int remaining = req->content_len;
    char buf[4096];
    while (remaining > 0) {
        int to_read = remaining < (int)sizeof(buf) ? remaining : (int)sizeof(buf);
        int received = httpd_req_recv(req, buf, to_read);
        if (received <= 0) {
            if (received == HTTPD_SOCK_ERR_TIMEOUT) continue; // 超时重试
            esp_ota_abort(ota_handle);
            httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Receive failed");
            return ESP_OK;
        }
        err = esp_ota_write(ota_handle, buf, received);
        if (err != ESP_OK) {
            esp_ota_abort(ota_handle);
            httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "OTA write failed");
            return ESP_OK;
        }
        remaining -= received;
    }

    if (esp_ota_end(ota_handle) != ESP_OK ||
        esp_ota_set_boot_partition(update_partition) != ESP_OK) {
        httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "OTA finalize failed");
        return ESP_OK;
    }

    // 重启*之前*先发 JSON 响应
    httpd_resp_set_type(req, "application/json");
    char response[160];
    snprintf(response, sizeof(response),
             "{\"status\":\"success\",\"partition\":\"%s\",\"written\":%d}",
             update_partition->label, req->content_len);
    httpd_resp_sendstr(req, response);

    // 响应冲刷*之后*再调度重启(见坑 #2)
    const esp_timer_create_args_t timer_args = {
        .callback = reboot_after_update,
        .arg = nullptr,
        .dispatch_method = ESP_TIMER_TASK,
        .name = "fw_reboot",
        .skip_unhandled_events = false,
    };
    esp_timer_handle_t reboot_timer = nullptr;
    if (esp_timer_create(&timer_args, &reboot_timer) == ESP_OK) {
        esp_timer_start_once(reboot_timer, 1200 * 1000); // 1.2 秒
    } else {
        esp_restart(); // 兜底:立即重启
    }
    return ESP_OK;
}

在服务器初始化里注册:

HTTPServer.cpp
static const httpd_uri_t firmware_update_uri = {
    .uri      = "/api/firmware/update",
    .method   = HTTP_POST,
    .handler  = firmware_update_handler,
    .user_ctx = nullptr,
};
httpd_register_uri_handler(server, &firmware_update_uri);

客户端侧

curl

flash.sh
curl -X POST \
  --data-binary "@build/MyFirmware.bin" \
  -H "Content-Type: application/octet-stream" \
  http://10.0.0.42/api/firmware/update

Python

firmware_updater.py
#!/usr/bin/env python3
import os
import sys
import requests

host, bin_path = sys.argv[1], sys.argv[2]
size = os.path.getsize(bin_path)

# 重要:直接传文件对象,requests 才会发固定
# Content-Length。不要传生成器——那会触发 chunked
# 传输编码,ESP-IDF HTTP 服务器这里不接受。
with open(bin_path, "rb") as f:
    r = requests.post(
        f"http://{host}/api/firmware/update",
        data=f,
        headers={
            "Content-Type": "application/octet-stream",
            "Content-Length": str(size),
        },
        timeout=120,
    )
print(r.status_code, r.text)

升级成功返回:

output.txt
200 {"status":"success","partition":"ota_1","written":1462400}

坑 1:chunked 传输编码 → HTTP 400

如果客户端发 Transfer-Encoding: chunked 而不是固定 Content-Length,ESP-IDF HTTP 服务器以 400 Bad request syntax 拒绝——req->content_len 对 chunked body 不可用。

Python 里把生成器(或任何无长度的可迭代对象)传给 requests.post() 的 data= 就容易踩上。像上面那样直接传文件对象,requests 就会发正常的 Content-Length 请求。

坑 2:用于重启的 xTaskCreate 可能静默失败

常见模式是起一个任务,延时后调 esp_restart():

do-not-do-this.cpp
// 反面教材:堆碎片时会静默失败
(void)xTaskCreate(reboot_task, "fw_reboot", 2048, nullptr, 5, nullptr);

长时间运行的设备上,内部堆可能碎到没有能容纳新任务栈的连续块。xTaskCreate 于是失败——而返回值被忽略,设备报告 OTA 成功、设好启动分区,却永不重启,无限期继续跑旧固件。升级后查 uptime 验证重启!

esp_timer 在已存在的 timer 任务里跑回调,不需要分配新栈——堆碎得再厉害也能用。

验证清单

  • 响应包含 HTTP 200 和 JSON status: success、目标分区和字节数。
  • 设备在响应后约 1 秒自行重启(uptime 归零)。
  • 重启后应用健康(我的场景:MQTT 重连、节点注册表完好)。

说明

  • 示例中端点无认证。任何不可信网络上都要保护它——至少用 HTTP digest auth(httpd 可经自定义 handler 检查做 basic auth),或只在管理 VLAN 上暴露。
  • 设备上要 HTTPS(TLS)就把 httpd_start() 换成 httpd_ssl_start()——handler 代码完全一样。
  • esp_ota_end() 会校验镜像;中断的上传会校验失败(ESP_ERR_OTA_VALIDATE_FAILED),设备继续跑旧固件——重试是安全的。

按类别查看类似文章: ESP32 嵌入式