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:
jimmyandClaude Opus 5.5 committed 2026-11-24 13:52:12 +13:00
1 parent edf35e9c71
commit ba8e160aee
104 files changed
+8674 -204

No files matched your search

@@ -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(&current_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(&current_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(&current_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
```