ESP32 快速入門(十三):OTA 示例代碼簡析

本篇博客主要記錄 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 URL
  • cert_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 裏配置 urlca_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,
    };
    ...
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章