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,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"
|
||||
Reference in new issue
Block a user