scripts: P4-Nano probe app and C6 esp-hosted OTA tools
p4-probe identifies the P4 and its C6 over esp-hosted SDIO. c6-ota holds the C6 coprocessor build and the two host updaters (3.1 and the 2.x one that moved the factory C6 firmware to esp-hosted 3.1). Also the pending graphify output. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
edf35e9c71
commit
ba8e160aee
104 files changed
+8674
-204
No files matched your search
@@ -0,0 +1,6 @@
|
||||
build/
|
||||
sdkconfig
|
||||
sdkconfig.old
|
||||
managed_components/
|
||||
dependencies.lock
|
||||
*.bin
|
||||
@@ -0,0 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
cmake_minimum_required(VERSION 3.5)
|
||||
|
||||
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
|
||||
project(eh_cp_ota_coprocessor_ota)
|
||||
@@ -0,0 +1,90 @@
|
||||
# ota / coprocessor_ota — Coprocessor
|
||||
|
||||
Pushes a new CP firmware image from the host through the OTA
|
||||
begin / write / end / activate RPC chain. The host can source the image
|
||||
from one of three places — HTTPS, an on-host LittleFS partition, or a
|
||||
dedicated raw flash partition — selected at build time.
|
||||
|
||||
## Supported Platforms and Transports
|
||||
|
||||
### Supported Coprocessors
|
||||
|
||||
| Coprocessor | ESP32 | ESP32-C Series | ESP32-S2/S3 | ESP32-S31 |
|
||||
| :----------: | :---: | :------------: | :---------: | :-------: |
|
||||
| Support | Yes | Yes | Yes | Yes ¹ |
|
||||
|
||||
¹ ESP32-S31: preview target, 2.4 GHz only, no SDIO. See [ESP32-S31 test board](https://github.com/espressif/esp-hosted/blob/master/docs/getting-started-mcu.md#esp32-s31-test-board-on-the-esp32-p4-function-ev-board).
|
||||
|
||||
### Supported Host Devices
|
||||
|
||||
| Host Device | ESP32-P4 | ESP32-H2 | Other MCUs | Linux |
|
||||
| :---------: | :------: | :------: | :--------: | :---: |
|
||||
| Support | Yes | Yes | [Yes](https://github.com/espressif/esp-hosted/blob/master/docs/getting-started-mcu.md) | [Yes](https://github.com/espressif/esp-hosted/blob/master/docs/getting-started-linux.md) |
|
||||
|
||||
### Supported Connection buses
|
||||
|
||||
| Connection bus | SDIO | SPI Full-Duplex | SPI Half-Duplex | UART |
|
||||
| :------------- | :--: | :-------------: | :-------------: | :--: |
|
||||
| Linux host | Yes | Yes | No | No |
|
||||
| MCU host | Yes | Yes | Yes | Yes |
|
||||
|
||||
## Scenario
|
||||
|
||||
The host streams new co-processor firmware over the control path using the four-call OTA RPC chain — `begin` → `write` (looped) → `end` → `activate`. (`activate` is a distinct RPC, needed on CP firmware v2.6.0+.) API names below are the example's compat surface (`esp_hosted_slave_ota_*`); the native equivalents are `eh_host_cp_ota_*`.
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant App as Host app
|
||||
participant CP as Co-processor
|
||||
participant SRC as Firmware source (HTTPS / LittleFS / partition)
|
||||
App->>CP: esp_hosted_slave_ota_begin() (RPC)
|
||||
loop firmware chunks
|
||||
App->>SRC: fetch chunk
|
||||
App->>CP: esp_hosted_slave_ota_write(chunk) (RPC)
|
||||
end
|
||||
App->>CP: esp_hosted_slave_ota_end() (RPC)
|
||||
App->>CP: esp_hosted_slave_ota_activate() (RPC)
|
||||
CP->>CP: set boot partition
|
||||
CP-->>App: result
|
||||
Note over CP: reboot into new firmware
|
||||
```
|
||||
|
||||
OTA runs on the co-processor's **System** feature (OTA / heartbeat / FW version), pre-enabled in `cp/sdkconfig.defaults` — you only select the transport:
|
||||
|
||||
```bash
|
||||
cd examples/ota/coprocessor_ota/cp
|
||||
idf.py set-target esp32c6
|
||||
idf.py menuconfig
|
||||
```
|
||||
|
||||
```text
|
||||
Component config
|
||||
└── ESP-Hosted
|
||||
└── Configure coprocessor
|
||||
└── CP transport
|
||||
├── Communication bus (co-processor <== bus ==> host)
|
||||
│ ├── ( ) SPI Full Duplex
|
||||
│ ├── (X) SDIO <── default
|
||||
│ ├── ( ) SPI Half Duplex ← MCU host only
|
||||
│ └── ( ) UART ← MCU host only
|
||||
└── SDIO Configuration ← clock, GPIOs, checksum (defaults OK)
|
||||
```
|
||||
|
||||
Each bus has its own settings submenu (pins, clock, checksum) — defaults are fine for bring-up.
|
||||
|
||||
CP dependency config is **pre-set in `cp/sdkconfig.defaults`** (do not remove):
|
||||
|
||||
```text
|
||||
CONFIG_ESP_HOSTED_CP_FEAT_WIFI=y # Wi-Fi — HTTPS OTA download path
|
||||
CONFIG_BT_ENABLED=n
|
||||
```
|
||||
|
||||
The System feature (OTA, heartbeat, FW version) is always enabled on the co-processor, so it needs no config.
|
||||
|
||||
Then flash and monitor:
|
||||
|
||||
```bash
|
||||
idf.py -p <cp_usb_serial_port> flash monitor
|
||||
```
|
||||
|
||||
<!-- generated from ../README.md — edit that file, not this one -->
|
||||
@@ -0,0 +1,4 @@
|
||||
idf_component_register(SRCS "main.c"
|
||||
INCLUDE_DIRS "."
|
||||
REQUIRES esp_hosted
|
||||
PRIV_REQUIRES nvs_flash esp_wifi)
|
||||
@@ -0,0 +1,5 @@
|
||||
dependencies:
|
||||
espressif/esp_hosted:
|
||||
version: '*'
|
||||
idf:
|
||||
version: '>=5.5'
|
||||
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2021-2025 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
#include "esp_log.h"
|
||||
#include "esp_event.h"
|
||||
#include "nvs_flash.h"
|
||||
|
||||
#include "esp_check.h"
|
||||
|
||||
static const char *TAG = "wifi_mcu_example";
|
||||
|
||||
void app_main(void)
|
||||
{
|
||||
ESP_LOGI(TAG, "ESP-Hosted MCU WiFi Example Starting...");
|
||||
|
||||
/* Initialize NVS */
|
||||
esp_err_t ret = nvs_flash_init();
|
||||
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
|
||||
ESP_ERROR_CHECK(nvs_flash_erase());
|
||||
ret = nvs_flash_init();
|
||||
}
|
||||
ESP_ERROR_CHECK(ret);
|
||||
|
||||
/* create default event loop */
|
||||
ESP_ERROR_CHECK(esp_event_loop_create_default());
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
# ESP-Hosted shared partition table — 2 MB flash, dual OTA (960 KB per slot)
|
||||
# Name, Type, SubType, Offset, Size
|
||||
nvs, data, nvs, 0x9000, 0x4000
|
||||
otadata, data, ota, 0xd000, 0x2000
|
||||
phy_init, data, phy, 0xf000, 0x1000
|
||||
ota_0, app, ota_0, 0x10000, 0xF0000
|
||||
ota_1, app, ota_1, 0x100000, 0xF0000
|
||||
|
@@ -0,0 +1,7 @@
|
||||
# ESP-Hosted shared partition table — 4 MB flash, dual OTA (1.75 MB per slot)
|
||||
# Name, Type, SubType, Offset, Size
|
||||
nvs, data, nvs, 0x9000, 0x4000
|
||||
otadata, data, ota, 0xd000, 0x2000
|
||||
phy_init, data, phy, 0xf000, 0x1000
|
||||
ota_0, app, ota_0, 0x10000, 0x1C0000
|
||||
ota_1, app, ota_1, 0x1D0000, 0x1C0000
|
||||
|
@@ -0,0 +1,25 @@
|
||||
# ── Role: COPROCESSOR ────────────────────────────────────────────────
|
||||
# ESP-Hosted coprocessor firmware (works with both MCU and Linux hosts
|
||||
# via the unified MCU RPC v1 wire).
|
||||
CONFIG_ESP_HOSTED=y
|
||||
CONFIG_ESP_HOSTED_CP=y
|
||||
CONFIG_ESP_HOSTED_CP_FOR_MCU=y
|
||||
CONFIG_ESP_HOSTED_CP_RPC_V2=y
|
||||
|
||||
#Disable enterprise support by default
|
||||
CONFIG_ESP_WIFI_ENTERPRISE_SUPPORT=n
|
||||
|
||||
# BT Configuration
|
||||
CONFIG_BT_ENABLED=n
|
||||
#CONFIG_BT_CONTROLLER_ONLY=y
|
||||
|
||||
# OTA
|
||||
CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y
|
||||
CONFIG_PARTITION_TABLE_CUSTOM=y
|
||||
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions_eh_cp_ota_4m.csv"
|
||||
|
||||
# OS
|
||||
CONFIG_FREERTOS_HZ=1000
|
||||
CONFIG_ESP_WIFI_NVS_ENABLED=y
|
||||
|
||||
CONFIG_ESP_HOSTED_CP_FEAT_WIFI=y
|
||||
@@ -0,0 +1,50 @@
|
||||
CONFIG_ESP32_DEFAULT_CPU_FREQ_240=y
|
||||
|
||||
# BT Configuration
|
||||
CONFIG_BT_ENABLED=n
|
||||
CONFIG_BT_CONTROLLER_ONLY=y
|
||||
CONFIG_BT_BLUEDROID_ENABLED=
|
||||
CONFIG_BTDM_CONTROLLER_MODE_BTDM=y
|
||||
CONFIG_BTDM_CONTROLLER_HCI_MODE_VHCI=y
|
||||
CONFIG_BTDM_CTRL_AUTO_LATENCY=y
|
||||
CONFIG_BTDM_CONTROLLER_MODEM_SLEEP=y
|
||||
CONFIG_BTDM_CTRL_MODEM_SLEEP=y
|
||||
|
||||
# BT over UART
|
||||
#CONFIG_BTDM_CONTROLLER_HCI_MODE_UART_H4=y
|
||||
#CONFIG_BTDM_CTRL_HCI_MODE_UART_H4=y
|
||||
#CONFIG_BT_HCI_UART_NO=1
|
||||
#CONFIG_BT_HCI_UART_BAUDRATE=921600
|
||||
|
||||
#CO-EX config
|
||||
CONFIG_FREERTOS_UNICORE=n
|
||||
CONFIG_ESP32_WIFI_TASK_PINNED_TO_CORE_1=y
|
||||
CONFIG_BTDM_CONTROLLER_PINNED_TO_CORE=0
|
||||
CONFIG_BTDM_CTRL_PINNED_TO_CORE=0
|
||||
CONFIG_BTDM_CTRL_PINNED_TO_CORE_0=y
|
||||
|
||||
CONFIG_ESP32_WIFI_STATIC_RX_BUFFER_NUM=16
|
||||
CONFIG_ESP32_WIFI_DYNAMIC_RX_BUFFER_NUM=32
|
||||
CONFIG_ESP32_WIFI_DYNAMIC_TX_BUFFER=y
|
||||
CONFIG_ESP32_WIFI_DYNAMIC_TX_BUFFER_NUM=64
|
||||
|
||||
# OTA
|
||||
CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y
|
||||
|
||||
# partitions
|
||||
CONFIG_PARTITION_TABLE_CUSTOM=y
|
||||
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions_eh_cp_ota_4m.csv"
|
||||
|
||||
# iram optimization
|
||||
CONFIG_ESP_WIFI_RX_IRAM_OPT=y
|
||||
CONFIG_ESP_WIFI_IRAM_OPT=y
|
||||
CONFIG_FREERTOS_PLACE_FUNCTIONS_INTO_FLASH=y
|
||||
CONFIG_RINGBUF_PLACE_FUNCTIONS_INTO_FLASH=y
|
||||
CONFIG_ESP_SYSTEM_ESP32_SRAM1_REGION_AS_IRAM=y
|
||||
|
||||
CONFIG_COMPILER_OPTIMIZATION_PERF=y
|
||||
#CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS=y
|
||||
|
||||
# OS
|
||||
CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_SIZE=y
|
||||
CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_PERF=n
|
||||
@@ -0,0 +1,87 @@
|
||||
# 1. CPU
|
||||
#--------
|
||||
CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_120=y
|
||||
|
||||
# 2. BT Configuration
|
||||
#---------------------
|
||||
CONFIG_BT_ENABLED=n
|
||||
CONFIG_BT_CONTROLLER_ONLY=y
|
||||
CONFIG_BT_LE_SLEEP_ENABLE=y
|
||||
|
||||
# 2.1 BLE over SPI/SDIO
|
||||
#-----------------------
|
||||
CONFIG_BT_LE_HCI_INTERFACE_USE_RAM=y
|
||||
|
||||
# 2.2 BLE over UART
|
||||
#-------------------
|
||||
#UART pins, Enable below config, delete sdkconfig and rebuild
|
||||
#CONFIG_BT_LE_HCI_INTERFACE_USE_UART=y
|
||||
#CONFIG_BT_LE_HCI_UART_FLOWCTRL=n
|
||||
#CONFIG_BT_LE_HCI_UART_TX_PIN=5
|
||||
#CONFIG_BT_LE_HCI_UART_RX_PIN=18
|
||||
|
||||
|
||||
# 3. Partition Table
|
||||
#--------------------
|
||||
CONFIG_PARTITION_TABLE_CUSTOM=y
|
||||
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions_eh_cp_ota_2m.csv"
|
||||
|
||||
# 4. Mempool
|
||||
#------------
|
||||
CONFIG_ESP_CACHE_MALLOC=y
|
||||
|
||||
|
||||
## 5 LWIP split
|
||||
##---------------
|
||||
#
|
||||
#CONFIG_ESP_HOSTED_CP_FEAT_NW_SPLIT=n
|
||||
|
||||
|
||||
# 6. Wifi config
|
||||
#----------------
|
||||
|
||||
CONFIG_ESP_WIFI_STATIC_RX_BUFFER_NUM=8
|
||||
CONFIG_ESP_WIFI_DYNAMIC_RX_BUFFER_NUM=16
|
||||
CONFIG_ESP_WIFI_DYNAMIC_TX_BUFFER_NUM=16
|
||||
CONFIG_ESP_WIFI_AMPDU_TX_ENABLED=y
|
||||
CONFIG_ESP_WIFI_TX_BA_WIN=8
|
||||
#CONFIG_ESP_WIFI_TX_BA_WIN=16
|
||||
CONFIG_ESP_WIFI_AMPDU_RX_ENABLED=y
|
||||
CONFIG_ESP_WIFI_RX_BA_WIN=8
|
||||
#CONFIG_ESP_WIFI_RX_BA_WIN=14
|
||||
|
||||
CONFIG_ESP_WIFI_RX_IRAM_OPT=y
|
||||
CONFIG_ESP_WIFI_IRAM_OPT=y
|
||||
|
||||
|
||||
# 7. Optimizations
|
||||
#-------------------
|
||||
CONFIG_COMPILER_OPTIMIZATION_SIZE=y
|
||||
#CONFIG_COMPILER_OPTIMIZATION_PERF=y
|
||||
|
||||
|
||||
# 8. Stats
|
||||
#-----------
|
||||
#CONFIG_ESP_PKT_STATS=y
|
||||
|
||||
|
||||
# 9. Mem optimizations
|
||||
#---------------------
|
||||
CONFIG_FREERTOS_PLACE_FUNCTIONS_INTO_FLASH=y
|
||||
CONFIG_ESP32_DEFAULT_CPU_FREQ_120=y
|
||||
CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ=120
|
||||
CONFIG_FREERTOS_UNICORE=y
|
||||
|
||||
#10. C2 specific opts
|
||||
#---------------------
|
||||
CONFIG_ESPTOOLPY_FLASHSIZE_4MB=n
|
||||
CONFIG_ESPTOOLPY_FLASHSIZE_2MB=y
|
||||
|
||||
CONFIG_ESP_DEFAULT_TASK_STACK_SIZE=2048
|
||||
|
||||
#11. C2 26 MHz XTAL chips
|
||||
# C2 generally in MP has 26MHz.
|
||||
# If your C2 has 40MHz, just comment below lines
|
||||
#---------------------------------
|
||||
CONFIG_SOC_XTAL_SUPPORT_26M=y
|
||||
CONFIG_XTAL_FREQ_26=y
|
||||
@@ -0,0 +1,104 @@
|
||||
# 1. CPU
|
||||
#--------
|
||||
CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_160=y
|
||||
|
||||
# 2. BT Configuration
|
||||
#---------------------
|
||||
CONFIG_BT_ENABLED=n
|
||||
CONFIG_BT_CONTROLLER_ONLY=y
|
||||
CONFIG_BT_BLUEDROID_ENABLED=
|
||||
CONFIG_BT_LE_SLEEP_ENABLE=y
|
||||
|
||||
# 3.1 BLE over SPI/SDIO
|
||||
#-----------------------
|
||||
CONFIG_BT_LE_HCI_INTERFACE_USE_RAM=y
|
||||
|
||||
# 3.2 BLE over UART
|
||||
#-------------------
|
||||
# Enable below config, delete sdkconfig, build/ and rebuild
|
||||
# CONFIG_BT_LE_HCI_INTERFACE_USE_UART=y
|
||||
# CONFIG_BT_LE_HCI_UART_TX_PIN=5
|
||||
# CONFIG_BT_LE_HCI_UART_RX_PIN=18
|
||||
# CONFIG_BT_LE_HCI_UART_FLOWCTRL=n
|
||||
# #CONFIG_BT_LE_HCI_UART_RTS_PIN=19
|
||||
# #CONFIG_BT_LE_HCI_UART_CTS_PIN=8
|
||||
|
||||
|
||||
# 4. Partition Table
|
||||
#--------------------
|
||||
CONFIG_PARTITION_TABLE_CUSTOM=y
|
||||
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions_eh_cp_ota_4m.csv"
|
||||
|
||||
# 5. Mempool
|
||||
#------------
|
||||
CONFIG_ESP_CACHE_MALLOC=y
|
||||
|
||||
|
||||
# # 6.1 LWIP split
|
||||
# #---------------
|
||||
|
||||
# CONFIG_ESP_HOSTED_CP_FEAT_NW_SPLIT=y
|
||||
# CONFIG_LWIP_TCP_LOCAL_PORT_RANGE_START=61440
|
||||
# CONFIG_LWIP_TCP_LOCAL_PORT_RANGE_END=65535
|
||||
# CONFIG_LWIP_UDP_LOCAL_PORT_RANGE_START=61440
|
||||
# CONFIG_LWIP_UDP_LOCAL_PORT_RANGE_END=65535
|
||||
|
||||
|
||||
# # 6.2 LWIP split examples
|
||||
# #-------------------------
|
||||
|
||||
|
||||
# 7. Transport config
|
||||
#---------------------
|
||||
# ESP_HOSTED_TRANSPORT_CP_SDIO_NSEND_PSAMPLE=y
|
||||
# ESP_HOSTED_TRANSPORT_CP_SDIO_DEFAULT_SPEED=y
|
||||
# ESP_HOSTED_TRANSPORT_CP_SDIO_STREAMING_MODE=n
|
||||
|
||||
# For SPI Full duplex C6 on ESP32-P4-Function-EV-Board, please uncomment below
|
||||
#CONFIG_C6_SPI_WITH_P4=y
|
||||
|
||||
|
||||
# 8. Wifi config
|
||||
#----------------
|
||||
|
||||
CONFIG_ESP_WIFI_STATIC_RX_BUFFER_NUM=10
|
||||
CONFIG_ESP_WIFI_DYNAMIC_RX_BUFFER_NUM=32
|
||||
CONFIG_ESP_WIFI_DYNAMIC_TX_BUFFER_NUM=32
|
||||
CONFIG_ESP_WIFI_AMPDU_TX_ENABLED=y
|
||||
CONFIG_ESP_WIFI_TX_BA_WIN=16
|
||||
CONFIG_ESP_WIFI_AMPDU_RX_ENABLED=y
|
||||
CONFIG_ESP_WIFI_RX_BA_WIN=16
|
||||
|
||||
CONFIG_ESP_WIFI_RX_IRAM_OPT=y
|
||||
CONFIG_ESP_WIFI_IRAM_OPT=y
|
||||
|
||||
# # 9. LWIP config
|
||||
# #----------------
|
||||
# CONFIG_LWIP_TCP_SND_BUF_DEFAULT=11520
|
||||
# CONFIG_LWIP_TCP_WND_DEFAULT=11520
|
||||
# CONFIG_LWIP_TCP_RECVMBOX_SIZE=16
|
||||
# CONFIG_LWIP_UDP_RECVMBOX_SIZE=16
|
||||
# CONFIG_LWIP_TCPIP_RECVMBOX_SIZE=32
|
||||
# CONFIG_LWIP_TCP_SACK_OUT=y
|
||||
# CONFIG_LWIP_TCPIP_CORE_LOCKING=y
|
||||
# CONFIG_LWIP_TCPIP_CORE_LOCKING_INPUT=y
|
||||
|
||||
|
||||
# 10. Optimizations
|
||||
#-------------------
|
||||
CONFIG_COMPILER_OPTIMIZATION_PERF=y
|
||||
CONFIG_SPI_MASTER_ISR_IN_IRAM=n
|
||||
|
||||
|
||||
# 11. Stats
|
||||
#-----------
|
||||
#CONFIG_ESP_HOSTED_FUNCTION_PROFILING=y
|
||||
#CONFIG_ESP_PKT_STATS=y
|
||||
|
||||
## 12. Priorities
|
||||
#----------------
|
||||
|
||||
|
||||
# 13. Mem optimizations
|
||||
#---------------------
|
||||
CONFIG_FREERTOS_PLACE_FUNCTIONS_INTO_FLASH=y
|
||||
@@ -0,0 +1,102 @@
|
||||
# 1. CPU
|
||||
#--------
|
||||
CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_240=y
|
||||
|
||||
# 2. BT Configuration
|
||||
#---------------------
|
||||
CONFIG_BT_ENABLED=n
|
||||
CONFIG_BT_CONTROLLER_ONLY=y
|
||||
CONFIG_BT_BLUEDROID_ENABLED=
|
||||
CONFIG_BT_LE_SLEEP_ENABLE=y
|
||||
|
||||
# 3.1 BLE over SPI/SDIO
|
||||
#-----------------------
|
||||
CONFIG_BT_LE_HCI_INTERFACE_USE_RAM=y
|
||||
|
||||
# 3.2 BLE over UART
|
||||
#-------------------
|
||||
# Enable below config, delete sdkconfig, build/ and rebuild
|
||||
# CONFIG_BT_LE_HCI_INTERFACE_USE_UART=y
|
||||
# CONFIG_BT_LE_HCI_UART_TX_PIN=5
|
||||
# CONFIG_BT_LE_HCI_UART_RX_PIN=18
|
||||
# CONFIG_BT_LE_HCI_UART_FLOWCTRL=n
|
||||
# #CONFIG_BT_LE_HCI_UART_RTS_PIN=19
|
||||
# #CONFIG_BT_LE_HCI_UART_CTS_PIN=8
|
||||
|
||||
|
||||
# 4. Partition Table
|
||||
#--------------------
|
||||
CONFIG_PARTITION_TABLE_CUSTOM=y
|
||||
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions_eh_cp_ota_4m.csv"
|
||||
|
||||
# 5. Mempool
|
||||
#------------
|
||||
CONFIG_ESP_CACHE_MALLOC=y
|
||||
|
||||
|
||||
## 6.1 LWIP split
|
||||
##---------------
|
||||
#
|
||||
#CONFIG_ESP_HOSTED_CP_FEAT_NW_SPLIT=y
|
||||
#CONFIG_LWIP_TCP_LOCAL_PORT_RANGE_START=61440
|
||||
#CONFIG_LWIP_TCP_LOCAL_PORT_RANGE_END=65535
|
||||
#CONFIG_LWIP_UDP_LOCAL_PORT_RANGE_START=61440
|
||||
#CONFIG_LWIP_UDP_LOCAL_PORT_RANGE_END=65535
|
||||
#
|
||||
#
|
||||
## 6.2 LWIP split examples
|
||||
##-------------------------
|
||||
|
||||
|
||||
# 7. Transport config
|
||||
#---------------------
|
||||
# ESP_HOSTED_TRANSPORT_CP_SDIO_NSEND_PSAMPLE=y
|
||||
# ESP_HOSTED_TRANSPORT_CP_SDIO_DEFAULT_SPEED=y
|
||||
# ESP_HOSTED_TRANSPORT_CP_SDIO_STREAMING_MODE=n
|
||||
|
||||
# For SPI Full duplex C6 on ESP32-P4-Function-EV-Board, please uncomment below
|
||||
#CONFIG_C6_SPI_WITH_P4=y
|
||||
|
||||
|
||||
# 8. Wifi config
|
||||
#----------------
|
||||
|
||||
CONFIG_ESP_WIFI_STATIC_RX_BUFFER_NUM=10
|
||||
CONFIG_ESP_WIFI_DYNAMIC_RX_BUFFER_NUM=32
|
||||
CONFIG_ESP_WIFI_DYNAMIC_TX_BUFFER_NUM=32
|
||||
CONFIG_ESP_WIFI_AMPDU_TX_ENABLED=y
|
||||
CONFIG_ESP_WIFI_TX_BA_WIN=16
|
||||
CONFIG_ESP_WIFI_AMPDU_RX_ENABLED=y
|
||||
CONFIG_ESP_WIFI_RX_BA_WIN=16
|
||||
|
||||
CONFIG_ESP_WIFI_RX_IRAM_OPT=y
|
||||
CONFIG_ESP_WIFI_IRAM_OPT=y
|
||||
|
||||
## 9. LWIP config
|
||||
##----------------
|
||||
#CONFIG_LWIP_TCP_SND_BUF_DEFAULT=11520
|
||||
#CONFIG_LWIP_TCP_WND_DEFAULT=11520
|
||||
#CONFIG_LWIP_TCP_RECVMBOX_SIZE=16
|
||||
#CONFIG_LWIP_UDP_RECVMBOX_SIZE=16
|
||||
#CONFIG_LWIP_TCPIP_RECVMBOX_SIZE=32
|
||||
#CONFIG_LWIP_TCP_SACK_OUT=y
|
||||
#CONFIG_LWIP_TCPIP_CORE_LOCKING=y
|
||||
#CONFIG_LWIP_TCPIP_CORE_LOCKING_INPUT=y
|
||||
|
||||
# 10. Optimizations
|
||||
#-------------------
|
||||
CONFIG_COMPILER_OPTIMIZATION_PERF=y
|
||||
|
||||
|
||||
# 11. Stats
|
||||
#-----------
|
||||
#CONFIG_ESP_HOSTED_FUNCTION_PROFILING=y
|
||||
#CONFIG_ESP_PKT_STATS=y
|
||||
|
||||
# # 12. Priorities
|
||||
# ----------------
|
||||
|
||||
|
||||
#13. Mem optimizations
|
||||
#---------------------
|
||||
CONFIG_FREERTOS_PLACE_FUNCTIONS_INTO_FLASH=y
|
||||
@@ -0,0 +1,100 @@
|
||||
# 1. CPU
|
||||
#--------
|
||||
CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_160=y
|
||||
|
||||
# 2. BT Configuration
|
||||
#---------------------
|
||||
CONFIG_BT_ENABLED=n
|
||||
CONFIG_BT_CONTROLLER_ONLY=y
|
||||
CONFIG_BT_BLUEDROID_ENABLED=
|
||||
CONFIG_BT_LE_SLEEP_ENABLE=y
|
||||
|
||||
# 3.1 BLE over SPI/SDIO
|
||||
#-----------------------
|
||||
CONFIG_BT_LE_HCI_INTERFACE_USE_RAM=y
|
||||
|
||||
# 3.2 BLE over UART
|
||||
#-------------------
|
||||
# Enable below config, delete sdkconfig, build/ and rebuild
|
||||
# CONFIG_BT_LE_HCI_INTERFACE_USE_UART=y
|
||||
# CONFIG_BT_LE_HCI_UART_TX_PIN=5
|
||||
# CONFIG_BT_LE_HCI_UART_RX_PIN=12
|
||||
# CONFIG_BT_LE_HCI_UART_FLOWCTRL=n
|
||||
# # 4 pin solution is not working yet for c6
|
||||
# #CONFIG_BT_LE_HCI_UART_RTS_PIN=9
|
||||
# #CONFIG_BT_LE_HCI_UART_CTS_PIN=13
|
||||
|
||||
|
||||
# 4. Partition Table
|
||||
#--------------------
|
||||
CONFIG_PARTITION_TABLE_CUSTOM=y
|
||||
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions_eh_cp_ota_4m.csv"
|
||||
|
||||
# 5. Mempool
|
||||
#------------
|
||||
CONFIG_ESP_CACHE_MALLOC=y
|
||||
|
||||
|
||||
# # 6.1 LWIP split
|
||||
# #---------------
|
||||
#
|
||||
# CONFIG_ESP_HOSTED_CP_FEAT_NW_SPLIT=y
|
||||
# CONFIG_LWIP_TCP_LOCAL_PORT_RANGE_START=61440
|
||||
# CONFIG_LWIP_TCP_LOCAL_PORT_RANGE_END=65535
|
||||
# CONFIG_LWIP_UDP_LOCAL_PORT_RANGE_START=61440
|
||||
# CONFIG_LWIP_UDP_LOCAL_PORT_RANGE_END=65535
|
||||
#
|
||||
#
|
||||
# # 6.2 LWIP split examples
|
||||
# #-------------------------
|
||||
|
||||
|
||||
# 7. Transport config
|
||||
#---------------------
|
||||
# ESP_HOSTED_TRANSPORT_CP_SDIO_NSEND_PSAMPLE=y
|
||||
# ESP_HOSTED_TRANSPORT_CP_SDIO_DEFAULT_SPEED=y
|
||||
#ESP_HOSTED_TRANSPORT_CP_SDIO_STREAMING_MODE=y
|
||||
|
||||
# For SPI Full duplex C6 on ESP32-P4-Function-EV-Board, please uncomment below
|
||||
#CONFIG_ESP_HOST_DEV_BOARD_P4_FUNC_BOARD=y
|
||||
#CONFIG_ESP_HOSTED_TRANSPORT_CP_SPI=y
|
||||
|
||||
|
||||
# 8. Wifi config
|
||||
#----------------
|
||||
|
||||
CONFIG_ESP_WIFI_STATIC_RX_BUFFER_NUM=20
|
||||
CONFIG_ESP_WIFI_DYNAMIC_RX_BUFFER_NUM=64
|
||||
CONFIG_ESP_WIFI_DYNAMIC_TX_BUFFER_NUM=64
|
||||
CONFIG_ESP_WIFI_AMPDU_TX_ENABLED=y
|
||||
CONFIG_ESP_WIFI_TX_BA_WIN=32
|
||||
CONFIG_ESP_WIFI_AMPDU_RX_ENABLED=y
|
||||
CONFIG_ESP_WIFI_RX_BA_WIN=32
|
||||
|
||||
CONFIG_ESP_WIFI_RX_IRAM_OPT=y
|
||||
CONFIG_ESP_WIFI_IRAM_OPT=y
|
||||
|
||||
# # 9. LWIP config
|
||||
# #----------------
|
||||
# CONFIG_LWIP_TCP_SND_BUF_DEFAULT=65535
|
||||
# CONFIG_LWIP_TCP_WND_DEFAULT=65535
|
||||
# CONFIG_LWIP_TCP_RECVMBOX_SIZE=64
|
||||
# CONFIG_LWIP_UDP_RECVMBOX_SIZE=64
|
||||
# CONFIG_LWIP_TCPIP_RECVMBOX_SIZE=64
|
||||
# CONFIG_LWIP_TCP_SACK_OUT=y
|
||||
# #CONFIG_LWIP_TCPIP_CORE_LOCKING=y
|
||||
# #CONFIG_LWIP_TCPIP_CORE_LOCKING_INPUT=y
|
||||
|
||||
|
||||
# 10. Optimizations
|
||||
#-------------------
|
||||
CONFIG_COMPILER_OPTIMIZATION_PERF=y
|
||||
|
||||
|
||||
# 11. Stats
|
||||
#-----------
|
||||
#CONFIG_ESP_HOSTED_FUNCTION_PROFILING=y
|
||||
#CONFIG_ESP_PKT_STATS=y
|
||||
|
||||
# # 12 iperf task
|
||||
# #--------------
|
||||
@@ -0,0 +1,16 @@
|
||||
CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_160=y
|
||||
|
||||
# BT Configuration
|
||||
CONFIG_BT_ENABLED=n
|
||||
CONFIG_BT_CONTROLLER_ONLY=y
|
||||
CONFIG_BT_BLUEDROID_ENABLED=
|
||||
CONFIG_BT_LE_SLEEP_ENABLE=y
|
||||
|
||||
# SPI/SDIO only
|
||||
#CONFIG_BT_LE_HCI_INTERFACE_USE_RAM=y
|
||||
|
||||
CONFIG_ESP_CACHE_MALLOC=n
|
||||
|
||||
CONFIG_PARTITION_TABLE_CUSTOM=y
|
||||
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions_eh_cp_ota_4m.csv"
|
||||
#CONFIG_ESP_PKT_STATS=y
|
||||
@@ -0,0 +1,82 @@
|
||||
# 1. CPU
|
||||
#--------
|
||||
CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ=240
|
||||
|
||||
# 2. Partition Table
|
||||
#--------------------
|
||||
CONFIG_PARTITION_TABLE_CUSTOM=y
|
||||
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions_eh_cp_ota_4m.csv"
|
||||
|
||||
# 3. Mempool
|
||||
#------------
|
||||
CONFIG_ESP_CACHE_MALLOC=y
|
||||
|
||||
|
||||
# # 4.1 LWIP split
|
||||
# #---------------
|
||||
#
|
||||
# CONFIG_ESP_HOSTED_CP_FEAT_NW_SPLIT=y
|
||||
# CONFIG_LWIP_TCP_LOCAL_PORT_RANGE_START=61440
|
||||
# CONFIG_LWIP_TCP_LOCAL_PORT_RANGE_END=65535
|
||||
# CONFIG_LWIP_UDP_LOCAL_PORT_RANGE_START=61440
|
||||
# CONFIG_LWIP_UDP_LOCAL_PORT_RANGE_END=65535
|
||||
#
|
||||
#
|
||||
# # 4.2 LWIP split examples
|
||||
# #-------------------------
|
||||
|
||||
|
||||
# 5. Transport config
|
||||
#---------------------
|
||||
# ESP_HOSTED_TRANSPORT_CP_SDIO_NSEND_PSAMPLE=y
|
||||
# ESP_HOSTED_TRANSPORT_CP_SDIO_DEFAULT_SPEED=y
|
||||
# ESP_HOSTED_TRANSPORT_CP_SDIO_STREAMING_MODE=n
|
||||
|
||||
# For SPI Full duplex C6 on ESP32-P4-Function-EV-Board, please uncomment below
|
||||
#CONFIG_C6_SPI_WITH_P4=y
|
||||
|
||||
|
||||
# 6. Wifi config
|
||||
#----------------
|
||||
|
||||
CONFIG_ESP_WIFI_STATIC_RX_BUFFER_NUM=10
|
||||
CONFIG_ESP_WIFI_DYNAMIC_RX_BUFFER_NUM=32
|
||||
CONFIG_ESP_WIFI_DYNAMIC_TX_BUFFER_NUM=32
|
||||
CONFIG_ESP_WIFI_AMPDU_TX_ENABLED=y
|
||||
CONFIG_ESP_WIFI_TX_BA_WIN=16
|
||||
CONFIG_ESP_WIFI_AMPDU_RX_ENABLED=y
|
||||
CONFIG_ESP_WIFI_RX_BA_WIN=16
|
||||
|
||||
CONFIG_ESP_WIFI_RX_IRAM_OPT=y
|
||||
CONFIG_ESP_WIFI_IRAM_OPT=y
|
||||
|
||||
# # 7. LWIP config
|
||||
# #----------------
|
||||
# CONFIG_LWIP_TCP_SND_BUF_DEFAULT=11520
|
||||
# CONFIG_LWIP_TCP_WND_DEFAULT=11520
|
||||
# CONFIG_LWIP_TCP_RECVMBOX_SIZE=16
|
||||
# CONFIG_LWIP_UDP_RECVMBOX_SIZE=16
|
||||
# CONFIG_LWIP_TCPIP_RECVMBOX_SIZE=32
|
||||
# CONFIG_LWIP_TCP_SACK_OUT=y
|
||||
# CONFIG_LWIP_TCPIP_CORE_LOCKING=y
|
||||
# CONFIG_LWIP_TCPIP_CORE_LOCKING_INPUT=y
|
||||
|
||||
|
||||
# 8. Optimizations
|
||||
#-------------------
|
||||
CONFIG_COMPILER_OPTIMIZATION_PERF=y
|
||||
CONFIG_SPI_MASTER_ISR_IN_IRAM=n
|
||||
|
||||
|
||||
# 9. Stats
|
||||
#-----------
|
||||
#CONFIG_ESP_HOSTED_FUNCTION_PROFILING=y
|
||||
#CONFIG_ESP_PKT_STATS=y
|
||||
|
||||
# # 10. Priorities
|
||||
# ----------------
|
||||
|
||||
|
||||
# 11. Mem optimizations
|
||||
#---------------------
|
||||
CONFIG_FREERTOS_PLACE_FUNCTIONS_INTO_FLASH=y
|
||||
@@ -0,0 +1,104 @@
|
||||
# 1. CPU
|
||||
#--------
|
||||
CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ=240
|
||||
|
||||
# 2. BT Configuration
|
||||
#---------------------
|
||||
CONFIG_BT_ENABLED=n
|
||||
CONFIG_BT_CONTROLLER_ONLY=y
|
||||
CONFIG_BT_BLUEDROID_ENABLED=
|
||||
CONFIG_BT_LE_SLEEP_ENABLE=y
|
||||
|
||||
# 3.1 BLE over SPI/SDIO
|
||||
#-----------------------
|
||||
CONFIG_BT_LE_HCI_INTERFACE_USE_RAM=y
|
||||
|
||||
# 3.2 BLE over UART
|
||||
#-------------------
|
||||
# Enable below config, delete sdkconfig, build/ and rebuild
|
||||
# CONFIG_BT_LE_HCI_INTERFACE_USE_UART=y
|
||||
# CONFIG_BT_LE_HCI_UART_TX_PIN=5
|
||||
# CONFIG_BT_LE_HCI_UART_RX_PIN=18
|
||||
# CONFIG_BT_LE_HCI_UART_FLOWCTRL=n
|
||||
# #CONFIG_BT_LE_HCI_UART_RTS_PIN=19
|
||||
# #CONFIG_BT_LE_HCI_UART_CTS_PIN=8
|
||||
|
||||
|
||||
# 4. Partition Table
|
||||
#--------------------
|
||||
CONFIG_PARTITION_TABLE_CUSTOM=y
|
||||
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions_eh_cp_ota_4m.csv"
|
||||
|
||||
# 5. Mempool
|
||||
#------------
|
||||
CONFIG_ESP_CACHE_MALLOC=y
|
||||
|
||||
|
||||
# # 6.1 LWIP split
|
||||
# #---------------
|
||||
#
|
||||
# CONFIG_ESP_HOSTED_CP_FEAT_NW_SPLIT=y
|
||||
# CONFIG_LWIP_TCP_LOCAL_PORT_RANGE_START=61440
|
||||
# CONFIG_LWIP_TCP_LOCAL_PORT_RANGE_END=65535
|
||||
# CONFIG_LWIP_UDP_LOCAL_PORT_RANGE_START=61440
|
||||
# CONFIG_LWIP_UDP_LOCAL_PORT_RANGE_END=65535
|
||||
#
|
||||
#
|
||||
# # 6.2 LWIP split examples
|
||||
# #-------------------------
|
||||
|
||||
|
||||
# 7. Transport config
|
||||
#---------------------
|
||||
# ESP_HOSTED_TRANSPORT_CP_SDIO_NSEND_PSAMPLE=y
|
||||
# ESP_HOSTED_TRANSPORT_CP_SDIO_DEFAULT_SPEED=y
|
||||
# ESP_HOSTED_TRANSPORT_CP_SDIO_STREAMING_MODE=n
|
||||
|
||||
# For SPI Full duplex C6 on ESP32-P4-Function-EV-Board, please uncomment below
|
||||
#CONFIG_C6_SPI_WITH_P4=y
|
||||
|
||||
|
||||
# 8. Wifi config
|
||||
#----------------
|
||||
|
||||
CONFIG_ESP_WIFI_STATIC_RX_BUFFER_NUM=10
|
||||
CONFIG_ESP_WIFI_DYNAMIC_RX_BUFFER_NUM=32
|
||||
CONFIG_ESP_WIFI_DYNAMIC_TX_BUFFER_NUM=32
|
||||
CONFIG_ESP_WIFI_AMPDU_TX_ENABLED=y
|
||||
CONFIG_ESP_WIFI_TX_BA_WIN=16
|
||||
CONFIG_ESP_WIFI_AMPDU_RX_ENABLED=y
|
||||
CONFIG_ESP_WIFI_RX_BA_WIN=16
|
||||
|
||||
CONFIG_ESP_WIFI_RX_IRAM_OPT=y
|
||||
CONFIG_ESP_WIFI_IRAM_OPT=y
|
||||
|
||||
# # 9. LWIP config
|
||||
# #----------------
|
||||
# CONFIG_LWIP_TCP_SND_BUF_DEFAULT=11520
|
||||
# CONFIG_LWIP_TCP_WND_DEFAULT=11520
|
||||
# CONFIG_LWIP_TCP_RECVMBOX_SIZE=16
|
||||
# CONFIG_LWIP_UDP_RECVMBOX_SIZE=16
|
||||
# CONFIG_LWIP_TCPIP_RECVMBOX_SIZE=32
|
||||
# CONFIG_LWIP_TCP_SACK_OUT=y
|
||||
# CONFIG_LWIP_TCPIP_CORE_LOCKING=y
|
||||
# CONFIG_LWIP_TCPIP_CORE_LOCKING_INPUT=y
|
||||
|
||||
|
||||
# 10. Optimizations
|
||||
#-------------------
|
||||
CONFIG_COMPILER_OPTIMIZATION_PERF=y
|
||||
CONFIG_SPI_MASTER_ISR_IN_IRAM=n
|
||||
|
||||
|
||||
# 11. Stats
|
||||
#-----------
|
||||
#CONFIG_ESP_HOSTED_FUNCTION_PROFILING=y
|
||||
#CONFIG_ESP_PKT_STATS=y
|
||||
|
||||
# # 12. Priorities
|
||||
# ----------------
|
||||
|
||||
|
||||
#13. Mem optimizations
|
||||
#---------------------
|
||||
CONFIG_FREERTOS_PLACE_FUNCTIONS_INTO_FLASH=y
|
||||
@@ -0,0 +1,3 @@
|
||||
cmake_minimum_required(VERSION 3.16)
|
||||
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
|
||||
project(c6_ota_v2)
|
||||
@@ -0,0 +1,2 @@
|
||||
idf_component_register(SRCS "main.c" INCLUDE_DIRS "."
|
||||
PRIV_REQUIRES esp_partition esp_app_format bootloader_support nvs_flash esp_netif esp_event esp_wifi)
|
||||
@@ -0,0 +1,3 @@
|
||||
dependencies:
|
||||
espressif/esp_hosted: "~2"
|
||||
espressif/esp_wifi_remote: "*"
|
||||
@@ -0,0 +1,87 @@
|
||||
// One-shot C6 updater for the Waveshare ESP32-P4-Nano, built on esp-hosted 2.x so it speaks the
|
||||
// RPC protocol of the C6's old factory firmware. Streams the C6 image that is already in the
|
||||
// P4's "slave_fw" flash partition (written by ../mcu_host's flash step) and then reboots.
|
||||
#include <string.h>
|
||||
#include "esp_log.h"
|
||||
#include "esp_partition.h"
|
||||
#include "esp_app_desc.h"
|
||||
#include "esp_image_format.h"
|
||||
#include "esp_event.h"
|
||||
#include "esp_netif.h"
|
||||
#include "nvs_flash.h"
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "esp_system.h"
|
||||
#include "esp_hosted.h"
|
||||
#include "esp_hosted_ota.h"
|
||||
|
||||
static const char *TAG = "c6-ota";
|
||||
#define CHUNK 1400
|
||||
|
||||
// Size of an ESP app image: header, segments, checksum padded to 16, optional SHA-256.
|
||||
static uint32_t image_size(const esp_partition_t *p)
|
||||
{
|
||||
esp_image_header_t h;
|
||||
if (esp_partition_read(p, 0, &h, sizeof h) != ESP_OK || h.magic != ESP_IMAGE_HEADER_MAGIC)
|
||||
return 0;
|
||||
uint32_t off = sizeof h;
|
||||
for (int i = 0; i < h.segment_count; i++) {
|
||||
esp_image_segment_header_t s;
|
||||
if (esp_partition_read(p, off, &s, sizeof s) != ESP_OK) return 0;
|
||||
off += sizeof s + s.data_len;
|
||||
}
|
||||
off = (off + 1 + 15) & ~15u; // checksum byte, then pad to 16
|
||||
if (h.hash_appended) off += 32;
|
||||
return off <= p->size ? off : 0;
|
||||
}
|
||||
|
||||
static void halt(const char *why)
|
||||
{
|
||||
ESP_LOGE(TAG, "%s", why);
|
||||
for (;;) { ESP_LOGE(TAG, "RESULT FAIL: %s", why); vTaskDelay(pdMS_TO_TICKS(5000)); }
|
||||
}
|
||||
|
||||
void app_main(void)
|
||||
{
|
||||
nvs_flash_init();
|
||||
esp_netif_init();
|
||||
esp_event_loop_create_default();
|
||||
|
||||
if (esp_hosted_connect_to_slave() != 0) halt("cannot connect to C6");
|
||||
|
||||
esp_hosted_coprocessor_fwver_t v = {0};
|
||||
if (esp_hosted_get_coprocessor_fwversion(&v) == ESP_OK)
|
||||
ESP_LOGI(TAG, "C6 firmware before update: %lu.%lu.%lu", (unsigned long)v.major1,
|
||||
(unsigned long)v.minor1, (unsigned long)v.patch1);
|
||||
else
|
||||
ESP_LOGW(TAG, "C6 did not report a version (old firmware)");
|
||||
|
||||
const esp_partition_t *p = esp_partition_find_first(ESP_PARTITION_TYPE_DATA, 0x40, "slave_fw");
|
||||
if (!p) halt("no slave_fw partition");
|
||||
uint32_t size = image_size(p);
|
||||
if (!size) halt("slave_fw does not hold a valid image");
|
||||
esp_app_desc_t d;
|
||||
esp_partition_read(p, sizeof(esp_image_header_t) + sizeof(esp_image_segment_header_t), &d, sizeof d);
|
||||
ESP_LOGI(TAG, "New C6 image: %u bytes, project '%s', IDF %s", (unsigned)size, d.project_name, d.idf_ver);
|
||||
|
||||
if (esp_hosted_slave_ota_begin() != ESP_OK) halt("OTA begin failed");
|
||||
static uint8_t buf[CHUNK];
|
||||
for (uint32_t off = 0; off < size;) {
|
||||
uint32_t n = size - off > CHUNK ? CHUNK : size - off;
|
||||
esp_partition_read(p, off, buf, n);
|
||||
if (esp_hosted_slave_ota_write(buf, n) != ESP_OK) {
|
||||
ESP_LOGE(TAG, "write failed at offset %u", (unsigned)off);
|
||||
halt("OTA write failed");
|
||||
}
|
||||
off += n;
|
||||
if ((off / CHUNK) % 100 == 0 || off == size)
|
||||
ESP_LOGI(TAG, "sent %u / %u bytes", (unsigned)off, (unsigned)size);
|
||||
}
|
||||
if (esp_hosted_slave_ota_end() != ESP_OK) halt("OTA end failed (image rejected)");
|
||||
ESP_LOGI(TAG, "OTA end OK");
|
||||
esp_err_t a = esp_hosted_slave_ota_activate(); // only on C6 fw 2.6+; older ones switch at end
|
||||
ESP_LOGI(TAG, "activate: %s", esp_err_to_name(a));
|
||||
|
||||
for (int i = 0; i < 3; i++) { ESP_LOGI(TAG, "RESULT OK: C6 updated, rebooting"); vTaskDelay(pdMS_TO_TICKS(1000)); }
|
||||
esp_restart(); // reboots the P4, which resets the C6 into the new image
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
# Universal partition table for all OTA methods (HTTPS / LittleFS / Partition).
|
||||
# Mirrors upstream esp_hosted/examples/host_performs_slave_ota/partitions.csv.
|
||||
#
|
||||
# Layout (8 MB flash, host = ESP32-P4):
|
||||
# nvs 16K — config / Wi-Fi credentials
|
||||
# otadata 8K — IDF OTA bookkeeping (which slot is active)
|
||||
# phy_init 4K — RF calibration data
|
||||
# ota_0 2M @ 0x010000 — host firmware A
|
||||
# ota_1 2M @ 0x210000 — host firmware B
|
||||
# storage 1920K @ 0x410000 — LittleFS partition (used by OTA_METHOD_LITTLEFS:
|
||||
# the host stages the slave .bin into this FS,
|
||||
# then streams it over RPC).
|
||||
# slave_fw 2M @ 0x5F0000 — raw partition (used by OTA_METHOD_PARTITION:
|
||||
# host reads slave .bin straight from flash).
|
||||
#
|
||||
# Name, Type, SubType, Offset, Size, Flags
|
||||
nvs, data, nvs, 0x9000, 16K,
|
||||
otadata, data, ota, 0xd000, 8K,
|
||||
phy_init, data, phy, 0xf000, 4K,
|
||||
ota_0, app, ota_0, 0x10000, 2M,
|
||||
ota_1, app, ota_1, 0x210000, 2M,
|
||||
storage, data, littlefs, 0x410000, 0x1E0000,
|
||||
slave_fw, data, 0x40, 0x5F0000, 0x200000,
|
||||
|
@@ -0,0 +1,7 @@
|
||||
CONFIG_IDF_TARGET="esp32p4"
|
||||
CONFIG_ESP_CONSOLE_UART_DEFAULT=y
|
||||
CONFIG_ESPTOOLPY_FLASHSIZE_16MB=y
|
||||
CONFIG_PARTITION_TABLE_CUSTOM=y
|
||||
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv"
|
||||
CONFIG_SLAVE_IDF_TARGET_ESP32C6=y
|
||||
CONFIG_ESP_HOSTED_SDIO_HOST_INTERFACE=y
|
||||
@@ -0,0 +1,9 @@
|
||||
cmake_minimum_required(VERSION 3.16)
|
||||
|
||||
#set(EXTRA_COMPONENT_DIRS "$ENV{IDF_PATH}/examples/common_components/protocol_examples_common")
|
||||
|
||||
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
|
||||
|
||||
set(PARTITION_TABLE_FILE "${CMAKE_CURRENT_SOURCE_DIR}/partitions.csv")
|
||||
|
||||
project(host_performs_slave_ota)
|
||||
@@ -0,0 +1,108 @@
|
||||
# ota / coprocessor_ota — Host
|
||||
|
||||
Pushes a new CP firmware image from the host through the OTA
|
||||
begin / write / end / activate RPC chain. The host can source the image
|
||||
from one of three places — HTTPS, an on-host LittleFS partition, or a
|
||||
dedicated raw flash partition — selected at build time.
|
||||
|
||||
## Supported Platforms and Transports
|
||||
|
||||
### Supported Coprocessors
|
||||
|
||||
| Coprocessor | ESP32 | ESP32-C Series | ESP32-S2/S3 | ESP32-S31 |
|
||||
| :----------: | :---: | :------------: | :---------: | :-------: |
|
||||
| Support | Yes | Yes | Yes | Yes ¹ |
|
||||
|
||||
¹ ESP32-S31: preview target, 2.4 GHz only, no SDIO. See [ESP32-S31 test board](https://github.com/espressif/esp-hosted/blob/master/docs/getting-started-mcu.md#esp32-s31-test-board-on-the-esp32-p4-function-ev-board).
|
||||
|
||||
### Supported Host Devices
|
||||
|
||||
| Host Device | ESP32-P4 | ESP32-H2 | Other MCUs | Linux |
|
||||
| :---------: | :------: | :------: | :--------: | :---: |
|
||||
| Support | Yes | Yes | [Yes](https://github.com/espressif/esp-hosted/blob/master/docs/getting-started-mcu.md) | [Yes](https://github.com/espressif/esp-hosted/blob/master/docs/getting-started-linux.md) |
|
||||
|
||||
### Supported Connection buses
|
||||
|
||||
| Connection bus | SDIO | SPI Full-Duplex | SPI Half-Duplex | UART |
|
||||
| :------------- | :--: | :-------------: | :-------------: | :--: |
|
||||
| Linux host | Yes | Yes | No | No |
|
||||
| MCU host | Yes | Yes | Yes | Yes |
|
||||
|
||||
## Scenario
|
||||
|
||||
The host streams new co-processor firmware over the control path using the four-call OTA RPC chain — `begin` → `write` (looped) → `end` → `activate`. (`activate` is a distinct RPC, needed on CP firmware v2.6.0+.) API names below are the example's compat surface (`esp_hosted_slave_ota_*`); the native equivalents are `eh_host_cp_ota_*`.
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant App as Host app
|
||||
participant CP as Co-processor
|
||||
participant SRC as Firmware source (HTTPS / LittleFS / partition)
|
||||
App->>CP: esp_hosted_slave_ota_begin() (RPC)
|
||||
loop firmware chunks
|
||||
App->>SRC: fetch chunk
|
||||
App->>CP: esp_hosted_slave_ota_write(chunk) (RPC)
|
||||
end
|
||||
App->>CP: esp_hosted_slave_ota_end() (RPC)
|
||||
App->>CP: esp_hosted_slave_ota_activate() (RPC)
|
||||
CP->>CP: set boot partition
|
||||
CP-->>App: result
|
||||
Note over CP: reboot into new firmware
|
||||
```
|
||||
|
||||
Select the transport (must match the co-processor) and pick the OTA method:
|
||||
|
||||
```bash
|
||||
cd examples/ota/coprocessor_ota/mcu_host
|
||||
idf.py set-target esp32p4
|
||||
idf.py menuconfig
|
||||
```
|
||||
|
||||
```text
|
||||
Component config
|
||||
└── ESP-Hosted
|
||||
└── Configure host
|
||||
└── Host transport
|
||||
├── Communication bus (co-processor <== bus ==> host)
|
||||
│ ├── ( ) SPI Full Duplex
|
||||
│ ├── (X) SDIO <── default (match the co-processor)
|
||||
│ ├── ( ) SPI Half Duplex
|
||||
│ └── ( ) UART
|
||||
└── SDIO Configuration ← slot, bus width, GPIOs (defaults OK)
|
||||
```
|
||||
|
||||
```text
|
||||
ESP-Hosted Coprocessor OTA Config
|
||||
├── Select OTA Method
|
||||
│ ├── (X) HTTP OTA <── default
|
||||
│ ├── ( ) LittleFS OTA
|
||||
│ └── ( ) Partition OTA
|
||||
│
|
||||
├── WiFi Connection ⎫
|
||||
│ ├── (MyWiFiSSID) WiFi SSID │
|
||||
│ └── (········) WiFi Password │
|
||||
├── HTTPS OTA Configuration ⎬ HTTP OTA method
|
||||
│ ├── (…/firmware.bin) OTA Server URL │
|
||||
│ ├── (30000) HTTPS connection timeout (ms) │
|
||||
│ └── [ ] Use self-signed certificate (testing only) ⎭
|
||||
│
|
||||
├── (slave_fw) Partition Label ← Partition OTA method
|
||||
├── [*] Delete OTA file after flashing ← LittleFS OTA method
|
||||
│
|
||||
└── OTA Verification Options
|
||||
├── [*] Host-Slave version compatibility check
|
||||
└── [*] Skip OTA if slave firmware versions match
|
||||
```
|
||||
|
||||
Host dependency config is **pre-set in `mcu_host/sdkconfig.defaults`** (do not remove):
|
||||
|
||||
```text
|
||||
CONFIG_ESP_HOSTED_HOST_FEAT_WIFI=y # Wi-Fi — HTTPS OTA download path
|
||||
```
|
||||
|
||||
Then flash and monitor:
|
||||
|
||||
```bash
|
||||
idf.py -p <host_usb_serial_port> flash monitor
|
||||
```
|
||||
|
||||
<!-- generated from ../README.md — edit that file, not this one -->
|
||||
@@ -0,0 +1,64 @@
|
||||
# Common script to find the newest firmware file dynamically during build
|
||||
# This runs every time during build, not just during configuration
|
||||
#
|
||||
# Required input variables:
|
||||
# - SOURCE_COMPONENT_DIR: Path to the component source directory
|
||||
# - BINARY_COMPONENT_DIR: Path to the component binary directory
|
||||
# - OTA_ACTION: "prepare_littlefs" or "select_for_partition"
|
||||
#
|
||||
# Optional input variables:
|
||||
# - COMPONENT_NAME: Name for logging (default: "OTA")
|
||||
|
||||
if(NOT DEFINED COMPONENT_NAME)
|
||||
set(COMPONENT_NAME "OTA")
|
||||
endif()
|
||||
|
||||
# Use the passed component directories
|
||||
set(SOURCE_DIR "${SOURCE_COMPONENT_DIR}/slave_fw_bin")
|
||||
set(TEMP_DIR "${BINARY_COMPONENT_DIR}/temp_littlefs")
|
||||
|
||||
message(STATUS "${COMPONENT_NAME}: Dynamically searching for newest firmware...")
|
||||
message(STATUS "${COMPONENT_NAME}: Searching in ${SOURCE_DIR}")
|
||||
|
||||
# Get all .bin files
|
||||
file(GLOB FIRMWARE_FILES "${SOURCE_DIR}/*.bin")
|
||||
|
||||
if(NOT FIRMWARE_FILES)
|
||||
message(FATAL_ERROR "${COMPONENT_NAME}: No .bin files found in ${SOURCE_DIR}")
|
||||
endif()
|
||||
|
||||
# Find the newest file by timestamp
|
||||
set(NEWEST_FILE "")
|
||||
set(NEWEST_TIMESTAMP 0)
|
||||
|
||||
foreach(FIRMWARE_FILE ${FIRMWARE_FILES})
|
||||
file(TIMESTAMP "${FIRMWARE_FILE}" FILE_TIMESTAMP "%s")
|
||||
message(STATUS "${COMPONENT_NAME}: File ${FIRMWARE_FILE} timestamp: ${FILE_TIMESTAMP}")
|
||||
if(FILE_TIMESTAMP GREATER NEWEST_TIMESTAMP)
|
||||
set(NEWEST_FILE "${FIRMWARE_FILE}")
|
||||
set(NEWEST_TIMESTAMP "${FILE_TIMESTAMP}")
|
||||
endif()
|
||||
endforeach()
|
||||
|
||||
get_filename_component(NEWEST_FILENAME "${NEWEST_FILE}" NAME)
|
||||
message(STATUS "${COMPONENT_NAME}: Selected newest firmware: ${NEWEST_FILENAME}")
|
||||
|
||||
# Perform the requested action
|
||||
if(OTA_ACTION STREQUAL "prepare_littlefs")
|
||||
# Clean and recreate temp directory for LittleFS
|
||||
file(REMOVE_RECURSE "${TEMP_DIR}")
|
||||
file(MAKE_DIRECTORY "${TEMP_DIR}")
|
||||
file(COPY "${NEWEST_FILE}" DESTINATION "${TEMP_DIR}")
|
||||
message(STATUS "${COMPONENT_NAME}: Prepared ${NEWEST_FILENAME} in temp directory for LittleFS")
|
||||
|
||||
elseif(OTA_ACTION STREQUAL "select_for_partition")
|
||||
# Write selection to files for partition OTA
|
||||
file(WRITE "${BINARY_COMPONENT_DIR}/selected_firmware.txt" "${NEWEST_FILE}")
|
||||
file(WRITE "${BINARY_COMPONENT_DIR}/selected_firmware_name.txt" "${NEWEST_FILENAME}")
|
||||
message(STATUS "${COMPONENT_NAME}: Saved firmware selection for partition flashing")
|
||||
|
||||
else()
|
||||
message(FATAL_ERROR "${COMPONENT_NAME}: Unknown OTA_ACTION: ${OTA_ACTION}")
|
||||
endif()
|
||||
|
||||
message(STATUS "${COMPONENT_NAME}: Firmware selection completed")
|
||||
@@ -0,0 +1,61 @@
|
||||
# Script to flash the dynamically selected firmware for partition OTA
|
||||
# Reads the firmware path from the selection file and flashes it
|
||||
#
|
||||
# Required input variables:
|
||||
# - BINARY_COMPONENT_DIR: Path to the component binary directory
|
||||
# - SLAVE_FW_OFFSET: Partition offset for flashing
|
||||
# - PYTHON: Python executable path
|
||||
|
||||
if(NOT DEFINED COMPONENT_NAME)
|
||||
set(COMPONENT_NAME "Partition OTA")
|
||||
endif()
|
||||
|
||||
# Read the selected firmware path and name
|
||||
set(SELECTION_FILE "${BINARY_COMPONENT_DIR}/selected_firmware.txt")
|
||||
set(NAME_FILE "${BINARY_COMPONENT_DIR}/selected_firmware_name.txt")
|
||||
|
||||
if(NOT EXISTS "${SELECTION_FILE}")
|
||||
message(FATAL_ERROR "${COMPONENT_NAME}: Selection file not found: ${SELECTION_FILE}")
|
||||
endif()
|
||||
|
||||
file(READ "${SELECTION_FILE}" SELECTED_FIRMWARE_PATH)
|
||||
file(READ "${NAME_FILE}" SELECTED_FIRMWARE_NAME)
|
||||
|
||||
# Remove any trailing newlines
|
||||
string(STRIP "${SELECTED_FIRMWARE_PATH}" SELECTED_FIRMWARE_PATH)
|
||||
string(STRIP "${SELECTED_FIRMWARE_NAME}" SELECTED_FIRMWARE_NAME)
|
||||
|
||||
message(STATUS "-----------------------------------------------------")
|
||||
message(STATUS "${COMPONENT_NAME}: Flashing ${SELECTED_FIRMWARE_NAME}")
|
||||
message(STATUS "Path: ${SELECTED_FIRMWARE_PATH}")
|
||||
message(STATUS "Offset: ${SLAVE_FW_OFFSET}")
|
||||
message(STATUS "-----------------------------------------------------")
|
||||
|
||||
# Check if file exists
|
||||
if(NOT EXISTS "${SELECTED_FIRMWARE_PATH}")
|
||||
message(FATAL_ERROR "❌ ERROR: Selected firmware file not found: ${SELECTED_FIRMWARE_PATH}")
|
||||
endif()
|
||||
|
||||
# Execute esptool (this will inherit the port from the parent build process)
|
||||
execute_process(
|
||||
COMMAND ${PYTHON} -m esptool
|
||||
-b 2000000
|
||||
write_flash
|
||||
--force
|
||||
${SLAVE_FW_OFFSET} "${SELECTED_FIRMWARE_PATH}"
|
||||
RESULT_VARIABLE FLASH_RESULT
|
||||
OUTPUT_VARIABLE FLASH_OUTPUT
|
||||
ERROR_VARIABLE FLASH_ERROR
|
||||
OUTPUT_STRIP_TRAILING_WHITESPACE
|
||||
ERROR_STRIP_TRAILING_WHITESPACE
|
||||
)
|
||||
|
||||
if(FLASH_OUTPUT)
|
||||
message(STATUS "${FLASH_OUTPUT}")
|
||||
endif()
|
||||
|
||||
if(NOT FLASH_RESULT EQUAL 0)
|
||||
message(FATAL_ERROR "❌ ERROR: Failed to flash firmware:\n${FLASH_ERROR}")
|
||||
endif()
|
||||
|
||||
message(STATUS "✅ Successfully flashed ${SELECTED_FIRMWARE_NAME} to partition!")
|
||||
@@ -0,0 +1,28 @@
|
||||
if(CONFIG_OTA_METHOD_HTTPS)
|
||||
set(SRC_LIST "ota_https.c" "ota_https_wifi.c")
|
||||
endif()
|
||||
|
||||
idf_component_register(SRCS ${SRC_LIST}
|
||||
INCLUDE_DIRS "."
|
||||
REQUIRES esp_http_client app_update esp_wifi esp_hosted nvs_flash esp_https_ota mbedtls esp-tls bootloader_support esp_app_format)
|
||||
|
||||
# Conditional certificate embedding based on Kconfig
|
||||
if(CONFIG_OTA_METHOD_HTTPS)
|
||||
if(CONFIG_OTA_USE_SELF_SIGNED_CERT)
|
||||
if(EXISTS "${COMPONENT_DIR}/certs/server_cert.pem")
|
||||
target_add_binary_data(
|
||||
${COMPONENT_LIB}
|
||||
"certs/server_cert.pem"
|
||||
TEXT
|
||||
)
|
||||
message(STATUS "✓ HTTPS OTA: Embedding self-signed certificate for testing")
|
||||
else()
|
||||
message(FATAL_ERROR
|
||||
"HTTPS OTA: Self-signed cert enabled but certs/server_cert.pem not found! \n"
|
||||
"1. Run ./create_self_signed_certs.sh in components/ota_https/test_server directory to generate certificates.\n"
|
||||
"2. Run ./create_https_server.py in components/ota_https/test_server directory to start the HTTPS server.")
|
||||
endif()
|
||||
else()
|
||||
message(STATUS "✓ HTTPS OTA: Using CA certificate bundle (Production mode)")
|
||||
endif()
|
||||
endif()
|
||||
@@ -0,0 +1,413 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2025-2026 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
/*
|
||||
* ESP-Hosted HTTPS OTA Component
|
||||
* =============================
|
||||
*
|
||||
* Downloads ESP32 slave firmware from HTTPS URL and performs OTA update.
|
||||
*
|
||||
* FEATURES:
|
||||
* - Secure HTTPS firmware download
|
||||
* - Firmware validation (magic number, image header)
|
||||
* - Version checking against current slave firmware
|
||||
* - WiFi connection management
|
||||
* - Certificate validation (optional)
|
||||
*
|
||||
* APIs USED:
|
||||
* - esp_hosted_get_coprocessor_fwversion() - Get slave firmware version
|
||||
* - esp_hosted_slave_ota_begin() - Initialize OTA session
|
||||
* - esp_hosted_slave_ota_write() - Transfer firmware chunks
|
||||
* - esp_hosted_slave_ota_end() - Finalize OTA session
|
||||
* - esp_hosted_slave_ota_activate() - (if current slave FW > v2.5.X only) - ** Called from main.c **
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <inttypes.h>
|
||||
#include "esp_log.h"
|
||||
#include "esp_err.h"
|
||||
#include "esp_hosted.h"
|
||||
#include "esp_http_client.h"
|
||||
#include "esp_crt_bundle.h" // For certificate bundle
|
||||
#include "sdkconfig.h" // For configuration macros
|
||||
#include "esp_app_format.h"
|
||||
#include "esp_app_desc.h"
|
||||
#include "esp_hosted_api_types.h"
|
||||
|
||||
#ifndef CHUNK_SIZE
|
||||
#define CHUNK_SIZE 1400
|
||||
#endif
|
||||
|
||||
static const char* TAG = "https_ota";
|
||||
|
||||
extern esp_err_t establish_wifi_connection(void);
|
||||
|
||||
/* Self-signed certificate - embedded at compile time (only if enabled) */
|
||||
#ifdef CONFIG_OTA_USE_SELF_SIGNED_CERT
|
||||
extern const uint8_t server_cert_pem_start[] asm("_binary_server_cert_pem_start");
|
||||
extern const uint8_t server_cert_pem_end[] asm("_binary_server_cert_pem_end");
|
||||
#endif
|
||||
|
||||
uint8_t http_err = 0;
|
||||
|
||||
/* Function to parse ESP32 image header and get firmware info from buffer */
|
||||
static esp_err_t parse_image_header_from_buffer(const uint8_t* buffer, size_t buffer_size, size_t* firmware_size, char* app_version_str, size_t version_str_len)
|
||||
{
|
||||
esp_image_header_t image_header;
|
||||
esp_image_segment_header_t segment_header;
|
||||
esp_app_desc_t app_desc;
|
||||
size_t offset = 0;
|
||||
size_t total_size = 0;
|
||||
|
||||
/* Check if buffer has enough data for image header */
|
||||
if (buffer_size < sizeof(image_header)) {
|
||||
ESP_LOGE(TAG, "Buffer too small for image header verification");
|
||||
return ESP_ERR_INVALID_SIZE;
|
||||
}
|
||||
|
||||
/* Read image header from buffer */
|
||||
memcpy(&image_header, buffer + offset, sizeof(image_header));
|
||||
|
||||
/* Validate magic number */
|
||||
if (image_header.magic != ESP_IMAGE_HEADER_MAGIC) {
|
||||
ESP_LOGE(TAG, "Invalid image magic: 0x%" PRIx8, image_header.magic);
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Image header: magic=0x%" PRIx8 ", segment_count=%" PRIu8 ", hash_appended=%" PRIu8,
|
||||
image_header.magic, image_header.segment_count, image_header.hash_appended);
|
||||
|
||||
/* Calculate total size by reading all segments */
|
||||
offset = sizeof(image_header);
|
||||
total_size = sizeof(image_header);
|
||||
|
||||
for (int i = 0; i < image_header.segment_count; i++) {
|
||||
/* Check if buffer has enough data for segment header */
|
||||
if (buffer_size < offset + sizeof(segment_header)) {
|
||||
ESP_LOGW(TAG, "Buffer too small to read all segment headers, using partial verification");
|
||||
break;
|
||||
}
|
||||
|
||||
/* Read segment header from buffer */
|
||||
memcpy(&segment_header, buffer + offset, sizeof(segment_header));
|
||||
|
||||
ESP_LOGI(TAG, "Segment %d: data_len=%" PRIu32 ", load_addr=0x%" PRIx32, i, segment_header.data_len, segment_header.load_addr);
|
||||
|
||||
/* Add segment header size + data size */
|
||||
total_size += sizeof(segment_header) + segment_header.data_len;
|
||||
offset += sizeof(segment_header) + segment_header.data_len;
|
||||
|
||||
/* Read app description from the first segment */
|
||||
if (i == 0) {
|
||||
size_t app_desc_offset = sizeof(image_header) + sizeof(segment_header);
|
||||
if (buffer_size >= app_desc_offset + sizeof(app_desc)) {
|
||||
memcpy(&app_desc, buffer + app_desc_offset, sizeof(app_desc));
|
||||
strncpy(app_version_str, app_desc.version, version_str_len - 1);
|
||||
app_version_str[version_str_len - 1] = '\0';
|
||||
ESP_LOGI(TAG, "Found app description: version='%s', project_name='%s'",
|
||||
app_desc.version, app_desc.project_name);
|
||||
} else {
|
||||
ESP_LOGW(TAG, "Buffer too small to read app description");
|
||||
strncpy(app_version_str, "unknown", version_str_len - 1);
|
||||
app_version_str[version_str_len - 1] = '\0';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Add padding to align to 16 bytes */
|
||||
size_t padding = (16 - (total_size % 16)) % 16;
|
||||
if (padding > 0) {
|
||||
ESP_LOGD(TAG, "Adding %u bytes of padding for alignment", (unsigned int)padding);
|
||||
total_size += padding;
|
||||
}
|
||||
|
||||
/* Add the checksum byte (always present) */
|
||||
total_size += 1;
|
||||
ESP_LOGD(TAG, "Added 1 byte for checksum");
|
||||
|
||||
/* Add SHA256 hash if appended */
|
||||
bool has_hash = (image_header.hash_appended == 1);
|
||||
if (has_hash) {
|
||||
total_size += 32; // SHA256 hash is 32 bytes
|
||||
ESP_LOGD(TAG, "Added 32 bytes for SHA256 hash (hash_appended=1)");
|
||||
} else {
|
||||
ESP_LOGD(TAG, "No SHA256 hash appended (hash_appended=0)");
|
||||
}
|
||||
|
||||
*firmware_size = total_size;
|
||||
ESP_LOGI(TAG, "Total image size: %u bytes", (unsigned int)*firmware_size);
|
||||
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static esp_err_t http_client_event_handler(esp_http_client_event_t *evt)
|
||||
{
|
||||
switch(evt->event_id) {
|
||||
case HTTP_EVENT_ERROR:
|
||||
ESP_LOGE(TAG, "HTTP_EVENT_ERROR");
|
||||
http_err = 1;
|
||||
break;
|
||||
case HTTP_EVENT_ON_CONNECTED:
|
||||
ESP_LOGI(TAG, "HTTPS_EVENT_ON_CONNECTED - SSL handshake successful");
|
||||
break;
|
||||
case HTTP_EVENT_HEADER_SENT:
|
||||
ESP_LOGI(TAG, "HTTPS_EVENT_HEADER_SENT");
|
||||
break;
|
||||
case HTTP_EVENT_ON_HEADER:
|
||||
ESP_LOGD(TAG, "HTTPS_EVENT_ON_HEADER: %s=%s", evt->header_key, evt->header_value);
|
||||
if (strcmp(evt->header_key, "Content-Length") == 0) {
|
||||
ESP_LOGI(TAG, "Content-Length: %s bytes", evt->header_value);
|
||||
}
|
||||
break;
|
||||
case HTTP_EVENT_ON_DATA:
|
||||
/* Data received - logged elsewhere */
|
||||
break;
|
||||
case HTTP_EVENT_ON_FINISH:
|
||||
ESP_LOGI(TAG, "HTTPS_EVENT_ON_FINISH - Transfer complete");
|
||||
break;
|
||||
case HTTP_EVENT_DISCONNECTED:
|
||||
ESP_LOGI(TAG, "HTTPS_EVENT_DISCONNECTED");
|
||||
break;
|
||||
case HTTP_EVENT_REDIRECT:
|
||||
ESP_LOGW(TAG, "HTTPS_EVENT_REDIRECT");
|
||||
break;
|
||||
default:
|
||||
ESP_LOGD(TAG, "Unhandled HTTPS event id: %d", evt->event_id);
|
||||
break;
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
esp_err_t ota_https_perform(const char* image_url)
|
||||
{
|
||||
uint8_t *ota_chunk = NULL;
|
||||
esp_err_t err = ESP_OK;
|
||||
int data_read = 0;
|
||||
int ota_failed = 0;
|
||||
|
||||
if ((image_url == NULL) || (image_url[0] == '\0')) {
|
||||
ESP_LOGE(TAG, "Invalid image URL");
|
||||
return ESP_HOSTED_SLAVE_OTA_FAILED;
|
||||
}
|
||||
|
||||
// Validate HTTPS URL
|
||||
if (strncmp(image_url, "https://", 8) != 0) {
|
||||
ESP_LOGE(TAG, "URL must use HTTPS protocol");
|
||||
return ESP_HOSTED_SLAVE_OTA_FAILED;
|
||||
}
|
||||
|
||||
err = establish_wifi_connection();
|
||||
if (err != ESP_OK) {
|
||||
ESP_LOGE(TAG, "WiFi connection failed: %s", esp_err_to_name(err));
|
||||
return ESP_HOSTED_SLAVE_OTA_FAILED;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Starting HTTPS OTA from URL: %s", image_url);
|
||||
|
||||
#ifdef CONFIG_OTA_USE_SELF_SIGNED_CERT
|
||||
// Log certificate information for self-signed mode
|
||||
size_t cert_len = server_cert_pem_end - server_cert_pem_start;
|
||||
ESP_LOGI(TAG, "Security: Self-signed certificate (Testing mode)");
|
||||
ESP_LOGI(TAG, "Certificate size: %u bytes", (unsigned int)cert_len);
|
||||
|
||||
if (cert_len == 0) {
|
||||
ESP_LOGE(TAG, "Certificate not embedded properly! Check CMakeLists.txt");
|
||||
return ESP_HOSTED_SLAVE_OTA_FAILED;
|
||||
}
|
||||
#else
|
||||
ESP_LOGI(TAG, "Security: CA Certificate Bundle (Production mode)");
|
||||
ESP_LOGI(TAG, "Supports: Let's Encrypt, DigiCert, and 200+ CAs");
|
||||
#endif
|
||||
|
||||
esp_http_client_config_t config = {
|
||||
.url = image_url,
|
||||
.timeout_ms = CONFIG_OTA_HTTPS_TIMEOUT_MS,
|
||||
.transport_type = HTTP_TRANSPORT_OVER_SSL, // Force HTTPS
|
||||
.event_handler = http_client_event_handler,
|
||||
.buffer_size = 8192, // Larger buffer for SSL
|
||||
.buffer_size_tx = 4096, // Increased TX buffer
|
||||
|
||||
#ifdef CONFIG_OTA_USE_SELF_SIGNED_CERT
|
||||
/* TESTING MODE - Self-signed certificate */
|
||||
.cert_pem = (const char *)server_cert_pem_start,
|
||||
.cert_len = server_cert_pem_end - server_cert_pem_start,
|
||||
.skip_cert_common_name_check = CONFIG_OTA_SKIP_CERT_CN_CHECK,
|
||||
.use_global_ca_store = false, // Use only our certificate
|
||||
#else
|
||||
/* PRODUCTION MODE - CA certificate bundle */
|
||||
.crt_bundle_attach = esp_crt_bundle_attach,
|
||||
.skip_cert_common_name_check = false, // Always validate CN in production
|
||||
#endif
|
||||
|
||||
.keep_alive_enable = true,
|
||||
.keep_alive_idle = 5,
|
||||
.keep_alive_interval = 5,
|
||||
.keep_alive_count = 3,
|
||||
};
|
||||
|
||||
esp_http_client_handle_t client = esp_http_client_init(&config);
|
||||
if (client == NULL) {
|
||||
ESP_LOGE(TAG, "Failed to initialize HTTPS client");
|
||||
return ESP_HOSTED_SLAVE_OTA_FAILED;
|
||||
}
|
||||
|
||||
/* Open connection */
|
||||
ESP_LOGI(TAG, "Opening HTTPS connection...");
|
||||
if ((err = esp_http_client_open(client, 0)) != ESP_OK) {
|
||||
ESP_LOGE(TAG, "Failed to open HTTPS connection: %s", esp_err_to_name(err));
|
||||
ESP_LOGE(TAG, "Common causes:");
|
||||
ESP_LOGE(TAG, " - Certificate CN doesn't match server IP");
|
||||
ESP_LOGE(TAG, " - Server not running or unreachable");
|
||||
ESP_LOGE(TAG, " - WiFi connection issues");
|
||||
ESP_LOGE(TAG, " - Firewall blocking port 8443");
|
||||
esp_http_client_cleanup(client);
|
||||
return ESP_HOSTED_SLAVE_OTA_FAILED;
|
||||
}
|
||||
|
||||
if (http_err) {
|
||||
ESP_LOGE(TAG, "Exiting OTA, due to http failure");
|
||||
esp_http_client_cleanup(client);
|
||||
http_err = 0;
|
||||
return ESP_HOSTED_SLAVE_OTA_FAILED;
|
||||
}
|
||||
|
||||
/* Fetch headers */
|
||||
ESP_LOGI(TAG, "Fetching HTTPS headers...");
|
||||
int64_t content_length = esp_http_client_fetch_headers(client);
|
||||
|
||||
int http_status = esp_http_client_get_status_code(client);
|
||||
if (http_status != 200) {
|
||||
ESP_LOGE(TAG, "HTTPS request failed with status: %d", http_status);
|
||||
esp_http_client_cleanup(client);
|
||||
return ESP_HOSTED_SLAVE_OTA_FAILED;
|
||||
}
|
||||
|
||||
if (content_length <= 0) {
|
||||
ESP_LOGE(TAG, "HTTP client fetch headers failed");
|
||||
ESP_LOGI(TAG, "HTTP GET Status = %d, content_length = %ld",
|
||||
esp_http_client_get_status_code(client),
|
||||
(long)esp_http_client_get_content_length(client));
|
||||
esp_http_client_close(client);
|
||||
esp_http_client_cleanup(client);
|
||||
return ESP_HOSTED_SLAVE_OTA_FAILED;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "HTTP GET Status = %d, content_length = %ld",
|
||||
esp_http_client_get_status_code(client),
|
||||
(long)esp_http_client_get_content_length(client));
|
||||
|
||||
/* Begin OTA */
|
||||
ESP_LOGI(TAG, "Preparing OTA");
|
||||
if ((err = esp_hosted_slave_ota_begin()) != ESP_OK) {
|
||||
ESP_LOGE(TAG, "esp_hosted_slave_ota_begin failed: %s", esp_err_to_name(err));
|
||||
ESP_LOGI(TAG, "esp_ota_begin failed, error=%s", esp_err_to_name(err));
|
||||
esp_http_client_close(client);
|
||||
esp_http_client_cleanup(client);
|
||||
return ESP_HOSTED_SLAVE_OTA_FAILED;
|
||||
}
|
||||
|
||||
ota_chunk = (uint8_t*)calloc(1, CHUNK_SIZE);
|
||||
if (!ota_chunk) {
|
||||
ESP_LOGE(TAG, "Failed to allocate OTA chunk memory");
|
||||
esp_http_client_close(client);
|
||||
esp_http_client_cleanup(client);
|
||||
return ESP_HOSTED_SLAVE_OTA_FAILED;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Starting OTA data transfer over HTTPS");
|
||||
|
||||
/* Read and write OTA data */
|
||||
bool header_verified = false;
|
||||
int chunk_count = 0;
|
||||
|
||||
while ((data_read = esp_http_client_read(client, (char*)ota_chunk, CHUNK_SIZE)) > 0) {
|
||||
ESP_LOGD(TAG, "Read image length %d", data_read);
|
||||
|
||||
/* Verify image header from the first chunk */
|
||||
if (!header_verified && chunk_count == 0) {
|
||||
size_t firmware_size;
|
||||
char app_version[32];
|
||||
|
||||
ESP_LOGI(TAG, "Verifying image header from first chunk (%d bytes)", data_read);
|
||||
if ((err = parse_image_header_from_buffer(ota_chunk, data_read, &firmware_size, app_version, sizeof(app_version))) != ESP_OK) {
|
||||
ESP_LOGE(TAG, "Image header verification failed: %s", esp_err_to_name(err));
|
||||
ota_failed = 1;
|
||||
break;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Image verified - Size: %u bytes, Version: %s", (unsigned int)firmware_size, app_version);
|
||||
|
||||
#ifdef CONFIG_OTA_VERSION_CHECK_SLAVEFW_SLAVE
|
||||
/* Get current running slave firmware version and compare */
|
||||
esp_hosted_coprocessor_fwver_t current_slave_version = {0};
|
||||
esp_err_t version_ret = esp_hosted_get_coprocessor_fwversion(¤t_slave_version);
|
||||
|
||||
if (version_ret == ESP_OK) {
|
||||
char current_version_str[32];
|
||||
snprintf(current_version_str, sizeof(current_version_str), "%" PRIu32 ".%" PRIu32 ".%" PRIu32,
|
||||
current_slave_version.major1, current_slave_version.minor1, current_slave_version.patch1);
|
||||
|
||||
ESP_LOGI(TAG, "Current slave firmware version: %s", current_version_str);
|
||||
ESP_LOGI(TAG, "New slave firmware version: %s", app_version);
|
||||
|
||||
if (strcmp(app_version, current_version_str) == 0) {
|
||||
ESP_LOGW(TAG, "Current slave firmware version (%s) is the same as new version (%s). Skipping OTA.",
|
||||
current_version_str, app_version);
|
||||
/* Cleanup and return success */
|
||||
free(ota_chunk);
|
||||
esp_http_client_close(client);
|
||||
esp_http_client_cleanup(client);
|
||||
return ESP_HOSTED_SLAVE_OTA_NOT_REQUIRED;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Version differs - proceeding with OTA from %s to %s", current_version_str, app_version);
|
||||
} else {
|
||||
ESP_LOGW(TAG, "Could not get current slave firmware version (error: %s), proceeding with OTA",
|
||||
esp_err_to_name(version_ret));
|
||||
}
|
||||
#else
|
||||
ESP_LOGI(TAG, "Version check disabled - proceeding with OTA (new firmware version: %s)", app_version);
|
||||
#endif
|
||||
|
||||
header_verified = true;
|
||||
}
|
||||
|
||||
if ((err = esp_hosted_slave_ota_write(ota_chunk, data_read)) != ESP_OK) {
|
||||
ESP_LOGE(TAG, "esp_hosted_slave_ota_write failed: %s", esp_err_to_name(err));
|
||||
ota_failed = 1;
|
||||
break;
|
||||
}
|
||||
|
||||
chunk_count++;
|
||||
}
|
||||
|
||||
/* Cleanup resources */
|
||||
free(ota_chunk);
|
||||
esp_http_client_close(client);
|
||||
esp_http_client_cleanup(client);
|
||||
|
||||
/* Check for read errors */
|
||||
if (data_read < 0) {
|
||||
ESP_LOGE(TAG, "Error: HTTPS data read error");
|
||||
ota_failed = 1;
|
||||
}
|
||||
|
||||
/* End OTA */
|
||||
if ((err = esp_hosted_slave_ota_end()) != ESP_OK) {
|
||||
ESP_LOGE(TAG, "esp_ota_end failed, error=%s", esp_err_to_name(err));
|
||||
return ESP_HOSTED_SLAVE_OTA_FAILED;
|
||||
}
|
||||
|
||||
/* Final result */
|
||||
if (ota_failed) {
|
||||
ESP_LOGE(TAG, "********* Slave OTA Failed *******************");
|
||||
return ESP_HOSTED_SLAVE_OTA_FAILED;
|
||||
} else {
|
||||
ESP_LOGI(TAG, "********* Slave OTA Complete *******************");
|
||||
return ESP_HOSTED_SLAVE_OTA_COMPLETED;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "esp_err.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @brief Perform HTTP OTA update
|
||||
*
|
||||
* @param url URL to download firmware from
|
||||
* @return esp_err_t ESP_OK on success
|
||||
*/
|
||||
esp_err_t ota_https_perform(const char* url);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,133 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
/* Miniature version of esp-idf example of Wi-Fi station,
|
||||
* <esp-idf>/examples/wifi/getting_started/station/main/station_example_main.c
|
||||
* */
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "freertos/event_groups.h"
|
||||
#include "esp_system.h"
|
||||
#include "esp_wifi.h"
|
||||
#include "esp_event.h"
|
||||
#include "esp_log.h"
|
||||
|
||||
#include "lwip/err.h"
|
||||
#include "lwip/sys.h"
|
||||
|
||||
#ifdef CONFIG_OTA_METHOD_HTTPS
|
||||
#include "nvs_flash.h"
|
||||
|
||||
static const char* TAG = "ota_https_wifi";
|
||||
|
||||
#define EXAMPLE_ESP_WIFI_SSID CONFIG_ESP_WIFI_SSID
|
||||
#define EXAMPLE_ESP_WIFI_PASS CONFIG_ESP_WIFI_PASSWORD
|
||||
#define EXAMPLE_ESP_MAXIMUM_RETRY CONFIG_ESP_MAXIMUM_RETRY
|
||||
|
||||
#define WIFI_CONNECTED_BIT BIT0
|
||||
#define WIFI_FAIL_BIT BIT1
|
||||
|
||||
/* FreeRTOS event group to signal when we are connected*/
|
||||
static EventGroupHandle_t s_wifi_event_group;
|
||||
|
||||
static int s_retry_num = 0;
|
||||
|
||||
|
||||
static void event_handler(void* arg, esp_event_base_t event_base,
|
||||
int32_t event_id, void* event_data)
|
||||
{
|
||||
if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
|
||||
esp_wifi_connect();
|
||||
} else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
|
||||
if (s_retry_num < EXAMPLE_ESP_MAXIMUM_RETRY) {
|
||||
esp_wifi_connect();
|
||||
s_retry_num++;
|
||||
ESP_LOGI(TAG, "retry to connect to the AP");
|
||||
} else {
|
||||
xEventGroupSetBits(s_wifi_event_group, WIFI_FAIL_BIT);
|
||||
}
|
||||
ESP_LOGI(TAG,"connect to the AP fail");
|
||||
} else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
|
||||
ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data;
|
||||
ESP_LOGI(TAG, "got ip:" IPSTR, IP2STR(&event->ip_info.ip));
|
||||
s_retry_num = 0;
|
||||
xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT);
|
||||
}
|
||||
}
|
||||
|
||||
void wifi_init_sta(void)
|
||||
{
|
||||
s_wifi_event_group = xEventGroupCreate();
|
||||
|
||||
esp_netif_init();
|
||||
|
||||
esp_event_loop_create_default();
|
||||
esp_netif_create_default_wifi_sta();
|
||||
|
||||
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
|
||||
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
|
||||
|
||||
esp_event_handler_instance_t instance_any_id;
|
||||
esp_event_handler_instance_t instance_got_ip;
|
||||
ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT,
|
||||
ESP_EVENT_ANY_ID,
|
||||
&event_handler,
|
||||
NULL,
|
||||
&instance_any_id));
|
||||
ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT,
|
||||
IP_EVENT_STA_GOT_IP,
|
||||
&event_handler,
|
||||
NULL,
|
||||
&instance_got_ip));
|
||||
|
||||
wifi_config_t wifi_config = {
|
||||
.sta = {
|
||||
.ssid = EXAMPLE_ESP_WIFI_SSID,
|
||||
.password = EXAMPLE_ESP_WIFI_PASS,
|
||||
},
|
||||
};
|
||||
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA) );
|
||||
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config) );
|
||||
ESP_ERROR_CHECK(esp_wifi_start() );
|
||||
|
||||
ESP_LOGI(TAG, "wifi_init_sta finished.");
|
||||
|
||||
/* Waiting until either the connection is established (WIFI_CONNECTED_BIT) or connection failed for the maximum
|
||||
* number of re-tries (WIFI_FAIL_BIT). The bits are set by event_handler() (see above) */
|
||||
EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group,
|
||||
WIFI_CONNECTED_BIT | WIFI_FAIL_BIT,
|
||||
pdFALSE,
|
||||
pdFALSE,
|
||||
portMAX_DELAY);
|
||||
|
||||
if (bits & WIFI_CONNECTED_BIT) {
|
||||
ESP_LOGI(TAG, "connected to ap SSID:%s password:%s",
|
||||
EXAMPLE_ESP_WIFI_SSID, EXAMPLE_ESP_WIFI_PASS);
|
||||
} else if (bits & WIFI_FAIL_BIT) {
|
||||
ESP_LOGI(TAG, "Failed to connect to SSID:%s, password:%s",
|
||||
EXAMPLE_ESP_WIFI_SSID, EXAMPLE_ESP_WIFI_PASS);
|
||||
} else {
|
||||
ESP_LOGE(TAG, "UNEXPECTED EVENT");
|
||||
}
|
||||
}
|
||||
|
||||
esp_err_t establish_wifi_connection(void)
|
||||
{
|
||||
ESP_LOGI(TAG, "ESP_WIFI_MODE_STA");
|
||||
wifi_init_sta();
|
||||
|
||||
EventBits_t bits = xEventGroupGetBits(s_wifi_event_group);
|
||||
if (bits & WIFI_CONNECTED_BIT) {
|
||||
return ESP_OK;
|
||||
} else if (bits & WIFI_FAIL_BIT) {
|
||||
ESP_LOGE(TAG, "WiFi connection failed after maximum retries");
|
||||
return ESP_FAIL;
|
||||
} else {
|
||||
ESP_LOGE(TAG, "WiFi connection in unexpected state");
|
||||
return ESP_ERR_INVALID_STATE;
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,66 @@
|
||||
# Test Server Tools
|
||||
|
||||
This directory contains tools for testing HTTPS OTA functionality with self-signed certificates.
|
||||
|
||||
## Files
|
||||
|
||||
- `create_self_signed_certs.sh` - Generates self-signed certificates for testing
|
||||
- `create_https_server.py` - Simple HTTPS server for serving OTA files
|
||||
- `README.md` - This file
|
||||
|
||||
## Quick Start
|
||||
|
||||
### 1. Generate Test Certificates
|
||||
|
||||
```bash
|
||||
cd test_server
|
||||
bash create_self_signed_certs.sh
|
||||
```
|
||||
|
||||
### 2. Start HTTPS Server
|
||||
|
||||
```bash
|
||||
cd test_server
|
||||
python3 create_https_server.py
|
||||
```
|
||||
|
||||
### 3. Configure ESP32
|
||||
|
||||
```bash
|
||||
# From project root
|
||||
eh.py menuconfig
|
||||
```
|
||||
|
||||
Enable in menuconfig:
|
||||
|
||||
- `Component config` → `HTTPS OTA Configuration` → `Use self-signed certificate (Testing Only)` → **YES**
|
||||
- Update `OTA Server URL` to the URL shown by the server
|
||||
|
||||
## Important Notes
|
||||
|
||||
- **Testing Only**: Self-signed certificates should only be used for testing
|
||||
- **Security**: For production, use proper CA-signed certificates
|
||||
- **IP Address**: The certificate is generated for your current IP address
|
||||
- **Regenerate**: If your IP changes, regenerate certificates
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Certificate not found error
|
||||
|
||||
```bash
|
||||
# Make sure you're in test_server directory
|
||||
cd test_server
|
||||
bash create_self_signed_certs.sh
|
||||
```
|
||||
|
||||
### Server won't start
|
||||
|
||||
- Check if port 8443 is available
|
||||
- Ensure certificates exist in `../certs/`
|
||||
|
||||
```
|
||||
ls ../certs/
|
||||
server_cert.pem server_key.pem
|
||||
```
|
||||
|
||||
- Run from `test_server/` directory
|
||||
@@ -0,0 +1,79 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
import http.server
|
||||
import ssl
|
||||
import socket
|
||||
import os
|
||||
import sys
|
||||
|
||||
def get_local_ip():
|
||||
"""Get the local IP address of this machine"""
|
||||
try:
|
||||
# Connect to a remote address (doesn't actually send data)
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
|
||||
s.connect(("8.8.8.8", 80))
|
||||
return s.getsockname()[0]
|
||||
except Exception:
|
||||
return "127.0.0.1"
|
||||
|
||||
# Check if certificates exist (relative to component certs)
|
||||
cert_path = '../certs/server_cert.pem'
|
||||
key_path = '../certs/server_key.pem'
|
||||
|
||||
if not os.path.exists(cert_path) or not os.path.exists(key_path):
|
||||
print("ERROR: Certificates not found!")
|
||||
print(f"Please run: bash create_self_signed_certs.sh")
|
||||
print(f"Looking for: {cert_path} and {key_path}")
|
||||
print(f"Note: Run this server from components/ota_https/test_server/ directory")
|
||||
sys.exit(1)
|
||||
|
||||
# Get local IP
|
||||
local_ip = get_local_ip()
|
||||
port = 8443
|
||||
|
||||
# Create HTTPS server
|
||||
class CORSHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
|
||||
def end_headers(self):
|
||||
self.send_header('Access-Control-Allow-Origin', '*')
|
||||
self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
|
||||
self.send_header('Access-Control-Allow-Headers', '*')
|
||||
super().end_headers()
|
||||
|
||||
def log_message(self, format, *args):
|
||||
"""Enhanced logging"""
|
||||
print(f"[{self.date_time_string()}] {format % args}")
|
||||
|
||||
server_address = ('0.0.0.0', port)
|
||||
httpd = http.server.HTTPServer(server_address, CORSHTTPRequestHandler)
|
||||
|
||||
# Configure SSL with proper settings for ESP32
|
||||
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
ssl_context.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
ssl_context.set_ciphers('ECDHE+AESGCM:ECDHE+CHACHA20:DHE+AESGCM:DHE+CHACHA20:!aNULL:!MD5:!DSS')
|
||||
ssl_context.load_cert_chain(cert_path, key_path)
|
||||
|
||||
# Wrap socket with SSL
|
||||
httpd.socket = ssl_context.wrap_socket(httpd.socket, server_side=True)
|
||||
|
||||
print("=" * 60)
|
||||
print("HTTPS OTA Server Started Successfully!")
|
||||
print("=" * 60)
|
||||
print(f"Server running on: https://{local_ip}:{port}")
|
||||
print(f"Serving files from: {os.getcwd()}")
|
||||
print(f"Using certificates:")
|
||||
print(f" Cert: {cert_path}")
|
||||
print(f" Key: {key_path}")
|
||||
print("")
|
||||
print("ESP32 Configuration:")
|
||||
print(f" Set OTA_HTTP_URL to: https://{local_ip}:{port}/firmware.bin")
|
||||
print("")
|
||||
print("To test, place your firmware.bin file in this directory")
|
||||
print("Press Ctrl+C to stop the server")
|
||||
print("=" * 60)
|
||||
|
||||
try:
|
||||
httpd.serve_forever()
|
||||
except KeyboardInterrupt:
|
||||
print("\n🛑 Server stopped by user")
|
||||
httpd.server_close()
|
||||
@@ -0,0 +1,55 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Create certificates for HTTPS OTA testing
|
||||
# This script should be run from the component's test_server directory
|
||||
|
||||
# Create a directory for certificates in the component's certs folder
|
||||
mkdir -p ../certs
|
||||
cd ../certs
|
||||
|
||||
# Get your machine's IP address
|
||||
IP_ADDRESS=$(ipconfig getifaddr en0 2>/dev/null || ipconfig getifaddr en1 2>/dev/null || echo "192.168.1.100")
|
||||
echo "Creating certificate for IP: $IP_ADDRESS"
|
||||
echo "If this IP is incorrect, please update the CN field manually"
|
||||
|
||||
# Generate private key
|
||||
openssl genrsa -out server_key.pem 2048
|
||||
|
||||
# Generate self-signed certificate (valid for 365 days)
|
||||
# Use your actual IP address as Common Name
|
||||
openssl req -new -x509 -key server_key.pem -out server_cert.pem -days 365 \
|
||||
-subj "/C=US/ST=State/L=City/O=ESP-OTA/CN=$IP_ADDRESS" \
|
||||
-extensions v3_req \
|
||||
-config <(cat <<EOF
|
||||
[req]
|
||||
distinguished_name = req_distinguished_name
|
||||
req_extensions = v3_req
|
||||
prompt = no
|
||||
|
||||
[req_distinguished_name]
|
||||
C = US
|
||||
ST = State
|
||||
L = City
|
||||
O = ESP-OTA
|
||||
CN = $IP_ADDRESS
|
||||
|
||||
[v3_req]
|
||||
basicConstraints = CA:FALSE
|
||||
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
|
||||
subjectAltName = @alt_names
|
||||
|
||||
[alt_names]
|
||||
IP.1 = $IP_ADDRESS
|
||||
IP.2 = 127.0.0.1
|
||||
DNS.1 = localhost
|
||||
EOF
|
||||
)
|
||||
|
||||
# View certificate details
|
||||
echo "Certificate created with the following details:"
|
||||
openssl x509 -in server_cert.pem -text -noout | grep -A 5 "Subject:"
|
||||
openssl x509 -in server_cert.pem -text -noout | grep -A 10 "Subject Alternative Name"
|
||||
|
||||
echo ""
|
||||
echo "IMPORTANT: Your HTTPS server must run on IP: $IP_ADDRESS"
|
||||
echo "Update your Kconfig OTA_HTTP_URL to: https://$IP_ADDRESS:8443/firmware.bin"
|
||||
@@ -0,0 +1,53 @@
|
||||
# LittleFS OTA Component CMakeLists.txt
|
||||
# This component handles LittleFS-based OTA updates
|
||||
|
||||
# Only process firmware files if LittleFS OTA is actually selected
|
||||
message(STATUS "🔍 LittleFS OTA: CONFIG_OTA_METHOD_LITTLEFS = ${CONFIG_OTA_METHOD_LITTLEFS}")
|
||||
if(CONFIG_OTA_METHOD_LITTLEFS)
|
||||
set(SRC_LIST "ota_littlefs.c")
|
||||
|
||||
# Check if we have any firmware files (just for early validation)
|
||||
file(GLOB SLAVE_FW_BIN_FILES "${CMAKE_CURRENT_SOURCE_DIR}/slave_fw_bin/*.bin")
|
||||
if(NOT SLAVE_FW_BIN_FILES)
|
||||
message(WARNING "🔴 LittleFS OTA: No .bin files found in slave_fw_bin directory!")
|
||||
endif()
|
||||
else()
|
||||
# LittleFS OTA not selected, skip firmware processing
|
||||
message(STATUS "LittleFS OTA: Not selected, skipping firmware processing")
|
||||
endif()
|
||||
|
||||
# Register the component
|
||||
idf_component_register(SRCS ${SRC_LIST}
|
||||
INCLUDE_DIRS "."
|
||||
PRIV_REQUIRES "littlefs" "esp_hosted" "bootloader_support" "esp_app_format")
|
||||
|
||||
# Create LittleFS partition image after component registration
|
||||
if(CONFIG_OTA_METHOD_LITTLEFS)
|
||||
set(TEMP_LITTLEFS_DIR "${CMAKE_CURRENT_BINARY_DIR}/temp_littlefs")
|
||||
|
||||
# Create a custom target that runs the common script to find newest firmware dynamically
|
||||
add_custom_target(prepare_littlefs_temp
|
||||
COMMAND ${CMAKE_COMMAND}
|
||||
-DSOURCE_COMPONENT_DIR=${CMAKE_CURRENT_SOURCE_DIR}
|
||||
-DBINARY_COMPONENT_DIR=${CMAKE_CURRENT_BINARY_DIR}
|
||||
-DCOMPONENT_NAME=LittleFS OTA
|
||||
-DOTA_ACTION=prepare_littlefs
|
||||
-P ${CMAKE_CURRENT_SOURCE_DIR}/../common_ota_scripts/find_newest_firmware.cmake
|
||||
COMMENT "LittleFS OTA: Dynamically finding and preparing newest firmware"
|
||||
VERBATIM
|
||||
)
|
||||
|
||||
# Make the target depend on all firmware files so it rebuilds when they change
|
||||
file(GLOB CURRENT_FIRMWARE_FILES "${CMAKE_CURRENT_SOURCE_DIR}/slave_fw_bin/*.bin")
|
||||
if(CURRENT_FIRMWARE_FILES)
|
||||
add_custom_target(firmware_files_dependency DEPENDS ${CURRENT_FIRMWARE_FILES})
|
||||
add_dependencies(prepare_littlefs_temp firmware_files_dependency)
|
||||
endif()
|
||||
|
||||
# Create the LittleFS partition image with proper dependency
|
||||
littlefs_create_partition_image(storage ${TEMP_LITTLEFS_DIR} FLASH_IN_PROJECT DEPENDS prepare_littlefs_temp)
|
||||
# No POST_BUILD cleanup of TEMP_LITTLEFS_DIR: attaching it to ${COMPONENT_LIB}
|
||||
# races the storage-image target (which reads that dir) under parallel ninja and
|
||||
# intermittently deletes it first. The dir lives in the build tree (cleaned on a
|
||||
# clean build), so leaving it is harmless.
|
||||
endif()
|
||||
@@ -0,0 +1,454 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2025-2026 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
/*
|
||||
* ESP-Hosted LittleFS OTA Component
|
||||
* ================================
|
||||
*
|
||||
* Reads ESP32 slave firmware from LittleFS filesystem and performs OTA update.
|
||||
*
|
||||
* FEATURES:
|
||||
* - Firmware validation (magic number, image header)
|
||||
* - Version checking against current slave firmware
|
||||
* - Chunked transfer to slave device
|
||||
* - Optional firmware file deletion after successful flash
|
||||
*
|
||||
* APIs USED:
|
||||
* - esp_hosted_get_coprocessor_fwversion() - Get slave firmware version
|
||||
* - esp_hosted_slave_ota_begin() - Initialize OTA session
|
||||
* - esp_hosted_slave_ota_write() - Transfer firmware chunks
|
||||
* - esp_hosted_slave_ota_end() - Finalize OTA session
|
||||
* - esp_hosted_slave_ota_activate() - (if current slave FW > v2.5.X only) - ** Called from main.c **
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <inttypes.h>
|
||||
#include <dirent.h>
|
||||
#include <sys/stat.h>
|
||||
#include "esp_log.h"
|
||||
#include "esp_err.h"
|
||||
#include "esp_littlefs.h"
|
||||
#include "esp_hosted_ota.h"
|
||||
#include <unistd.h>
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "esp_app_format.h"
|
||||
#include "esp_app_desc.h"
|
||||
#include "esp_hosted.h"
|
||||
#include "esp_hosted_api_types.h"
|
||||
|
||||
static const char* TAG = "ota_littlefs";
|
||||
|
||||
#ifndef CHUNK_SIZE
|
||||
/* 1500 + RPC envelope (~26B) > MAX_PAYLOAD_SIZE (1524) — see Drift B in
|
||||
* task list re: envelope size diff vs upstream. 1400 matches ota_https.c. */
|
||||
#define CHUNK_SIZE 1400
|
||||
#endif
|
||||
|
||||
/* Function to parse ESP32 image header and get firmware info from file */
|
||||
static esp_err_t parse_image_header_from_file(const char* file_path, size_t* firmware_size, char* app_version_str, size_t version_str_len)
|
||||
{
|
||||
FILE* file;
|
||||
esp_image_header_t image_header;
|
||||
esp_image_segment_header_t segment_header;
|
||||
esp_app_desc_t app_desc;
|
||||
size_t offset = 0;
|
||||
size_t total_size = 0;
|
||||
|
||||
file = fopen(file_path, "rb");
|
||||
if (file == NULL) {
|
||||
ESP_LOGE(TAG, "Failed to open firmware file for header verification: %s", file_path);
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
/* Read image header */
|
||||
if (fread(&image_header, sizeof(image_header), 1, file) != 1) {
|
||||
ESP_LOGE(TAG, "Failed to read image header from file");
|
||||
fclose(file);
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
/* Validate magic number */
|
||||
if (image_header.magic != ESP_IMAGE_HEADER_MAGIC) {
|
||||
ESP_LOGE(TAG, "Invalid image magic: 0x%" PRIx8 " (expected: 0x%" PRIx8 ")", image_header.magic, ESP_IMAGE_HEADER_MAGIC);
|
||||
ESP_LOGE(TAG, "This indicates the file is not a valid ESP32 firmware image!");
|
||||
ESP_LOGE(TAG, "Please ensure you have flashed the correct firmware binary to the LittleFS partition.");
|
||||
fclose(file);
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Image header: magic=0x%" PRIx8 ", segment_count=%" PRIu8 ", hash_appended=%" PRIu8,
|
||||
image_header.magic, image_header.segment_count, image_header.hash_appended);
|
||||
|
||||
/* Calculate total size by reading all segments */
|
||||
offset = sizeof(image_header);
|
||||
total_size = sizeof(image_header);
|
||||
|
||||
for (int i = 0; i < image_header.segment_count; i++) {
|
||||
/* Read segment header */
|
||||
if (fseek(file, offset, SEEK_SET) != 0 ||
|
||||
fread(&segment_header, sizeof(segment_header), 1, file) != 1) {
|
||||
ESP_LOGE(TAG, "Failed to read segment %d header", i);
|
||||
fclose(file);
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Segment %d: data_len=%" PRIu32 ", load_addr=0x%" PRIx32, i, segment_header.data_len, segment_header.load_addr);
|
||||
|
||||
/* Add segment header size + data size */
|
||||
total_size += sizeof(segment_header) + segment_header.data_len;
|
||||
offset += sizeof(segment_header) + segment_header.data_len;
|
||||
|
||||
/* Read app description from the first segment */
|
||||
if (i == 0) {
|
||||
size_t app_desc_offset = sizeof(image_header) + sizeof(segment_header);
|
||||
if (fseek(file, app_desc_offset, SEEK_SET) == 0 &&
|
||||
fread(&app_desc, sizeof(app_desc), 1, file) == 1) {
|
||||
strncpy(app_version_str, app_desc.version, version_str_len - 1);
|
||||
app_version_str[version_str_len - 1] = '\0';
|
||||
ESP_LOGI(TAG, "Found app description: version='%s', project_name='%s'",
|
||||
app_desc.version, app_desc.project_name);
|
||||
} else {
|
||||
ESP_LOGW(TAG, "Failed to read app description");
|
||||
strncpy(app_version_str, "unknown", version_str_len - 1);
|
||||
app_version_str[version_str_len - 1] = '\0';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Add padding to align to 16 bytes */
|
||||
size_t padding = (16 - (total_size % 16)) % 16;
|
||||
if (padding > 0) {
|
||||
ESP_LOGD(TAG, "Adding %u bytes of padding for alignment", (unsigned int)padding);
|
||||
total_size += padding;
|
||||
}
|
||||
|
||||
/* Add the checksum byte (always present) */
|
||||
total_size += 1;
|
||||
ESP_LOGD(TAG, "Added 1 byte for checksum");
|
||||
|
||||
/* Add SHA256 hash if appended */
|
||||
bool has_hash = (image_header.hash_appended == 1);
|
||||
if (has_hash) {
|
||||
total_size += 32; // SHA256 hash is 32 bytes
|
||||
ESP_LOGD(TAG, "Added 32 bytes for SHA256 hash (hash_appended=1)");
|
||||
} else {
|
||||
ESP_LOGD(TAG, "No SHA256 hash appended (hash_appended=0)");
|
||||
}
|
||||
|
||||
*firmware_size = total_size;
|
||||
ESP_LOGI(TAG, "Total image size: %u bytes", (unsigned int)*firmware_size);
|
||||
|
||||
fclose(file);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
/* Find latest firmware file in LittleFS */
|
||||
static esp_err_t find_latest_firmware(char* firmware_path, size_t max_len)
|
||||
{
|
||||
DIR *dir;
|
||||
struct dirent *entry;
|
||||
struct stat file_stat;
|
||||
char *latest_file = malloc(256); // Use heap instead of stack
|
||||
char *full_path = malloc(512); // Use heap for full path
|
||||
|
||||
if (!latest_file || !full_path) {
|
||||
ESP_LOGE(TAG, "Failed to allocate memory for file search");
|
||||
if (latest_file) free(latest_file);
|
||||
if (full_path) free(full_path);
|
||||
return ESP_ERR_NO_MEM;
|
||||
}
|
||||
|
||||
memset(latest_file, 0, 256);
|
||||
|
||||
dir = opendir("/littlefs");
|
||||
if (dir == NULL) {
|
||||
ESP_LOGE(TAG, "Failed to open /littlefs directory");
|
||||
free(latest_file);
|
||||
free(full_path);
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Successfully opened /littlefs directory");
|
||||
|
||||
/* Find the first .bin file (since timestamps might not be reliable in LittleFS) */
|
||||
while ((entry = readdir(dir)) != NULL) {
|
||||
ESP_LOGI(TAG, "Found file: %s", entry->d_name);
|
||||
if (strstr(entry->d_name, ".bin") != NULL) {
|
||||
ESP_LOGI(TAG, "Found .bin file: %s", entry->d_name);
|
||||
snprintf(full_path, 512, "/littlefs/%s", entry->d_name);
|
||||
|
||||
if (stat(full_path, &file_stat) == 0) {
|
||||
ESP_LOGI(TAG, "File stat successful for %s, size: %ld", entry->d_name, file_stat.st_size);
|
||||
/* Use the first .bin file found */
|
||||
strncpy(latest_file, entry->d_name, 255);
|
||||
latest_file[255] = '\0'; // Ensure null termination
|
||||
ESP_LOGI(TAG, "Using firmware file: %s", latest_file);
|
||||
break; // Use the first .bin file found
|
||||
} else {
|
||||
ESP_LOGW(TAG, "Failed to stat file: %s", full_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
closedir(dir);
|
||||
|
||||
ESP_LOGI(TAG, "Final latest_file: '%s', length: %d", latest_file, strlen(latest_file));
|
||||
|
||||
if (strlen(latest_file) == 0) {
|
||||
ESP_LOGE(TAG, "No valid .bin firmware files found in /littlefs directory!");
|
||||
ESP_LOGE(TAG, "Please ensure:");
|
||||
ESP_LOGE(TAG, " - The firmware binary has a .bin extension");
|
||||
ESP_LOGE(TAG, " - The binary is flashed to the 'storage' partition");
|
||||
ESP_LOGE(TAG, " - The binary is a valid ESP32 firmware image");
|
||||
ESP_LOGE(TAG, "Refer to documentation for partition table setup and flashing instructions.");
|
||||
free(latest_file);
|
||||
free(full_path);
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
// Ensure we don't overflow the destination buffer
|
||||
if (snprintf(firmware_path, max_len, "/littlefs/%s", latest_file) >= max_len) {
|
||||
ESP_LOGE(TAG, "Firmware path too long");
|
||||
free(latest_file);
|
||||
free(full_path);
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Found latest firmware: %s", firmware_path);
|
||||
|
||||
// Clean up allocated memory
|
||||
free(latest_file);
|
||||
free(full_path);
|
||||
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
/* Function to check if LittleFS partition has any files */
|
||||
static esp_err_t check_littlefs_files(void)
|
||||
{
|
||||
DIR *dir;
|
||||
struct dirent *entry;
|
||||
int file_count = 0;
|
||||
|
||||
dir = opendir("/littlefs");
|
||||
if (dir == NULL) {
|
||||
ESP_LOGE(TAG, "Failed to open /littlefs directory");
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Checking contents of /littlefs partition:");
|
||||
|
||||
while ((entry = readdir(dir)) != NULL) {
|
||||
/* Skip . and .. directories */
|
||||
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
file_count++;
|
||||
ESP_LOGI(TAG, " Found: %s", entry->d_name);
|
||||
}
|
||||
closedir(dir);
|
||||
|
||||
if (file_count == 0) {
|
||||
ESP_LOGW(TAG, "LittleFS partition is empty! No firmware files found.");
|
||||
ESP_LOGW(TAG, "Please ensure you have:");
|
||||
ESP_LOGW(TAG, " 1. Created a 'storage' partition in your partition table");
|
||||
ESP_LOGW(TAG, " 2. Flashed a firmware binary to the LittleFS partition");
|
||||
ESP_LOGW(TAG, " 3. Or used 'idf.py flash' with the firmware binary");
|
||||
ESP_LOGW(TAG, "Refer to the documentation for detailed setup instructions.");
|
||||
return ESP_ERR_NOT_FOUND;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Found %d file(s) in LittleFS partition", file_count);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
esp_err_t ota_littlefs_perform(bool delete_after_use)
|
||||
{
|
||||
char *firmware_path = malloc(256); // Use heap instead of stack
|
||||
FILE *firmware_file;
|
||||
uint8_t *chunk = malloc(CHUNK_SIZE); // Use heap for chunk buffer
|
||||
size_t bytes_read;
|
||||
esp_err_t ret = ESP_OK;
|
||||
|
||||
if (!firmware_path || !chunk) {
|
||||
ESP_LOGE(TAG, "Failed to allocate memory");
|
||||
if (firmware_path) free(firmware_path);
|
||||
if (chunk) free(chunk);
|
||||
return ESP_ERR_NO_MEM;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Starting LittleFS OTA process");
|
||||
|
||||
/* Initialize LittleFS */
|
||||
ESP_LOGI(TAG, "Initializing LittleFS filesystem");
|
||||
esp_vfs_littlefs_conf_t conf = {
|
||||
.base_path = "/littlefs",
|
||||
.partition_label = "storage",
|
||||
.format_if_mount_failed = true,
|
||||
.dont_mount = false,
|
||||
};
|
||||
|
||||
ret = esp_vfs_littlefs_register(&conf);
|
||||
if (ret != ESP_OK) {
|
||||
ESP_LOGE(TAG, "Failed to initialize LittleFS: %s", esp_err_to_name(ret));
|
||||
free(firmware_path);
|
||||
free(chunk);
|
||||
return ESP_HOSTED_SLAVE_OTA_FAILED;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "LittleFS filesystem registered successfully");
|
||||
|
||||
/* Check if LittleFS partition has any files */
|
||||
ret = check_littlefs_files();
|
||||
if (ret == ESP_ERR_NOT_FOUND) {
|
||||
ESP_LOGW(TAG, "OTA cannot proceed - no firmware files found in LittleFS partition");
|
||||
esp_vfs_littlefs_unregister("storage");
|
||||
free(firmware_path);
|
||||
free(chunk);
|
||||
return ESP_HOSTED_SLAVE_OTA_FAILED;
|
||||
} else if (ret != ESP_OK) {
|
||||
ESP_LOGE(TAG, "Failed to check LittleFS partition contents");
|
||||
esp_vfs_littlefs_unregister("storage");
|
||||
free(firmware_path);
|
||||
free(chunk);
|
||||
return ESP_HOSTED_SLAVE_OTA_FAILED;
|
||||
}
|
||||
|
||||
/* Get filesystem info */
|
||||
size_t total = 0, used = 0;
|
||||
ret = esp_littlefs_info("storage", &total, &used);
|
||||
if (ret != ESP_OK) {
|
||||
ESP_LOGW(TAG, "Failed to get LittleFS partition information (%s)", esp_err_to_name(ret));
|
||||
} else {
|
||||
ESP_LOGI(TAG, "LittleFS partition size: total: %d, used: %d", total, used);
|
||||
}
|
||||
|
||||
/* Find the latest firmware file */
|
||||
ESP_LOGI(TAG, "Searching for firmware files in LittleFS");
|
||||
ret = find_latest_firmware(firmware_path, 256);
|
||||
if (ret != ESP_OK) {
|
||||
ESP_LOGE(TAG, "Failed to find firmware file");
|
||||
esp_vfs_littlefs_unregister("storage");
|
||||
free(firmware_path);
|
||||
free(chunk);
|
||||
return ESP_HOSTED_SLAVE_OTA_FAILED;
|
||||
}
|
||||
ESP_LOGI(TAG, "Firmware file found: %s", firmware_path);
|
||||
|
||||
/* Verify image header and get firmware info */
|
||||
size_t firmware_size;
|
||||
char new_app_version[32];
|
||||
ret = parse_image_header_from_file(firmware_path, &firmware_size, new_app_version, sizeof(new_app_version));
|
||||
if (ret != ESP_OK) {
|
||||
ESP_LOGE(TAG, "Failed to parse image header: %s", esp_err_to_name(ret));
|
||||
esp_vfs_littlefs_unregister("storage");
|
||||
free(firmware_path);
|
||||
free(chunk);
|
||||
return ESP_HOSTED_SLAVE_OTA_FAILED;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Firmware verified - Size: %u bytes, Version: %s", (unsigned int)firmware_size, new_app_version);
|
||||
|
||||
#ifdef CONFIG_OTA_VERSION_CHECK_SLAVEFW_SLAVE
|
||||
/* Get current running slave firmware version */
|
||||
esp_hosted_coprocessor_fwver_t current_slave_version = {0};
|
||||
esp_err_t version_ret = esp_hosted_get_coprocessor_fwversion(¤t_slave_version);
|
||||
|
||||
if (version_ret == ESP_OK) {
|
||||
char current_version_str[32];
|
||||
snprintf(current_version_str, sizeof(current_version_str), "%" PRIu32 ".%" PRIu32 ".%" PRIu32,
|
||||
current_slave_version.major1, current_slave_version.minor1, current_slave_version.patch1);
|
||||
|
||||
ESP_LOGI(TAG, "Current slave firmware version: %s", current_version_str);
|
||||
ESP_LOGI(TAG, "New slave firmware version: %s", new_app_version);
|
||||
|
||||
if (strcmp(new_app_version, current_version_str) == 0) {
|
||||
ESP_LOGW(TAG, "Current slave firmware version (%s) is the same as new version (%s). Skipping OTA.",
|
||||
current_version_str, new_app_version);
|
||||
esp_vfs_littlefs_unregister("storage");
|
||||
free(firmware_path);
|
||||
free(chunk);
|
||||
return ESP_HOSTED_SLAVE_OTA_NOT_REQUIRED;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Version differs - proceeding with OTA from %s to %s", current_version_str, new_app_version);
|
||||
} else {
|
||||
ESP_LOGW(TAG, "Could not get current slave firmware version (error: %s), proceeding with OTA",
|
||||
esp_err_to_name(version_ret));
|
||||
}
|
||||
#else
|
||||
ESP_LOGI(TAG, "Version check disabled - proceeding with OTA (new firmware version: %s)", new_app_version);
|
||||
#endif
|
||||
|
||||
/* Open firmware file */
|
||||
firmware_file = fopen(firmware_path, "rb");
|
||||
if (firmware_file == NULL) {
|
||||
ESP_LOGE(TAG, "Failed to open firmware file: %s", firmware_path);
|
||||
esp_vfs_littlefs_unregister("storage");
|
||||
free(firmware_path);
|
||||
free(chunk);
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Starting OTA from LittleFS: %s", firmware_path);
|
||||
|
||||
/* Begin OTA */
|
||||
ret = esp_hosted_slave_ota_begin();
|
||||
if (ret != ESP_OK) {
|
||||
ESP_LOGE(TAG, "Failed to begin OTA: %s", esp_err_to_name(ret));
|
||||
fclose(firmware_file);
|
||||
esp_vfs_littlefs_unregister("storage");
|
||||
free(firmware_path);
|
||||
free(chunk);
|
||||
return ESP_HOSTED_SLAVE_OTA_FAILED;
|
||||
}
|
||||
|
||||
/* Write firmware in chunks */
|
||||
while ((bytes_read = fread(chunk, 1, CHUNK_SIZE, firmware_file)) > 0) {
|
||||
ret = esp_hosted_slave_ota_write(chunk, bytes_read);
|
||||
if (ret != ESP_OK) {
|
||||
ESP_LOGE(TAG, "Failed to write OTA chunk: %s", esp_err_to_name(ret));
|
||||
fclose(firmware_file);
|
||||
esp_vfs_littlefs_unregister("storage");
|
||||
free(firmware_path);
|
||||
free(chunk);
|
||||
return ESP_HOSTED_SLAVE_OTA_FAILED;
|
||||
}
|
||||
}
|
||||
|
||||
fclose(firmware_file);
|
||||
|
||||
/* End OTA */
|
||||
ret = esp_hosted_slave_ota_end();
|
||||
if (ret != ESP_OK) {
|
||||
ESP_LOGE(TAG, "Failed to end OTA: %s", esp_err_to_name(ret));
|
||||
esp_vfs_littlefs_unregister("storage");
|
||||
free(firmware_path);
|
||||
free(chunk);
|
||||
return ESP_HOSTED_SLAVE_OTA_FAILED;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "LittleFS OTA completed successfully");
|
||||
|
||||
/* Delete firmware file if requested */
|
||||
if (delete_after_use) {
|
||||
if (unlink(firmware_path) == 0) {
|
||||
ESP_LOGI(TAG, "Deleted firmware file: %s", firmware_path);
|
||||
} else {
|
||||
ESP_LOGW(TAG, "Failed to delete firmware file: %s", firmware_path);
|
||||
}
|
||||
}
|
||||
|
||||
esp_vfs_littlefs_unregister("storage");
|
||||
|
||||
/* Clean up allocated memory */
|
||||
free(firmware_path);
|
||||
free(chunk);
|
||||
|
||||
return ESP_HOSTED_SLAVE_OTA_COMPLETED;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "esp_err.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @brief Perform LittleFS OTA update
|
||||
*
|
||||
* @param delete_after_use Whether to delete firmware file after successful flash
|
||||
* @return esp_err_t ESP_OK on success
|
||||
*/
|
||||
esp_err_t ota_littlefs_perform(bool delete_after_use);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,3 @@
|
||||
# This directory should contain .bin firmware files for LittleFS OTA
|
||||
# Place your slave firmware binaries here before building
|
||||
# Git tracks this file to ensure the directory exists in the repository
|
||||
@@ -0,0 +1,29 @@
|
||||
# Slave Firmware Binaries for LittleFS OTA
|
||||
|
||||
This directory should contain ESP32 slave firmware `.bin` files for LittleFS-based OTA updates.
|
||||
|
||||
## Usage
|
||||
|
||||
1. Copy your slave firmware binary (e.g., `network_adapter.bin`) to this directory
|
||||
2. Build the project with `CONFIG_OTA_METHOD_LITTLEFS=y`
|
||||
3. The build system will automatically:
|
||||
- Find the newest `.bin` file in this directory
|
||||
- Create a LittleFS partition image containing the firmware
|
||||
- Flash it to the `storage` partition
|
||||
|
||||
## Important Notes
|
||||
|
||||
- Only `.bin` files are recognized
|
||||
- If multiple files exist, the newest one (by timestamp) is used
|
||||
- The firmware must be a valid ESP32 binary with proper image header
|
||||
- This directory is only used during build time, not runtime
|
||||
|
||||
## Example
|
||||
|
||||
```bash
|
||||
# Copy your slave firmware here
|
||||
cp /path/to/your/slave/build/network_adapter.bin ./slave_fw_bin/
|
||||
|
||||
# Then build the project
|
||||
eh.py -p <host_port> build flash monitor
|
||||
```
|
||||
@@ -0,0 +1,89 @@
|
||||
# Partition OTA Component CMakeLists.txt
|
||||
# This component handles Partition-based OTA updates
|
||||
|
||||
idf_component_register(
|
||||
SRCS "ota_partition.c"
|
||||
INCLUDE_DIRS "."
|
||||
PRIV_REQUIRES "esp_partition" "esp_hosted" "bootloader_support" "esp_app_format"
|
||||
)
|
||||
|
||||
if(CONFIG_OTA_METHOD_PARTITION)
|
||||
# --- Step 0: Get partition offset from partition table ---
|
||||
set(SLAVE_FW_PARTITION_NAME "slave_fw")
|
||||
file(READ "${CMAKE_SOURCE_DIR}/partitions.csv" PARTITION_TABLE_CONTENT)
|
||||
# Require comma immediately after the partition name so descriptive
|
||||
# comments containing "slave_fw" (e.g. the table-of-contents header) don't
|
||||
# accidentally match and capture "Offset" from the column-header row.
|
||||
string(REGEX MATCH "${SLAVE_FW_PARTITION_NAME},[^,]*,[^,]*,[ ]*([^,]*)" PARTITION_MATCH "${PARTITION_TABLE_CONTENT}")
|
||||
if(PARTITION_MATCH)
|
||||
string(REGEX REPLACE "${SLAVE_FW_PARTITION_NAME},[^,]*,[^,]*,[ ]*([^,]*)" "\\1" SLAVE_FW_OFFSET "${PARTITION_MATCH}")
|
||||
string(STRIP "${SLAVE_FW_OFFSET}" SLAVE_FW_OFFSET)
|
||||
message(STATUS "✅ Partition OTA: Found ${SLAVE_FW_PARTITION_NAME} partition at offset: ${SLAVE_FW_OFFSET}")
|
||||
else()
|
||||
set(SLAVE_FW_OFFSET "0x5F0000") # Fallback to hardcoded value
|
||||
message(WARNING "⚠️ Partition OTA: Could not find ${SLAVE_FW_PARTITION_NAME} in partitions.csv, using fallback offset: ${SLAVE_FW_OFFSET}")
|
||||
endif()
|
||||
|
||||
# --- Step 1: Check if firmware files exist (early validation) ---
|
||||
message(STATUS "🔍 Partition OTA: Checking for firmware files...")
|
||||
|
||||
file(GLOB SLAVE_FW_BIN_FILES "${CMAKE_CURRENT_SOURCE_DIR}/slave_fw_bin/*.bin")
|
||||
|
||||
if(SLAVE_FW_BIN_FILES)
|
||||
message(STATUS "✅ Partition OTA: Found firmware files for dynamic selection")
|
||||
|
||||
# Get Python and esptool path from IDF
|
||||
idf_build_get_property(PYTHON PYTHON)
|
||||
idf_build_get_property(ESPTOOL_PATH ESPTOOL_PATH)
|
||||
|
||||
# Create a target that dynamically selects the newest firmware
|
||||
add_custom_target(select_partition_firmware
|
||||
COMMAND ${CMAKE_COMMAND}
|
||||
-DSOURCE_COMPONENT_DIR=${CMAKE_CURRENT_SOURCE_DIR}
|
||||
-DBINARY_COMPONENT_DIR=${CMAKE_CURRENT_BINARY_DIR}
|
||||
-DCOMPONENT_NAME=Partition OTA
|
||||
-DOTA_ACTION=select_for_partition
|
||||
-P ${CMAKE_CURRENT_SOURCE_DIR}/../common_ota_scripts/find_newest_firmware.cmake
|
||||
COMMENT "Partition OTA: Dynamically selecting newest firmware"
|
||||
VERBATIM
|
||||
)
|
||||
|
||||
# Create a target that flashes the selected firmware
|
||||
add_custom_target(flash_slave_fw
|
||||
DEPENDS select_partition_firmware
|
||||
COMMAND ${CMAKE_COMMAND}
|
||||
-DBINARY_COMPONENT_DIR=${CMAKE_CURRENT_BINARY_DIR}
|
||||
-DSLAVE_FW_OFFSET=${SLAVE_FW_OFFSET}
|
||||
-DPYTHON=${PYTHON}
|
||||
-DCOMPONENT_NAME=Partition OTA
|
||||
-P ${CMAKE_CURRENT_SOURCE_DIR}/../common_ota_scripts/flash_selected_firmware.cmake
|
||||
COMMENT "Partition OTA: Flashing selected firmware to partition"
|
||||
VERBATIM
|
||||
)
|
||||
|
||||
# Make flash_slave_fw depend on the main project binary being built successfully
|
||||
idf_build_get_property(project_name PROJECT_NAME)
|
||||
add_dependencies(flash_slave_fw ${project_name}.elf)
|
||||
|
||||
# Add flash_slave_fw to the flash target only after successful build
|
||||
add_dependencies(flash flash_slave_fw)
|
||||
|
||||
else()
|
||||
message(WARNING "⚠️ Partition OTA: No .bin files found in slave_fw_bin directory. Nothing to flash.")
|
||||
|
||||
# Add warning target for flash command when no slave firmware present
|
||||
add_custom_target(warn_no_slave_fw
|
||||
COMMAND ${CMAKE_COMMAND} -E echo ""
|
||||
COMMAND ${CMAKE_COMMAND} -E echo "⚠️ WARNING: Partition OTA is enabled but no slave firmware found!"
|
||||
COMMAND ${CMAKE_COMMAND} -E echo " Expected: .bin files in components/ota_partition/slave_fw_bin/"
|
||||
COMMAND ${CMAKE_COMMAND} -E echo " Current flash will only flash the host application"
|
||||
COMMAND ${CMAKE_COMMAND} -E echo " The partition at ${SLAVE_FW_OFFSET} will not be flashed this time"
|
||||
COMMAND ${CMAKE_COMMAND} -E echo ""
|
||||
COMMENT "Warning: No slave firmware binaries found"
|
||||
VERBATIM
|
||||
)
|
||||
|
||||
# Make flash target show this warning
|
||||
add_dependencies(flash warn_no_slave_fw)
|
||||
endif()
|
||||
endif()
|
||||
@@ -0,0 +1,336 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2025-2026 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
/*
|
||||
* ESP-Hosted Partition OTA Component
|
||||
* =================================
|
||||
*
|
||||
* Reads ESP32 slave firmware from dedicated flash partition and performs OTA update.
|
||||
*
|
||||
* FEATURES:
|
||||
* - Firmware validation (magic number, image header)
|
||||
* - Version checking against current slave firmware
|
||||
* - Direct partition reading with chunked transfer
|
||||
* - Robust error handling for partition access issues
|
||||
*
|
||||
* APIs USED:
|
||||
* - esp_hosted_get_coprocessor_fwversion() - Get slave firmware version
|
||||
* - esp_hosted_slave_ota_begin() - Initialize OTA session
|
||||
* - esp_hosted_slave_ota_write() - Transfer firmware chunks
|
||||
* - esp_hosted_slave_ota_end() - Finalize OTA session
|
||||
* - esp_hosted_slave_ota_activate() - (if current slave FW > v2.5.X only) - ** Called from main.c **
|
||||
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <inttypes.h>
|
||||
#include "esp_log.h"
|
||||
#include "esp_err.h"
|
||||
#include "esp_partition.h"
|
||||
#include "esp_hosted_ota.h"
|
||||
#include "esp_app_format.h"
|
||||
#include "esp_app_desc.h"
|
||||
#include "esp_hosted.h"
|
||||
#include "esp_hosted_api_types.h"
|
||||
|
||||
static const char* TAG = "ota_partition";
|
||||
|
||||
#ifndef CHUNK_SIZE
|
||||
#define CHUNK_SIZE 1500
|
||||
#endif
|
||||
|
||||
/* Function to check if partition contains valid firmware data */
|
||||
static esp_err_t check_partition_has_firmware(const esp_partition_t* partition)
|
||||
{
|
||||
uint8_t buffer[256];
|
||||
esp_err_t ret;
|
||||
size_t total_checked = 0;
|
||||
size_t check_size = sizeof(buffer);
|
||||
|
||||
ESP_LOGI(TAG, "Checking if partition '%s' contains firmware data...", partition->label);
|
||||
|
||||
/* Check first 1KB of partition for any non-0xFF data */
|
||||
while (total_checked < 1024 && total_checked < partition->size) {
|
||||
check_size = (1024 - total_checked > sizeof(buffer)) ? sizeof(buffer) : (1024 - total_checked);
|
||||
|
||||
ret = esp_partition_read(partition, total_checked, buffer, check_size);
|
||||
if (ret != ESP_OK) {
|
||||
ESP_LOGE(TAG, "Failed to read partition data for validation: %s", esp_err_to_name(ret));
|
||||
return ret;
|
||||
}
|
||||
|
||||
/* Check if all bytes are 0xFF (empty partition) */
|
||||
bool all_ff = true;
|
||||
for (size_t i = 0; i < check_size; i++) {
|
||||
if (buffer[i] != 0xFF) {
|
||||
all_ff = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!all_ff) {
|
||||
ESP_LOGI(TAG, "Found non-empty data in partition at offset %u", (unsigned int)total_checked);
|
||||
return ESP_OK; /* Found some data */
|
||||
}
|
||||
|
||||
total_checked += check_size;
|
||||
}
|
||||
|
||||
if (total_checked >= 1024) {
|
||||
ESP_LOGW(TAG, "Partition appears to be empty or uninitialized (first 1KB is all 0xFF)!");
|
||||
ESP_LOGW(TAG, "");
|
||||
ESP_LOGW(TAG, "---- OPTION 1 ----");
|
||||
ESP_LOGW(TAG, "Keep Slave FW <here> and `idf.py fullclean` & `idf.py flash` again");
|
||||
ESP_LOGW(TAG, " - host_performs_slave_ota/");
|
||||
ESP_LOGW(TAG, " └── components/");
|
||||
ESP_LOGW(TAG, " └── ota_partition/ # Slave OTA using Host Partition method");
|
||||
ESP_LOGW(TAG, " └── slave_fw_bin/ # Put slave .bin files here");
|
||||
ESP_LOGW(TAG, "");
|
||||
ESP_LOGW(TAG, " OR");
|
||||
ESP_LOGW(TAG, "");
|
||||
ESP_LOGW(TAG, "---- OPTION 2 ----");
|
||||
ESP_LOGW(TAG, " 1. Create a '%s' partition in your host partition table", partition->label);
|
||||
ESP_LOGW(TAG, " 2. Flashed desired slave firmware binary to this partition using 'idf.py partition-table-flash && idf.py app-flash' or similar");
|
||||
return ESP_ERR_NOT_FOUND;
|
||||
}
|
||||
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
/* Function to parse ESP32 image header and get firmware info */
|
||||
static esp_err_t parse_image_header(const esp_partition_t* partition, size_t* firmware_size, char* app_version_str, size_t version_str_len)
|
||||
{
|
||||
esp_image_header_t image_header;
|
||||
esp_image_segment_header_t segment_header;
|
||||
esp_app_desc_t app_desc;
|
||||
esp_err_t ret;
|
||||
size_t offset = 0;
|
||||
size_t total_size = 0;
|
||||
|
||||
/* Read image header */
|
||||
ret = esp_partition_read(partition, offset, &image_header, sizeof(image_header));
|
||||
if (ret != ESP_OK) {
|
||||
ESP_LOGE(TAG, "Failed to read image header: %s", esp_err_to_name(ret));
|
||||
return ret;
|
||||
}
|
||||
|
||||
/* Validate magic number */
|
||||
if (image_header.magic != ESP_IMAGE_HEADER_MAGIC) {
|
||||
ESP_LOGE(TAG, "Invalid image magic: 0x%" PRIx8 " (expected: 0x%" PRIx8 ")", image_header.magic, ESP_IMAGE_HEADER_MAGIC);
|
||||
ESP_LOGE(TAG, "This indicates the partition does not contain a valid ESP32 firmware image!");
|
||||
ESP_LOGE(TAG, "Please ensure you have flashed firmware to the '%s' partition.", partition->label);
|
||||
ESP_LOGE(TAG, "Use 'idf.py partition-table-flash && idf.py flash' or similar command.");
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Image header: magic=0x%" PRIx8 ", segment_count=%" PRIu8 ", hash_appended=%" PRIu8,
|
||||
image_header.magic, image_header.segment_count, image_header.hash_appended);
|
||||
|
||||
/* Calculate total size by reading all segments */
|
||||
offset = sizeof(image_header);
|
||||
total_size = sizeof(image_header);
|
||||
|
||||
for (int i = 0; i < image_header.segment_count; i++) {
|
||||
/* Read segment header */
|
||||
ret = esp_partition_read(partition, offset, &segment_header, sizeof(segment_header));
|
||||
if (ret != ESP_OK) {
|
||||
ESP_LOGE(TAG, "Failed to read segment %d header: %s", i, esp_err_to_name(ret));
|
||||
return ret;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Segment %d: data_len=%" PRIu32 ", load_addr=0x%" PRIx32, i, segment_header.data_len, segment_header.load_addr);
|
||||
|
||||
/* Add segment header size + data size */
|
||||
total_size += sizeof(segment_header) + segment_header.data_len;
|
||||
offset += sizeof(segment_header) + segment_header.data_len;
|
||||
|
||||
/* Read app description from the first segment */
|
||||
if (i == 0) {
|
||||
size_t app_desc_offset = sizeof(image_header) + sizeof(segment_header);
|
||||
ret = esp_partition_read(partition, app_desc_offset, &app_desc, sizeof(app_desc));
|
||||
if (ret == ESP_OK) {
|
||||
strncpy(app_version_str, app_desc.version, version_str_len - 1);
|
||||
app_version_str[version_str_len - 1] = '\0';
|
||||
ESP_LOGI(TAG, "Found app description: version='%s', project_name='%s'",
|
||||
app_desc.version, app_desc.project_name);
|
||||
} else {
|
||||
ESP_LOGW(TAG, "Failed to read app description: %s", esp_err_to_name(ret));
|
||||
strncpy(app_version_str, "unknown", version_str_len - 1);
|
||||
app_version_str[version_str_len - 1] = '\0';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Add padding to align to 16 bytes */
|
||||
size_t padding = (16 - (total_size % 16)) % 16;
|
||||
if (padding > 0) {
|
||||
ESP_LOGD(TAG, "Adding %u bytes of padding for alignment", (unsigned int)padding);
|
||||
total_size += padding;
|
||||
}
|
||||
|
||||
/* Add the checksum byte (always present) */
|
||||
total_size += 1;
|
||||
ESP_LOGD(TAG, "Added 1 byte for checksum");
|
||||
|
||||
/* Add SHA256 hash if appended */
|
||||
bool has_hash = (image_header.hash_appended == 1);
|
||||
if (has_hash) {
|
||||
/* ESP-IDF pads to 16-byte alignment AFTER checksum, before hash */
|
||||
size_t hash_padding = (16 - (total_size % 16)) % 16;
|
||||
total_size += hash_padding;
|
||||
total_size += 32; // SHA256 hash is 32 bytes
|
||||
ESP_LOGD(TAG, "Added %u bytes padding + 32 bytes for SHA256 hash", (unsigned int)hash_padding);
|
||||
} else {
|
||||
ESP_LOGD(TAG, "No SHA256 hash appended (hash_appended=0)");
|
||||
}
|
||||
|
||||
*firmware_size = total_size;
|
||||
ESP_LOGI(TAG, "Total image size: %u bytes", (unsigned int)*firmware_size);
|
||||
|
||||
/* Debug: Read last 48 bytes to verify structure */
|
||||
uint8_t tail_data[48];
|
||||
size_t tail_offset = (total_size > 48) ? (total_size - 48) : 0;
|
||||
ret = esp_partition_read(partition, tail_offset, tail_data, 48);
|
||||
if (ret == ESP_OK) {
|
||||
ESP_LOGD(TAG, "Last 48 bytes of image (offset %u):", (unsigned int)tail_offset);
|
||||
ESP_LOG_BUFFER_HEX_LEVEL(TAG, tail_data, 48, ESP_LOG_DEBUG);
|
||||
}
|
||||
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
esp_err_t ota_partition_perform(const char* partition_label)
|
||||
{
|
||||
const esp_partition_t* partition;
|
||||
esp_err_t ret = ESP_OK;
|
||||
uint8_t chunk[CHUNK_SIZE];
|
||||
size_t bytes_read;
|
||||
size_t offset = 0;
|
||||
size_t firmware_size;
|
||||
char new_app_version[32];
|
||||
|
||||
ESP_LOGI(TAG, "Starting Partition OTA from partition: %s", partition_label);
|
||||
|
||||
/* Find the partition */
|
||||
partition = esp_partition_find_first(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_ANY, partition_label);
|
||||
if (partition == NULL) {
|
||||
ESP_LOGE(TAG, "Partition '%s' not found", partition_label);
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Found partition: %s, size: %" PRIu32 " bytes", partition->label, partition->size);
|
||||
|
||||
/* Check if partition contains any firmware data */
|
||||
ret = check_partition_has_firmware(partition);
|
||||
if (ret == ESP_ERR_NOT_FOUND) {
|
||||
ESP_LOGW(TAG, "OTA cannot proceed - partition appears to be empty or uninitialized");
|
||||
return ESP_HOSTED_SLAVE_OTA_FAILED;
|
||||
} else if (ret != ESP_OK) {
|
||||
ESP_LOGE(TAG, "Failed to check partition contents: %s", esp_err_to_name(ret));
|
||||
return ESP_HOSTED_SLAVE_OTA_FAILED;
|
||||
}
|
||||
|
||||
/* Parse image header to get firmware size and version */
|
||||
ret = parse_image_header(partition, &firmware_size, new_app_version, sizeof(new_app_version));
|
||||
if (ret != ESP_OK) {
|
||||
ESP_LOGE(TAG, "Failed to parse image header: %s", esp_err_to_name(ret));
|
||||
return ESP_HOSTED_SLAVE_OTA_FAILED;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Firmware verified - Size: %u bytes, Version: %s", (unsigned int)firmware_size, new_app_version);
|
||||
|
||||
#ifdef CONFIG_OTA_VERSION_CHECK_SLAVEFW_SLAVE
|
||||
/* Get current running slave firmware version */
|
||||
esp_hosted_coprocessor_fwver_t current_slave_version = {0};
|
||||
esp_err_t version_ret = esp_hosted_get_coprocessor_fwversion(¤t_slave_version);
|
||||
|
||||
if (version_ret == ESP_OK) {
|
||||
char current_version_str[32];
|
||||
snprintf(current_version_str, sizeof(current_version_str), "%" PRIu32 ".%" PRIu32 ".%" PRIu32,
|
||||
current_slave_version.major1, current_slave_version.minor1, current_slave_version.patch1);
|
||||
|
||||
ESP_LOGI(TAG, "Current slave firmware version: %s", current_version_str);
|
||||
ESP_LOGI(TAG, "New slave firmware version: %s", new_app_version);
|
||||
|
||||
if (strcmp(new_app_version, current_version_str) == 0) {
|
||||
ESP_LOGW(TAG, "Current slave firmware version (%s) is the same as new version (%s). Skipping OTA.",
|
||||
current_version_str, new_app_version);
|
||||
return ESP_HOSTED_SLAVE_OTA_NOT_REQUIRED;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Version differs - proceeding with OTA from %s to %s", current_version_str, new_app_version);
|
||||
} else {
|
||||
ESP_LOGW(TAG, "Could not get current slave firmware version (error: %s), proceeding with OTA",
|
||||
esp_err_to_name(version_ret));
|
||||
}
|
||||
#else
|
||||
ESP_LOGI(TAG, "Version check disabled - proceeding with OTA (new firmware version: %s)", new_app_version);
|
||||
#endif
|
||||
|
||||
/* Validate firmware size */
|
||||
if (firmware_size == 0) {
|
||||
ESP_LOGE(TAG, "Firmware size is 0, cannot proceed with OTA");
|
||||
return ESP_HOSTED_SLAVE_OTA_FAILED;
|
||||
}
|
||||
if (firmware_size > partition->size) {
|
||||
ESP_LOGE(TAG, "Firmware size (%u) exceeds partition size (%" PRIu32 ")", (unsigned int)firmware_size, partition->size);
|
||||
return ESP_HOSTED_SLAVE_OTA_FAILED;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Proceeding with OTA - Firmware size: %u bytes", (unsigned int)firmware_size);
|
||||
|
||||
/* Begin OTA */
|
||||
ret = esp_hosted_slave_ota_begin();
|
||||
if (ret != ESP_OK) {
|
||||
ESP_LOGE(TAG, "Failed to begin OTA: %s", esp_err_to_name(ret));
|
||||
return ESP_HOSTED_SLAVE_OTA_FAILED;
|
||||
}
|
||||
|
||||
/* Read firmware from partition in chunks - only up to actual firmware size */
|
||||
uint32_t total_bytes_sent = 0;
|
||||
uint32_t chunk_count = 0;
|
||||
|
||||
while (offset < firmware_size) {
|
||||
bytes_read = (firmware_size - offset > CHUNK_SIZE) ? CHUNK_SIZE : (firmware_size - offset);
|
||||
|
||||
ret = esp_partition_read(partition, offset, chunk, bytes_read);
|
||||
if (ret != ESP_OK) {
|
||||
ESP_LOGE(TAG, "Failed to read partition: %s", esp_err_to_name(ret));
|
||||
esp_hosted_slave_ota_end();
|
||||
return ESP_HOSTED_SLAVE_OTA_FAILED;
|
||||
}
|
||||
|
||||
ret = esp_hosted_slave_ota_write(chunk, bytes_read);
|
||||
if (ret != ESP_OK) {
|
||||
ESP_LOGE(TAG, "Failed to write OTA chunk %" PRIu32 ": %s", chunk_count, esp_err_to_name(ret));
|
||||
esp_hosted_slave_ota_end();
|
||||
return ESP_HOSTED_SLAVE_OTA_FAILED;
|
||||
}
|
||||
|
||||
total_bytes_sent += bytes_read;
|
||||
offset += bytes_read;
|
||||
chunk_count++;
|
||||
|
||||
/* Progress indicator */
|
||||
if (chunk_count % 50 == 0) {
|
||||
ESP_LOGD(TAG, "Progress: %" PRIu32 "/%u bytes (%.1f%%)",
|
||||
total_bytes_sent, (unsigned int)firmware_size, (float)total_bytes_sent * 100 / firmware_size);
|
||||
}
|
||||
}
|
||||
|
||||
ESP_LOGD(TAG, "Total chunks sent: %" PRIu32 ", Total bytes sent: %" PRIu32, chunk_count, total_bytes_sent);
|
||||
|
||||
/* End OTA */
|
||||
ret = esp_hosted_slave_ota_end();
|
||||
if (ret != ESP_OK) {
|
||||
ESP_LOGE(TAG, "Failed to end OTA: %s", esp_err_to_name(ret));
|
||||
return ESP_HOSTED_SLAVE_OTA_FAILED;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Partition OTA completed successfully - Sent %u bytes", (unsigned int)firmware_size);
|
||||
return ESP_HOSTED_SLAVE_OTA_COMPLETED;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "esp_err.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @brief Perform Partition OTA update
|
||||
*
|
||||
* @param partition_label Label of the partition containing firmware
|
||||
* @return esp_err_t ESP_OK on success
|
||||
*/
|
||||
esp_err_t ota_partition_perform(const char* partition_label);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,3 @@
|
||||
# This directory should contain .bin firmware files for Partition OTA
|
||||
# Place your slave firmware binaries here before building
|
||||
# Git tracks this file to ensure the directory exists in the repository
|
||||
@@ -0,0 +1,34 @@
|
||||
# Slave Firmware Binaries for Partition OTA
|
||||
|
||||
This directory should contain ESP32 slave firmware `.bin` files for partition-based OTA updates.
|
||||
|
||||
## Usage
|
||||
|
||||
1. Copy your slave firmware binary (e.g., `network_adapter.bin`) to this directory
|
||||
2. Ensure your `partitions.csv` has a partition labeled `slave_fw` (or as configured in Kconfig)
|
||||
3. Build the project with `CONFIG_OTA_METHOD_PARTITION=y`
|
||||
4. The build system will automatically:
|
||||
- Find the newest `.bin` file in this directory
|
||||
- Flash it directly to the dedicated partition during `eh.py flash`
|
||||
|
||||
## Important Notes
|
||||
|
||||
- Only `.bin` files are recognized
|
||||
- If multiple files exist, the newest one (by timestamp) is used
|
||||
- The firmware must be a valid ESP32 binary with proper image header
|
||||
- This directory is only used during build time for flashing, not runtime
|
||||
- The partition must be defined in your partition table
|
||||
|
||||
## Example
|
||||
|
||||
```bash
|
||||
# Copy your slave firmware here
|
||||
cp /path/to/your/slave/build/network_adapter.bin ./slave_fw_bin/
|
||||
|
||||
# Ensure partitions.csv has something like:
|
||||
# slave_fw, data, 0x40, 0x5F0000, 0x200000,
|
||||
|
||||
# Then build and flash the project
|
||||
eh.py fullclean
|
||||
eh.py -p <host_port> build flash monitor
|
||||
```
|
||||
@@ -0,0 +1,14 @@
|
||||
# Simple component selection based on Kconfig
|
||||
if(CONFIG_EH_USE_LEGACY_API)
|
||||
set(_main_src "legacy/main.c")
|
||||
else()
|
||||
set(_main_src "main.c")
|
||||
endif()
|
||||
|
||||
# main.c #if-selects the header of the chosen OTA method's component. Kconfig
|
||||
# values are NOT available during component-requirements expansion, so require
|
||||
# all three method components unconditionally — main.c picks the one to use.
|
||||
idf_component_register(SRCS "${_main_src}"
|
||||
INCLUDE_DIRS "."
|
||||
REQUIRES esp_hosted console esp_timer
|
||||
PRIV_REQUIRES esp_app_format ota_https ota_littlefs ota_partition)
|
||||
@@ -0,0 +1,137 @@
|
||||
menu "ESP-Hosted Coprocessor OTA Config"
|
||||
|
||||
choice OTA_METHOD
|
||||
prompt "Select OTA Method"
|
||||
default OTA_METHOD_HTTPS
|
||||
help
|
||||
Choose the OTA method for updating slave firmware.
|
||||
|
||||
config OTA_METHOD_HTTPS
|
||||
bool "HTTP OTA"
|
||||
help
|
||||
Download firmware from HTTPS URL
|
||||
|
||||
config OTA_METHOD_LITTLEFS
|
||||
bool "LittleFS OTA"
|
||||
help
|
||||
Read firmware from LittleFS filesystem
|
||||
|
||||
config OTA_METHOD_PARTITION
|
||||
bool "Partition OTA"
|
||||
help
|
||||
Read firmware from dedicated partition
|
||||
|
||||
endchoice
|
||||
|
||||
########### OTA with Partition ########
|
||||
config OTA_PARTITION_LABEL
|
||||
string "Partition Label"
|
||||
depends on OTA_METHOD_PARTITION
|
||||
default "slave_fw"
|
||||
help
|
||||
Label of the partition containing firmware
|
||||
|
||||
########### OTA with Littlefs #########
|
||||
config OTA_DELETE_FILE_AFTER_FLASH
|
||||
depends on OTA_METHOD_LITTLEFS
|
||||
bool "Delete OTA file from LittleFS/FatFS etc, once finished"
|
||||
default y
|
||||
|
||||
########### OTA with HTTPS ############
|
||||
menu "WiFi Connection"
|
||||
depends on OTA_METHOD_HTTPS
|
||||
config ESP_WIFI_SSID
|
||||
string "WiFi SSID"
|
||||
default "MyWiFiSSID"
|
||||
help
|
||||
SSID (network name) for the example to connect to.
|
||||
|
||||
config ESP_WIFI_PASSWORD
|
||||
string "WiFi Password"
|
||||
default "MyWiFiPass@123"
|
||||
help
|
||||
WiFi password (WPA or WPA2) for the example to use.
|
||||
|
||||
config ESP_MAXIMUM_RETRY
|
||||
int "Maximum retry"
|
||||
default 5
|
||||
help
|
||||
Set the Maximum retry to avoid station reconnecting to the AP unlimited when the AP is really inexistent.
|
||||
|
||||
endmenu
|
||||
|
||||
menu "HTTPS OTA Configuration"
|
||||
depends on OTA_METHOD_HTTPS
|
||||
|
||||
config OTA_USE_SELF_SIGNED_CERT
|
||||
bool "Use self-signed certificate (Testing Only)"
|
||||
default n
|
||||
help
|
||||
Enable this ONLY for testing with self-signed certificates.
|
||||
Disable for production use with CA-signed certificates.
|
||||
|
||||
When enabled, the component will use an embedded certificate
|
||||
from certs/server_cert.pem for HTTPS validation.
|
||||
|
||||
When disabled, the component will use the ESP32 CA certificate
|
||||
bundle which supports major CAs like Let's Encrypt, DigiCert, etc.
|
||||
|
||||
config OTA_SKIP_CERT_CN_CHECK
|
||||
bool "Skip certificate Common Name check"
|
||||
depends on OTA_USE_SELF_SIGNED_CERT
|
||||
default n
|
||||
help
|
||||
Skip Common Name validation in self-signed certificates.
|
||||
Only enable if you cannot match the CN with your server IP/hostname.
|
||||
|
||||
WARNING: This reduces security. Use only for testing.
|
||||
|
||||
config OTA_HTTPS_TIMEOUT_MS
|
||||
int "HTTPS connection timeout (milliseconds)"
|
||||
default 30000
|
||||
range 5000 120000
|
||||
help
|
||||
Timeout for HTTPS connection and SSL handshake.
|
||||
Increase if you have slow network or server.
|
||||
|
||||
config OTA_SERVER_URL
|
||||
string "OTA Server URL"
|
||||
default "https://192.168.1.3:8443/firmware.bin"
|
||||
help
|
||||
HTTPS URL of the OTA firmware file.
|
||||
Must start with https://
|
||||
|
||||
endmenu
|
||||
|
||||
########### OTA Verification Options ############
|
||||
menu "OTA Verification Options"
|
||||
|
||||
config OTA_VERSION_CHECK_HOST_SLAVE
|
||||
bool "Host-Slave version compatibility check"
|
||||
default y
|
||||
help
|
||||
Check if host and slave firmware have compatible major.minor versions.
|
||||
If host is X.Y.Z and slave is A.B.C, warn if X.Y != A.B.
|
||||
|
||||
This ensures compatible API versions between host and slave.
|
||||
|
||||
config OTA_VERSION_CHECK_SLAVEFW_SLAVE
|
||||
bool "Skip OTA if slave firmware versions match"
|
||||
default y
|
||||
help
|
||||
Compare current running slave firmware version with new firmware version.
|
||||
Skip OTA if versions are identical to avoid unnecessary updates.
|
||||
|
||||
Disable this to force OTA even when versions match.
|
||||
|
||||
endmenu
|
||||
|
||||
config EH_USE_LEGACY_API
|
||||
bool "Use legacy esp_hosted_* compat-surface main"
|
||||
default n
|
||||
help
|
||||
Build the example from main/legacy/main.c (preserves the
|
||||
esp_hosted_* compat surface) instead of main/main.c (which
|
||||
uses native eh_host_* APIs).
|
||||
|
||||
endmenu
|
||||
@@ -0,0 +1,16 @@
|
||||
dependencies:
|
||||
cmd_nvs:
|
||||
path: ${IDF_PATH}/examples/system/console/advanced/components/cmd_nvs
|
||||
cmd_system:
|
||||
path: ${IDF_PATH}/examples/system/console/advanced/components/cmd_system
|
||||
espressif/esp_hosted:
|
||||
rules:
|
||||
- if: target in [esp32p4, esp32h2]
|
||||
version: '*'
|
||||
espressif/esp_wifi_remote:
|
||||
rules:
|
||||
- if: target in [esp32p4, esp32h2]
|
||||
- if: idf_version <6.1
|
||||
version: '>=1.3.1'
|
||||
joltwallet/littlefs:
|
||||
version: '*'
|
||||
@@ -0,0 +1,278 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2025-2026 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
/*
|
||||
* ESP-Hosted Slave OTA Example
|
||||
* ===========================
|
||||
*
|
||||
* This example demonstrates how to perform Over-The-Air (OTA) updates on the
|
||||
* ESP32 slave device (co-processor) from the ESP32 host device.
|
||||
*
|
||||
* SUPPORTED OTA METHODS:
|
||||
* ----------------------
|
||||
* 1. HTTPS OTA: Download firmware from remote HTTPS URL
|
||||
* 2. LittleFS OTA: Flash firmware stored in ESP32's LittleFS filesystem
|
||||
* 3. Partition OTA: Flash firmware stored in dedicated ESP32 partition
|
||||
*
|
||||
* VERSION CHECKING & VERIFICATIONS:
|
||||
* ---------------------------------
|
||||
* - Host-Slave Compatibility Check (optional, CONFIG_OTA_VERSION_CHECK_HOST_SLAVE):
|
||||
* Compares major.minor versions between host and slave ESP-Hosted stacks
|
||||
* Ensures API compatibility to prevent communication issues
|
||||
*
|
||||
* - Slave Firmware Version Check for Activate API:
|
||||
* Checks if slave supports esp_hosted_slave_ota_activate() (requires v2.6.0+)
|
||||
* API availability determined by: (major > 2) || (major == 2 && minor > 5)
|
||||
*
|
||||
* ESP-HOSTED OTA APIs USED:
|
||||
* -------------------------
|
||||
* Slave OTA APIs (embedded in OTA methods):
|
||||
* - esp_hosted_slave_ota_begin() - Initialize OTA session
|
||||
* - esp_hosted_slave_ota_write() - Write firmware chunks
|
||||
* - esp_hosted_slave_ota_end() - Finalize OTA session
|
||||
*
|
||||
* Slave OTA API (called from main.c):
|
||||
* - esp_hosted_slave_ota_activate() - Activate new firmware (only for current slave FW > v2.5.X)
|
||||
*
|
||||
* OTA METHOD API MAPPING:
|
||||
* -----------------------
|
||||
* ota_https_perform() -> Calls: begin() + write() + end()
|
||||
* ota_littlefs_perform() -> Calls: begin() + write() + end()
|
||||
* ota_partition_perform() -> Calls: begin() + write() + end()
|
||||
*
|
||||
* EXECUTION FLOW:
|
||||
* ---------------
|
||||
* 1. Initialize ESP-Hosted connection
|
||||
* 2. Check version compatibility (optional)
|
||||
* 3. Execute selected OTA method
|
||||
* 4. Conditionally activate new firmware
|
||||
* 5. Restart host for resync
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include <inttypes.h>
|
||||
#include "esp_log.h"
|
||||
#include "esp_system.h"
|
||||
#include "nvs_flash.h"
|
||||
#include "esp_event.h"
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "esp_err.h"
|
||||
#include "esp_hosted.h"
|
||||
#include "esp_hosted_ota.h"
|
||||
#include "esp_timer.h"
|
||||
#include "esp_app_desc.h"
|
||||
#include "esp_hosted_api_types.h"
|
||||
#include "esp_check.h"
|
||||
|
||||
#if CONFIG_OTA_METHOD_HTTPS
|
||||
#include "ota_https.h"
|
||||
#elif CONFIG_OTA_METHOD_LITTLEFS
|
||||
#include "ota_littlefs.h"
|
||||
#elif CONFIG_OTA_METHOD_PARTITION
|
||||
#include "ota_partition.h"
|
||||
#endif
|
||||
|
||||
static const char *TAG = "host_performs_slave_ota";
|
||||
|
||||
#ifdef CONFIG_OTA_VERSION_CHECK_HOST_SLAVE
|
||||
/**
|
||||
* @brief Compare host and slave firmware versions
|
||||
*
|
||||
* Compares major.minor versions only (ignoring patch level)
|
||||
*
|
||||
* @return 0 if versions match
|
||||
* -1 if host version > slave version (slave needs upgrade)
|
||||
* 1 if host version < slave version (host needs upgrade)
|
||||
*/
|
||||
static int compare_versions(uint32_t slave_version)
|
||||
{
|
||||
uint32_t host_version = ESP_HOSTED_VERSION_VAL(ESP_HOSTED_VERSION_MAJOR_1,
|
||||
ESP_HOSTED_VERSION_MINOR_1,
|
||||
ESP_HOSTED_VERSION_PATCH_1);
|
||||
|
||||
// Compare major.minor only (ignore patch level)
|
||||
slave_version &= 0xFFFFFF00;
|
||||
host_version &= 0xFFFFFF00;
|
||||
|
||||
if (host_version == slave_version) {
|
||||
return 0; // Versions match
|
||||
} else if (host_version > slave_version) {
|
||||
#ifndef CONFIG_ESP_HOSTED_FW_VERSION_MISMATCH_WARNING_SUPPRESS
|
||||
ESP_LOGW(TAG, "Version mismatch: Host [%u.%u.%u] > Co-proc [%u.%u.%u] ==> Upgrade co-proc to avoid RPC timeouts",
|
||||
ESP_HOSTED_VERSION_PRINTF_ARGS(host_version), ESP_HOSTED_VERSION_PRINTF_ARGS(slave_version));
|
||||
#endif
|
||||
return -1; // Host newer, slave needs upgrade
|
||||
} else {
|
||||
#ifndef CONFIG_ESP_HOSTED_FW_VERSION_MISMATCH_WARNING_SUPPRESS
|
||||
ESP_LOGW(TAG, "Version mismatch: Host [%u.%u.%u] < Co-proc [%u.%u.%u] ==> Upgrade host to avoid compatibility issues",
|
||||
ESP_HOSTED_VERSION_PRINTF_ARGS(host_version), ESP_HOSTED_VERSION_PRINTF_ARGS(slave_version));
|
||||
#endif
|
||||
return 1; // Slave newer, host needs upgrade
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Check if host and slave firmware versions are compatible
|
||||
*
|
||||
* @return 0 if versions are compatible (OTA not needed)
|
||||
* -1 if slave needs upgrade
|
||||
* 1 if host needs upgrade
|
||||
*/
|
||||
static int check_version_compatibility(void)
|
||||
{
|
||||
esp_hosted_coprocessor_fwver_t slave_version = {0};
|
||||
esp_err_t ret = esp_hosted_get_coprocessor_fwversion(&slave_version);
|
||||
|
||||
if (ret != ESP_OK) {
|
||||
ESP_LOGW(TAG, "Could not get slave firmware version (error: %s)", esp_err_to_name(ret));
|
||||
ESP_LOGW(TAG, "Proceeding without version compatibility check");
|
||||
return -1; // Assume upgrade needed
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Host firmware version: %d.%d.%d",
|
||||
ESP_HOSTED_VERSION_MAJOR_1, ESP_HOSTED_VERSION_MINOR_1, ESP_HOSTED_VERSION_PATCH_1);
|
||||
ESP_LOGI(TAG, "Slave firmware version: %" PRIu32 ".%" PRIu32 ".%" PRIu32,
|
||||
slave_version.major1, slave_version.minor1, slave_version.patch1);
|
||||
|
||||
uint32_t slave_ver = ESP_HOSTED_VERSION_VAL(slave_version.major1,
|
||||
slave_version.minor1,
|
||||
slave_version.patch1);
|
||||
return compare_versions(slave_ver);
|
||||
}
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @brief Execute OTA update based on configured method
|
||||
*
|
||||
* Supports three OTA methods:
|
||||
* - HTTPS: Download firmware from URL
|
||||
* - LittleFS: Flash firmware from filesystem
|
||||
* - Partition: Flash firmware from partition
|
||||
*
|
||||
* @return ESP_HOSTED_SLAVE_OTA_COMPLETED if successful
|
||||
* ESP_HOSTED_SLAVE_OTA_NOT_REQUIRED if not needed
|
||||
* Error code otherwise
|
||||
*/
|
||||
static int perform_slave_ota(void)
|
||||
{
|
||||
#if CONFIG_OTA_METHOD_HTTPS
|
||||
ESP_LOGW(TAG, "Starting OTA via HTTPS");
|
||||
ESP_LOGW(TAG, "URL: %s", CONFIG_OTA_SERVER_URL);
|
||||
return ota_https_perform(CONFIG_OTA_SERVER_URL);
|
||||
|
||||
#elif CONFIG_OTA_METHOD_LITTLEFS
|
||||
uint8_t delete_after_flash = 0;
|
||||
|
||||
ESP_LOGW(TAG, "Starting OTA via LittleFS");
|
||||
#ifdef CONFIG_OTA_DELETE_FILE_AFTER_FLASH
|
||||
delete_after_flash = 1;
|
||||
#endif
|
||||
return ota_littlefs_perform(delete_after_flash);
|
||||
|
||||
#elif CONFIG_OTA_METHOD_PARTITION
|
||||
ESP_LOGW(TAG, "Starting OTA via Partition");
|
||||
ESP_LOGW(TAG, "Partition label: %s", CONFIG_OTA_PARTITION_LABEL);
|
||||
return ota_partition_perform(CONFIG_OTA_PARTITION_LABEL);
|
||||
|
||||
#else
|
||||
ESP_LOGE(TAG, "No OTA method configured!");
|
||||
return ESP_FAIL;
|
||||
#endif
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Activate new firmware and restart host
|
||||
*
|
||||
* Checks if slave firmware supports activate API (v2.6.0+)
|
||||
* If supported, activates the new firmware
|
||||
* Then restarts the host to resync with slave
|
||||
*/
|
||||
static void activate_and_restart(void)
|
||||
{
|
||||
bool activate_supported = false;
|
||||
esp_hosted_coprocessor_fwver_t slave_version = {0};
|
||||
|
||||
// Check if activate API is available (v2.6.0+)
|
||||
if (esp_hosted_get_coprocessor_fwversion(&slave_version) == ESP_OK) {
|
||||
ESP_LOGI(TAG, "Slave firmware version: %" PRIu32 ".%" PRIu32 ".%" PRIu32,
|
||||
slave_version.major1, slave_version.minor1, slave_version.patch1);
|
||||
|
||||
if ((slave_version.major1 > 2) ||
|
||||
(slave_version.major1 == 2 && slave_version.minor1 > 5)) {
|
||||
activate_supported = true;
|
||||
}
|
||||
} else {
|
||||
ESP_LOGW(TAG, "Could not detect slave version");
|
||||
}
|
||||
|
||||
// Activate new firmware if supported
|
||||
if (activate_supported) {
|
||||
esp_err_t ret = esp_hosted_slave_ota_activate();
|
||||
if (ret == ESP_OK) {
|
||||
ESP_LOGI(TAG, "New firmware activated - slave will reboot");
|
||||
} else {
|
||||
ESP_LOGE(TAG, "Failed to activate firmware: %s", esp_err_to_name(ret));
|
||||
}
|
||||
} else {
|
||||
ESP_LOGI(TAG, "Activate API not supported (requires v2.6.0+)");
|
||||
}
|
||||
|
||||
// Restart host to resync with slave
|
||||
ESP_LOGW(TAG, "Restarting host to resync with slave...");
|
||||
|
||||
esp_err_t deinit_rc = esp_hosted_deinit();
|
||||
if (deinit_rc != ESP_OK) {
|
||||
ESP_LOGW(TAG, "esp_hosted_deinit failed before restart: %s",
|
||||
esp_err_to_name(deinit_rc));
|
||||
}
|
||||
|
||||
vTaskDelay(pdMS_TO_TICKS(2000));
|
||||
esp_restart();
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Main application entry point
|
||||
*
|
||||
* Flow:
|
||||
* 1. Initialize ESP-Hosted
|
||||
* 2. Check version compatibility (optional)
|
||||
* 3. Perform OTA if needed
|
||||
* 4. Activate and restart
|
||||
*/
|
||||
void app_main(void)
|
||||
{
|
||||
// Step 1: Initialize system
|
||||
ESP_LOGI(TAG, "Initializing ESP-Hosted...");
|
||||
ESP_ERROR_CHECK(nvs_flash_init());
|
||||
ESP_ERROR_CHECK(esp_event_loop_create_default());
|
||||
ESP_ERROR_CHECK(esp_hosted_init());
|
||||
ESP_ERROR_CHECK(esp_hosted_connect_to_slave());
|
||||
ESP_LOGI(TAG, "ESP-Hosted initialized successfully");
|
||||
|
||||
// Step 2: Check version compatibility (if enabled)
|
||||
#ifdef CONFIG_OTA_VERSION_CHECK_HOST_SLAVE
|
||||
int version_check = check_version_compatibility();
|
||||
if (version_check == 0) {
|
||||
ESP_LOGI(TAG, "Versions compatible - OTA not required");
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
|
||||
// Step 3: Perform OTA update
|
||||
ESP_LOGI(TAG, "Starting slave OTA update...");
|
||||
int ret = perform_slave_ota();
|
||||
|
||||
// Step 4: Handle OTA result
|
||||
if (ret == ESP_HOSTED_SLAVE_OTA_COMPLETED) {
|
||||
ESP_LOGI(TAG, "OTA completed successfully!");
|
||||
activate_and_restart();
|
||||
} else if (ret == ESP_HOSTED_SLAVE_OTA_NOT_REQUIRED) {
|
||||
ESP_LOGI(TAG, "OTA not required - slave firmware is up to date");
|
||||
} else {
|
||||
ESP_LOGE(TAG, "OTA failed with error: %s", esp_err_to_name(ret));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2025-2026 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
/* Native eh_host_* API; legacy compat under main/legacy/main.c. */
|
||||
|
||||
#include <stdio.h>
|
||||
#include <inttypes.h>
|
||||
#include "esp_log.h"
|
||||
#include "esp_system.h"
|
||||
#include "nvs_flash.h"
|
||||
#include "esp_event.h"
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "esp_err.h"
|
||||
#include "eh_host.h"
|
||||
#include "eh_host_core.h"
|
||||
#include "eh_host_cp_ota.h"
|
||||
#include "eh_host_api_types.h"
|
||||
#include "eh_host_sys.h"
|
||||
#include "esp_hosted_host_fw_ver.h"
|
||||
#include "esp_hosted_ota.h"
|
||||
#include "esp_timer.h"
|
||||
#include "esp_app_desc.h"
|
||||
#include "esp_check.h"
|
||||
|
||||
#if CONFIG_OTA_METHOD_HTTPS
|
||||
#include "ota_https.h"
|
||||
#elif CONFIG_OTA_METHOD_LITTLEFS
|
||||
#include "ota_littlefs.h"
|
||||
#elif CONFIG_OTA_METHOD_PARTITION
|
||||
#include "ota_partition.h"
|
||||
#endif
|
||||
|
||||
static const char *TAG = "host_performs_slave_ota";
|
||||
|
||||
#ifdef CONFIG_OTA_VERSION_CHECK_HOST_SLAVE
|
||||
/* 0 = match, -1 = host newer, 1 = slave newer. major.minor only. */
|
||||
static int compare_versions(uint32_t slave_version)
|
||||
{
|
||||
uint32_t host_version = ESP_HOSTED_VERSION_VAL(ESP_HOSTED_VERSION_MAJOR_1,
|
||||
ESP_HOSTED_VERSION_MINOR_1,
|
||||
ESP_HOSTED_VERSION_PATCH_1);
|
||||
|
||||
slave_version &= 0xFFFFFF00;
|
||||
host_version &= 0xFFFFFF00;
|
||||
|
||||
if (host_version == slave_version) {
|
||||
return 0;
|
||||
} else if (host_version > slave_version) {
|
||||
#ifndef CONFIG_ESP_HOSTED_FW_VERSION_MISMATCH_WARNING_SUPPRESS
|
||||
ESP_LOGW(TAG, "Version mismatch: Host [%u.%u.%u] > Co-proc [%u.%u.%u] ==> Upgrade co-proc to avoid RPC timeouts",
|
||||
ESP_HOSTED_VERSION_PRINTF_ARGS(host_version), ESP_HOSTED_VERSION_PRINTF_ARGS(slave_version));
|
||||
#endif
|
||||
return -1;
|
||||
} else {
|
||||
#ifndef CONFIG_ESP_HOSTED_FW_VERSION_MISMATCH_WARNING_SUPPRESS
|
||||
ESP_LOGW(TAG, "Version mismatch: Host [%u.%u.%u] < Co-proc [%u.%u.%u] ==> Upgrade host to avoid compatibility issues",
|
||||
ESP_HOSTED_VERSION_PRINTF_ARGS(host_version), ESP_HOSTED_VERSION_PRINTF_ARGS(slave_version));
|
||||
#endif
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
static int check_version_compatibility(void)
|
||||
{
|
||||
eh_host_coprocessor_fwver_t slave_version = {0};
|
||||
esp_err_t ret = eh_host_sys_get_cp_fw_version(&slave_version);
|
||||
|
||||
if (ret != ESP_OK) {
|
||||
ESP_LOGW(TAG, "Could not get slave firmware version (error: %s)", esp_err_to_name(ret));
|
||||
ESP_LOGW(TAG, "Proceeding without version compatibility check");
|
||||
return -1;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Host firmware version: %d.%d.%d",
|
||||
ESP_HOSTED_VERSION_MAJOR_1, ESP_HOSTED_VERSION_MINOR_1, ESP_HOSTED_VERSION_PATCH_1);
|
||||
ESP_LOGI(TAG, "Slave firmware version: %" PRIu32 ".%" PRIu32 ".%" PRIu32,
|
||||
slave_version.major1, slave_version.minor1, slave_version.patch1);
|
||||
|
||||
uint32_t slave_ver = ESP_HOSTED_VERSION_VAL(slave_version.major1,
|
||||
slave_version.minor1,
|
||||
slave_version.patch1);
|
||||
return compare_versions(slave_ver);
|
||||
}
|
||||
#endif
|
||||
|
||||
static int perform_slave_ota(void)
|
||||
{
|
||||
#if CONFIG_OTA_METHOD_HTTPS
|
||||
ESP_LOGW(TAG, "Starting OTA via HTTPS");
|
||||
ESP_LOGW(TAG, "URL: %s", CONFIG_OTA_SERVER_URL);
|
||||
return ota_https_perform(CONFIG_OTA_SERVER_URL);
|
||||
|
||||
#elif CONFIG_OTA_METHOD_LITTLEFS
|
||||
uint8_t delete_after_flash = 0;
|
||||
|
||||
ESP_LOGW(TAG, "Starting OTA via LittleFS");
|
||||
#ifdef CONFIG_OTA_DELETE_FILE_AFTER_FLASH
|
||||
delete_after_flash = 1;
|
||||
#endif
|
||||
return ota_littlefs_perform(delete_after_flash);
|
||||
|
||||
#elif CONFIG_OTA_METHOD_PARTITION
|
||||
ESP_LOGW(TAG, "Starting OTA via Partition");
|
||||
ESP_LOGW(TAG, "Partition label: %s", CONFIG_OTA_PARTITION_LABEL);
|
||||
return ota_partition_perform(CONFIG_OTA_PARTITION_LABEL);
|
||||
|
||||
#else
|
||||
ESP_LOGE(TAG, "No OTA method configured!");
|
||||
return ESP_FAIL;
|
||||
#endif
|
||||
}
|
||||
|
||||
/* Activates new firmware (slave v2.6.0+) and restarts host to resync. */
|
||||
static void activate_and_restart(void)
|
||||
{
|
||||
bool activate_supported = false;
|
||||
eh_host_coprocessor_fwver_t slave_version = {0};
|
||||
|
||||
if (eh_host_sys_get_cp_fw_version(&slave_version) == ESP_OK) {
|
||||
ESP_LOGI(TAG, "Slave firmware version: %" PRIu32 ".%" PRIu32 ".%" PRIu32,
|
||||
slave_version.major1, slave_version.minor1, slave_version.patch1);
|
||||
|
||||
if ((slave_version.major1 > 2) ||
|
||||
(slave_version.major1 == 2 && slave_version.minor1 > 5)) {
|
||||
activate_supported = true;
|
||||
}
|
||||
} else {
|
||||
ESP_LOGW(TAG, "Could not detect slave version");
|
||||
}
|
||||
|
||||
if (activate_supported) {
|
||||
esp_err_t ret = eh_host_cp_ota_activate();
|
||||
if (ret == ESP_OK) {
|
||||
ESP_LOGI(TAG, "New firmware activated - slave will reboot");
|
||||
} else {
|
||||
ESP_LOGE(TAG, "Failed to activate firmware: %s", esp_err_to_name(ret));
|
||||
}
|
||||
} else {
|
||||
ESP_LOGI(TAG, "Activate API not supported (requires v2.6.0+)");
|
||||
}
|
||||
|
||||
ESP_LOGW(TAG, "Restarting host to resync with slave...");
|
||||
|
||||
esp_err_t deinit_rc = eh_host_deinit();
|
||||
if (deinit_rc != ESP_OK) {
|
||||
ESP_LOGW(TAG, "eh_host_deinit failed before restart: %s",
|
||||
esp_err_to_name(deinit_rc));
|
||||
}
|
||||
|
||||
/* Must outlast the coprocessor's OTA_ACTIVATE_RESTART_TIMEOUT plus its
|
||||
* boot, measured at ~600 ms. Resetting it inside the pending-verify
|
||||
* window makes BOOTLOADER_APP_ROLLBACK revert the update, and the OTA
|
||||
* silently does not stick. */
|
||||
vTaskDelay(pdMS_TO_TICKS(2000));
|
||||
esp_restart();
|
||||
}
|
||||
|
||||
void app_main(void)
|
||||
{
|
||||
ESP_LOGI(TAG, "Initializing ESP-Hosted...");
|
||||
ESP_ERROR_CHECK(nvs_flash_init());
|
||||
ESP_ERROR_CHECK(esp_event_loop_create_default());
|
||||
ESP_ERROR_CHECK(eh_host_init(NULL));
|
||||
ESP_ERROR_CHECK(eh_host_connect_to_slave());
|
||||
ESP_LOGI(TAG, "ESP-Hosted initialized successfully");
|
||||
|
||||
#ifdef CONFIG_OTA_VERSION_CHECK_HOST_SLAVE
|
||||
int version_check = check_version_compatibility();
|
||||
if (version_check == 0) {
|
||||
ESP_LOGI(TAG, "Versions compatible - OTA not required");
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
|
||||
ESP_LOGI(TAG, "Starting slave OTA update...");
|
||||
int ret = perform_slave_ota();
|
||||
|
||||
if (ret == ESP_HOSTED_SLAVE_OTA_COMPLETED) {
|
||||
ESP_LOGI(TAG, "OTA completed successfully!");
|
||||
activate_and_restart();
|
||||
} else if (ret == ESP_HOSTED_SLAVE_OTA_NOT_REQUIRED) {
|
||||
ESP_LOGI(TAG, "OTA not required - slave firmware is up to date");
|
||||
} else {
|
||||
ESP_LOGE(TAG, "OTA failed with error: %s", esp_err_to_name(ret));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
# Universal partition table for all OTA methods (HTTPS / LittleFS / Partition).
|
||||
# Mirrors upstream esp_hosted/examples/host_performs_slave_ota/partitions.csv.
|
||||
#
|
||||
# Layout (8 MB flash, host = ESP32-P4):
|
||||
# nvs 16K — config / Wi-Fi credentials
|
||||
# otadata 8K — IDF OTA bookkeeping (which slot is active)
|
||||
# phy_init 4K — RF calibration data
|
||||
# ota_0 2M @ 0x010000 — host firmware A
|
||||
# ota_1 2M @ 0x210000 — host firmware B
|
||||
# storage 1920K @ 0x410000 — LittleFS partition (used by OTA_METHOD_LITTLEFS:
|
||||
# the host stages the slave .bin into this FS,
|
||||
# then streams it over RPC).
|
||||
# slave_fw 2M @ 0x5F0000 — raw partition (used by OTA_METHOD_PARTITION:
|
||||
# host reads slave .bin straight from flash).
|
||||
#
|
||||
# Name, Type, SubType, Offset, Size, Flags
|
||||
nvs, data, nvs, 0x9000, 16K,
|
||||
otadata, data, ota, 0xd000, 8K,
|
||||
phy_init, data, phy, 0xf000, 4K,
|
||||
ota_0, app, ota_0, 0x10000, 2M,
|
||||
ota_1, app, ota_1, 0x210000, 2M,
|
||||
storage, data, littlefs, 0x410000, 0x1E0000,
|
||||
slave_fw, data, 0x40, 0x5F0000, 0x200000,
|
||||
|
@@ -0,0 +1,23 @@
|
||||
# Coprocessor OTA Example — host (MCU)
|
||||
|
||||
# Role: HOST (MCU / ESP-IDF)
|
||||
CONFIG_ESP_HOSTED=y
|
||||
|
||||
CONFIG_ESP_HOSTED_HOST_FEAT_WIFI=y
|
||||
|
||||
# Custom partition table — ota_0/1 for HTTPS, storage for LittleFS, slave_fw for Partition.
|
||||
CONFIG_PARTITION_TABLE_CUSTOM=y
|
||||
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv"
|
||||
CONFIG_PARTITION_TABLE_FILENAME="partitions.csv"
|
||||
# 8MB replaced below
|
||||
|
||||
|
||||
CONFIG_FREERTOS_HZ=1000
|
||||
|
||||
# --- Waveshare ESP32-P4-Nano ---
|
||||
CONFIG_ESPTOOLPY_FLASHSIZE_16MB=y
|
||||
CONFIG_ESPTOOLPY_FLASHSIZE="16MB"
|
||||
CONFIG_ESP_CONSOLE_UART_DEFAULT=y
|
||||
CONFIG_SLAVE_IDF_TARGET_ESP32C6=y
|
||||
# C6 image comes from a raw flash partition (slave_fw), written at flash time
|
||||
CONFIG_OTA_METHOD_PARTITION=y
|
||||
Reference in new issue
Block a user