本篇博客主要记录 esp-idf 中的 ota 实现,相关 API 参考请查看 ESP HTTPS OTA。
1. esp_http_client_config_t 介绍
在 simple_ota 示例 中的 esp_http_client_config_t
如下:
esp_http_client_config_t config = {
.url = CONFIG_EXAMPLE_FIRMWARE_UPGRADE_URL,
.cert_pem = (char *)server_cert_pem_start,
.event_handler = _http_event_handler,
};
可以发现此 config 定义了以下参数:
url
设置放置待 ota.bin 文件的 HTTP URLcert_pem
设置 SSL 服务器证书event_handler
设置 HTTP 事件句柄
有时 ota 还配置了 .timeout_ms
来设置 ota 接收超时时间(idf 里默认为 5000 ms),config 中的 url
可以在 make menuconfig -> Example Configuration -> firmware upgrade url endpoint
中配置,Wi-Fi SSID 和 PWD 可以在 make menuconfig -> Example Connection Configuration
中配置。
注:可以将 config.skip_cert_common_name_check 设置为 true 来跳过 SSL 检查。
2. OTA 方法介绍
方法一:只需要在 menuconfig 里配置 url
,ca_cert_pem
等服务器信息后,使用 esp_https_ota()
这一条 API 即可进行 ota 升级。
注:在此条 API 成功执行后需要立即运行 esp_restart() 进行软件复位。
方法二:依次使用以下 API
esp_https_ota_begin(esp_https_ota_config_t *ota_config, esp_https_ota_handle_t *handle)
开始 HTTPS OTA 固件升级,初始化环境以及建立 HTTPS 连接esp_https_ota_perform(esp_https_ota_handle_thttps_ota_handle)
从 HTTP 数据流中读取数据并写进 OTA 中esp_https_ota_finish(esp_https_ota_handle_thttps_ota_handle)
清除 HTTPS OTA 固件升级并关闭 HTTPS 连接
注:在 esp_https_ota_finish(esp_https_ota_handle_thttps_ota_handle) 前可使用 esp_https_ota_is_complete_data_received(esp_https_ota_handle_thttps_ota_handle) 来检查是否收到全部数据。
3. CA 证书导入的方法
打开 CMakeLists.txt 可以看到其中有以下内容:
# Embed the server root certificate into the final binary
idf_build_get_property(project_dir PROJECT_DIR)
idf_component_register(SRCS "simple_ota_example.c"
INCLUDE_DIRS "."
EMBED_TXTFILES ${
project_dir}/server_certs/ca_cert.pem)
此时将 CA 证书放入 ${project_dir}/server_certs/ca_cert.pem
目录下即可。然后使用以下代码来导入使用 CA 证书:
extern const uint8_t server_cert_pem_start[] asm("_binary_ca_cert_pem_start");
extern const uint8_t server_cert_pem_end[] asm("_binary_ca_cert_pem_end");
void app_main(void)
{
...
esp_http_client_config_t config = {
.url = CONFIG_EXAMPLE_FIRMWARE_UPGRADE_URL,
.cert_pem = (char *)server_cert_pem_start,
.event_handler = _http_event_handler,
};
...
}