ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
esp32_hosted_update.cpp
Go to the documentation of this file.
1#if defined(USE_ESP32_VARIANT_ESP32H2) || defined(USE_ESP32_VARIANT_ESP32P4)
6#include "esphome/core/log.h"
7#include <esp_image_format.h>
8#include <esp_app_desc.h>
9#include <esp_hosted.h>
10#include <esp_hosted_host_fw_ver.h>
11#include <esp_ota_ops.h>
12#include <esp_system.h>
13#include <esp_wifi.h>
14
15#ifdef USE_ESP32_HOSTED_HTTP_UPDATE
19#endif
20
21extern "C" {
22#include <esp_hosted_ota.h>
23}
24
26
27ESPHOME_LOG_TAG(TAG, "esp32_hosted.update");
28
29// The host rejects writes above its per-RPC payload limit before they reach the coprocessor
30constexpr size_t CHUNK_SIZE = EH_HOST_CP_OTA_CHUNK_MAX;
31// OTA begin blocks while the coprocessor erases its partition, end while it validates the image
32constexpr uint32_t OTA_WDT_TIMEOUT_MS = 60000;
33
34static esp_err_t ota_end_guarded() {
36 return esp_hosted_slave_ota_end(); // NOLINT
37}
38
39#ifdef USE_ESP32_HOSTED_HTTP_UPDATE
40// Interval/timeout IDs (uint32_t to avoid string comparison)
42#endif
43
44// Compile-time version string from esp_hosted_host_fw_ver.h macros
45#define STRINGIFY_(x) #x
46#define STRINGIFY(x) STRINGIFY_(x)
47static const char *const ESP_HOSTED_VERSION_STR = STRINGIFY(ESP_HOSTED_VERSION_MAJOR_1) "." STRINGIFY(
48 ESP_HOSTED_VERSION_MINOR_1) "." STRINGIFY(ESP_HOSTED_VERSION_PATCH_1);
49
50#ifdef USE_ESP32_HOSTED_HTTP_UPDATE
51// Parse an integer from str, advancing ptr past the number
52// Returns false if no digits were parsed
53static bool parse_int(const char *&ptr, int &value) {
54 char *end;
55 value = static_cast<int>(strtol(ptr, &end, 10));
56 if (end == ptr)
57 return false;
58 ptr = end;
59 return true;
60}
61
62// Parse version string "major.minor.patch" into components
63// Returns true if at least major.minor was parsed
64static bool parse_version(const std::string &version_str, int &major, int &minor, int &patch) {
65 major = minor = patch = 0;
66 const char *ptr = version_str.c_str();
67
68 if (!parse_int(ptr, major) || *ptr != '.')
69 return false;
70 ++ptr;
71 if (!parse_int(ptr, minor))
72 return false;
73 if (*ptr == '.')
74 parse_int(++ptr, patch);
75
76 return true;
77}
78
79// Compare two versions, returns:
80// -1 if v1 < v2
81// 0 if v1 == v2
82// 1 if v1 > v2
83static int compare_versions(int major1, int minor1, int patch1, int major2, int minor2, int patch2) {
84 if (major1 != major2)
85 return major1 < major2 ? -1 : 1;
86 if (minor1 != minor2)
87 return minor1 < minor2 ? -1 : 1;
88 if (patch1 != patch2)
89 return patch1 < patch2 ? -1 : 1;
90 return 0;
91}
92#endif
93
95 this->update_info_.title = "ESP32 Hosted Coprocessor";
96
97#ifndef USE_WIFI
98 // If WiFi is not present, connect to the coprocessor
99 esp_hosted_connect_to_slave(); // NOLINT
100#endif
101
102 // Get coprocessor version
103 esp_hosted_coprocessor_fwver_t ver_info;
104 if (esp_hosted_get_coprocessor_fwversion(&ver_info) == ESP_OK) {
105 // 16 bytes: "255.255.255" (11 chars) + null + safety margin
106 char buf[16];
107 snprintf(buf, sizeof(buf), "%" PRIu32 ".%" PRIu32 ".%" PRIu32, ver_info.major1, ver_info.minor1, ver_info.patch1);
108 this->update_info_.current_version = buf;
109 } else {
110 this->update_info_.current_version = "unknown";
111 }
112 ESP_LOGD(TAG, "Coprocessor version: %s", this->update_info_.current_version.c_str());
113
114#ifndef USE_ESP32_HOSTED_HTTP_UPDATE
115 // Embedded mode: get image version from embedded firmware
116 const int app_desc_offset = sizeof(esp_image_header_t) + sizeof(esp_image_segment_header_t);
117 if (this->firmware_size_ >= app_desc_offset + sizeof(esp_app_desc_t)) {
118 esp_app_desc_t *app_desc = (esp_app_desc_t *) (this->firmware_data_ + app_desc_offset);
119 if (app_desc->magic_word == ESP_APP_DESC_MAGIC_WORD) {
120 ESP_LOGD(TAG,
121 "ESP32 Hosted firmware:\n"
122 " Firmware version: %s\n"
123 " Project name: %s\n"
124 " Build date: %s\n"
125 " Build time: %s\n"
126 " IDF version: %s",
127 app_desc->version, app_desc->project_name, app_desc->date, app_desc->time, app_desc->idf_ver);
128 this->update_info_.latest_version = app_desc->version;
129 if (this->update_info_.latest_version != this->update_info_.current_version) {
131 } else {
133 }
134 } else {
135 ESP_LOGW(TAG, "Invalid app description magic word: 0x%08" PRIx32 " (expected 0x%08" PRIx32 ")",
136 app_desc->magic_word, static_cast<uint32_t>(ESP_APP_DESC_MAGIC_WORD));
138 }
139 } else {
140 ESP_LOGW(TAG, "Firmware too small to contain app description");
142 }
143
144 // Publish state
145 this->status_clear_error();
146 this->publish_state();
147 // Defer so the automation runs on the main loop after setup, not during App.setup()
149 this->defer([this]() { this->update_available_trigger_->trigger(this->update_info_); });
150 }
151#else
152 // HTTP mode: check every 10s until network is ready (max 6 attempts)
153 // Only if update interval is > 1 minute to avoid redundant checks
154 if (this->get_update_interval() > 60000) {
155 this->initial_check_remaining_ = 6;
156 this->set_interval(INITIAL_CHECK_INTERVAL_ID, 10000, [this]() {
157 bool connected = network::is_connected();
158 if (--this->initial_check_remaining_ == 0 || connected) {
159 this->cancel_interval(INITIAL_CHECK_INTERVAL_ID);
160 if (connected) {
161 this->check();
162 }
163 }
164 });
165 }
166#endif
167}
168
170 ESP_LOGCONFIG(TAG,
171 "ESP32 Hosted Update:\n"
172 " Host Library Version: %s\n"
173 " Coprocessor Version: %s\n"
174 " Latest Version: %s",
175 ESP_HOSTED_VERSION_STR, this->update_info_.current_version.c_str(),
176 this->update_info_.latest_version.c_str());
177#ifdef USE_ESP32_HOSTED_HTTP_UPDATE
178 ESP_LOGCONFIG(TAG,
179 " Mode: HTTP\n"
180 " Source URL: %s",
181 this->source_url_);
182#else
183 ESP_LOGCONFIG(TAG,
184 " Mode: Embedded\n"
185 " Firmware Size: %zu bytes",
186 this->firmware_size_);
187#endif
188}
189
191#ifdef USE_ESP32_HOSTED_HTTP_UPDATE
192 if (!network::is_connected()) {
193 ESP_LOGD(TAG, "Network not connected, skipping update check");
194 return;
195 }
196
197 if (!this->fetch_manifest_()) {
198 return;
199 }
200
201 const bool was_available = this->state_ == update::UPDATE_STATE_AVAILABLE;
202
203 // Compare versions
204 if (this->update_info_.latest_version.empty() ||
205 this->update_info_.latest_version == this->update_info_.current_version) {
207 } else {
209 }
210
211 this->update_info_.has_progress = false;
212 this->update_info_.progress = 0.0f;
213 this->status_clear_error();
214 this->publish_state();
215 if (this->state_ == update::UPDATE_STATE_AVAILABLE && !was_available && this->update_available_trigger_) {
216 this->update_available_trigger_->trigger(this->update_info_);
217 }
218#endif
219}
220
221#ifdef USE_ESP32_HOSTED_HTTP_UPDATE
223 ESP_LOGD(TAG, "Fetching manifest");
224
225 auto container = this->http_request_parent_->get(this->source_url_);
226 if (container == nullptr || container->status_code != 200) {
227 ESP_LOGE(TAG, "Failed to fetch manifest from %s", this->source_url_);
228 this->status_set_error(LOG_STR("Failed to fetch manifest"));
229 return false;
230 }
231
232 // Read manifest JSON into string (manifest is small, ~1KB max)
233 // NOTE: HttpContainer::read() has non-BSD socket semantics - see http_request.h
234 // Use http_read_loop_result() helper instead of checking return values directly
235 std::string json_str;
236 json_str.reserve(container->content_length);
237 uint8_t buf[256];
238 uint32_t last_data_time = millis();
239 const uint32_t read_timeout = this->http_request_parent_->get_timeout();
240 while (container->get_bytes_read() < container->content_length) {
241 int read_or_error = container->read(buf, sizeof(buf));
242 App.feed_wdt();
243 yield();
244 auto result =
245 http_request::http_read_loop_result(read_or_error, last_data_time, read_timeout, container->is_read_complete());
247 continue;
248 // Note: COMPLETE is currently unreachable since the loop condition checks bytes_read < content_length,
249 // but this is defensive code in case chunked transfer encoding support is added in the future.
251 break; // COMPLETE, ERROR, or TIMEOUT
252 json_str.append(reinterpret_cast<char *>(buf), read_or_error);
253 }
254 container->end();
255
256 // Parse JSON manifest
257 // Format: {"versions": [{"version": "2.7.0", "url": "...", "sha256": "..."}]}
258 // Only consider versions <= host library version to avoid compatibility issues
259 bool valid = json::parse_json(json_str, [this](JsonObject root) -> bool {
260 if (!root["versions"].is<JsonArray>()) {
261 ESP_LOGE(TAG, "Manifest does not contain 'versions' array");
262 return false;
263 }
264
265 JsonArray versions = root["versions"].as<JsonArray>();
266 if (versions.size() == 0) {
267 ESP_LOGE(TAG, "Manifest 'versions' array is empty");
268 return false;
269 }
270
271 // Find the highest version that is compatible with the host library
272 // (version <= host version to avoid upgrading coprocessor ahead of host)
273 int best_major = -1, best_minor = -1, best_patch = -1;
274 std::string best_version, best_url, best_sha256;
275
276 for (JsonObject entry : versions) {
277 if (!entry["version"].is<const char *>() || !entry["url"].is<const char *>() ||
278 !entry["sha256"].is<const char *>()) {
279 continue; // Skip malformed entries
280 }
281
282 std::string ver_str = entry["version"].as<std::string>();
283 int major, minor, patch;
284 if (!parse_version(ver_str, major, minor, patch)) {
285 ESP_LOGW(TAG, "Failed to parse version: %s", ver_str.c_str());
286 continue;
287 }
288
289 // Check if this version is compatible (not newer than host)
290 if (compare_versions(major, minor, patch, ESP_HOSTED_VERSION_MAJOR_1, ESP_HOSTED_VERSION_MINOR_1,
291 ESP_HOSTED_VERSION_PATCH_1) > 0) {
292 continue;
293 }
294
295 // Check if this is better than our current best
296 if (best_major < 0 || compare_versions(major, minor, patch, best_major, best_minor, best_patch) > 0) {
297 best_major = major;
298 best_minor = minor;
299 best_patch = patch;
300 best_version = ver_str;
301 best_url = entry["url"].as<std::string>();
302 best_sha256 = entry["sha256"].as<std::string>();
303 }
304 }
305
306 if (best_major < 0) {
307 ESP_LOGW(TAG, "No compatible firmware version found (host is %s)", ESP_HOSTED_VERSION_STR);
308 return false;
309 }
310
311 this->update_info_.latest_version = best_version;
312 this->firmware_url_ = best_url;
313
314 // Parse SHA256 hex string to bytes
315 if (!parse_hex(best_sha256, this->firmware_sha256_.data(), 32)) {
316 ESP_LOGE(TAG, "Invalid SHA256: %s", best_sha256.c_str());
317 return false;
318 }
319
320 ESP_LOGD(TAG, "Best compatible version: %s", this->update_info_.latest_version.c_str());
321
322 return true;
323 });
324
325 if (!valid) {
326 ESP_LOGE(TAG, "Failed to parse manifest JSON");
327 this->status_set_error(LOG_STR("Failed to parse manifest"));
328 return false;
329 }
330
331 return true;
332}
333
335 ESP_LOGI(TAG, "Downloading firmware");
336
337 auto container = this->http_request_parent_->get(this->firmware_url_);
338 if (container == nullptr || container->status_code != 200) {
339 ESP_LOGE(TAG, "Failed to fetch firmware");
340 this->status_set_error(LOG_STR("Failed to fetch firmware"));
341 return false;
342 }
343
344 size_t total_size = container->content_length;
345 ESP_LOGI(TAG, "Firmware size: %zu bytes", total_size);
346
347 // Begin OTA on coprocessor
348 esp_err_t err;
349 {
351 err = esp_hosted_slave_ota_begin(); // NOLINT
352 }
353 if (err != ESP_OK) {
354 ESP_LOGE(TAG, "Failed to begin OTA: %s", esp_err_to_name(err));
355 container->end();
356 this->status_set_error(LOG_STR("Failed to begin OTA"));
357 return false;
358 }
359
360 // Stream firmware to coprocessor while computing SHA256
361 // NOTE: HttpContainer::read() has non-BSD socket semantics - see http_request.h
362 // Use http_read_loop_result() helper instead of checking return values directly
363 sha256::SHA256 hasher;
364 hasher.init();
365
366 uint8_t buffer[CHUNK_SIZE];
367 uint32_t last_data_time = millis();
368 const uint32_t read_timeout = this->http_request_parent_->get_timeout();
369 while (container->get_bytes_read() < total_size) {
370 int read_or_error = container->read(buffer, sizeof(buffer));
371
372 // Feed watchdog and give other tasks a chance to run
373 App.feed_wdt();
374 yield();
375
376 auto result =
377 http_request::http_read_loop_result(read_or_error, last_data_time, read_timeout, container->is_read_complete());
379 continue;
380 // Note: COMPLETE is currently unreachable since the loop condition checks bytes_read < content_length,
381 // but this is defensive code in case chunked transfer encoding support is added in the future.
383 break;
386 ESP_LOGE(TAG, "Timeout reading firmware data");
387 } else {
388 ESP_LOGE(TAG, "Error reading firmware data: %d", read_or_error);
389 }
390 ota_end_guarded();
391 container->end();
392 this->status_set_error(LOG_STR("Download failed"));
393 return false;
394 }
395
396 hasher.add(buffer, read_or_error);
397 err = esp_hosted_slave_ota_write(buffer, read_or_error); // NOLINT
398 if (err != ESP_OK) {
399 ESP_LOGE(TAG, "Failed to write OTA data: %s", esp_err_to_name(err));
400 ota_end_guarded();
401 container->end();
402 this->status_set_error(LOG_STR("Failed to write OTA data"));
403 return false;
404 }
405 }
406 container->end();
407
408 // Verify SHA256
409 hasher.calculate();
410 if (!hasher.equals_bytes(this->firmware_sha256_.data())) {
411 ESP_LOGE(TAG, "SHA256 mismatch");
412 ota_end_guarded();
413 this->status_set_error(LOG_STR("SHA256 verification failed"));
414 return false;
415 }
416
417 ESP_LOGI(TAG, "SHA256 verified successfully");
418 return true;
419}
420#else
422 if (this->firmware_data_ == nullptr || this->firmware_size_ == 0) {
423 ESP_LOGE(TAG, "No firmware data available");
424 this->status_set_error(LOG_STR("No firmware data available"));
425 return false;
426 }
427
428 // Verify SHA256 before writing
429 sha256::SHA256 hasher;
430 hasher.init();
431 hasher.add(this->firmware_data_, this->firmware_size_);
432 hasher.calculate();
433 if (!hasher.equals_bytes(this->firmware_sha256_.data())) {
434 ESP_LOGE(TAG, "SHA256 mismatch");
435 this->status_set_error(LOG_STR("SHA256 verification failed"));
436 return false;
437 }
438
439 ESP_LOGI(TAG, "Starting OTA update (%zu bytes)", this->firmware_size_);
440
441 esp_err_t err;
442 {
444 err = esp_hosted_slave_ota_begin(); // NOLINT
445 }
446 if (err != ESP_OK) {
447 ESP_LOGE(TAG, "Failed to begin OTA: %s", esp_err_to_name(err));
448 this->status_set_error(LOG_STR("Failed to begin OTA"));
449 return false;
450 }
451
452 uint8_t chunk[CHUNK_SIZE];
453 const uint8_t *data_ptr = this->firmware_data_;
454 size_t remaining = this->firmware_size_;
455 while (remaining > 0) {
456 size_t chunk_size = std::min(remaining, static_cast<size_t>(CHUNK_SIZE));
457 memcpy(chunk, data_ptr, chunk_size);
458 err = esp_hosted_slave_ota_write(chunk, chunk_size); // NOLINT
459 if (err != ESP_OK) {
460 ESP_LOGE(TAG, "Failed to write OTA data: %s", esp_err_to_name(err));
461 ota_end_guarded();
462 this->status_set_error(LOG_STR("Failed to write OTA data"));
463 return false;
464 }
465 data_ptr += chunk_size;
466 remaining -= chunk_size;
467 App.feed_wdt();
468 }
469
470 return true;
471}
472#endif
473
475 if (this->state_ != update::UPDATE_STATE_AVAILABLE && !force) {
476 ESP_LOGW(TAG, "Update not available");
477 return;
478 }
479
480#ifdef USE_ESP32_HOSTED_HTTP_UPDATE
481 if (this->firmware_url_.empty()) {
482 ESP_LOGW(TAG, "No firmware URL available, run check first");
483 return;
484 }
485#endif
486
487 update::UpdateState prev_state = this->state_;
489 this->update_info_.has_progress = false;
490 this->publish_state();
491
492#ifdef USE_ESP32_HOSTED_HTTP_UPDATE
494#else
496#endif
497 {
498 this->state_ = prev_state;
499 this->publish_state();
500 return;
501 }
502
503 esp_err_t end_err = ota_end_guarded();
504 if (end_err != ESP_OK) {
505 ESP_LOGE(TAG, "Failed to end OTA: %s", esp_err_to_name(end_err));
506 this->state_ = prev_state;
507 this->status_set_error(LOG_STR("Failed to end OTA"));
508 this->publish_state();
509 return;
510 }
511
512 // Update state
513 ESP_LOGI(TAG, "OTA update successful");
515 this->status_clear_error();
516 this->publish_state();
517
518#ifdef USE_OTA_ROLLBACK
519 // Mark the host partition as valid before rebooting, in case the safe mode
520 // timer hasn't expired yet.
521 esp_ota_mark_app_valid_cancel_rollback();
522#endif
523
524 // Give the state publish time to reach the API clients, then restart both sides
525 ESP_LOGI(TAG, "Restarting in 1 second");
526 this->set_timeout(1000, []() {
527 // Shut the host down while the coprocessor still answers; activate makes it
528 // reboot itself 500 ms later
529 App.safe_shutdown(TEARDOWN_TIMEOUT_REBOOT_MS);
530 esp_err_t err = esp_hosted_slave_ota_activate(); // NOLINT
531 if (err != ESP_OK) {
532 ESP_LOGE(TAG, "Failed to activate OTA: %s", esp_err_to_name(err));
533 }
534 // esp_wifi_remote registers esp_wifi_stop with esp_restart; that RPC to the
535 // rebooting coprocessor blocks until the task watchdog fires
536 esp_unregister_shutdown_handler(reinterpret_cast<shutdown_handler_t>(esp_wifi_stop));
537 arch_restart();
538 });
539}
540
541} // namespace esphome::esp32_hosted
542#endif
void feed_wdt()
Feed the task watchdog.
void safe_shutdown(uint32_t timeout_ms)
Run the safe shutdown hooks, give components up to timeout_ms to tear down, then run the powerdown ho...
bool cancel_interval(const char *name)
Cancel an interval function.
Definition component.cpp:92
void status_clear_error()
Definition component.h:315
void set_timeout(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a const char* name.
Definition component.cpp:96
void defer(const char *name, std::function< void()> &&f)
Defer a callback to the next loop() call with a const char* name.
void set_interval(const char *name, uint32_t interval, std::function< void()> &&f)
Set an interval function with a const char* name.
Definition component.cpp:88
bool equals_bytes(const uint8_t *expected)
Compare the hash against a provided byte-encoded hash.
Definition hash_base.h:32
virtual uint32_t get_update_interval() const
Get the update interval in ms of this sensor.
http_request::HttpRequestComponent * http_request_parent_
std::shared_ptr< HttpContainer > get(const char *url)
SHA256 hash implementation.
Definition sha256.h:51
void calculate() override
Definition sha256.cpp:27
void add(const uint8_t *data, size_t len) override
Definition sha256.cpp:25
void init() override
Definition sha256.cpp:19
std::unique_ptr< Trigger< const UpdateInfo & > > update_available_trigger_
void yield(void)
uint32_t buffer
Definition gif.cpp:50
constexpr uint32_t INITIAL_CHECK_INTERVAL_ID
ESPHOME_LOG_TAG(TAG, "esp32_hosted.update")
constexpr uint32_t OTA_WDT_TIMEOUT_MS
@ TIMEOUT
Timeout waiting for data, caller should exit loop.
@ COMPLETE
All content has been read, caller should exit loop.
@ RETRY
No data yet, already delayed, caller should continue loop.
@ DATA
Data was read, process it.
HttpReadLoopResult http_read_loop_result(int bytes_read_or_error, uint32_t &last_data_time, uint32_t timeout_ms, bool is_read_complete)
Process a read result with timeout tracking and delay handling.
bool parse_json(const std::string &data, const json_parse_t &f)
Parse a JSON string and run the provided json parse function if it's valid.
Definition json_util.cpp:28
ESPHOME_ALWAYS_INLINE bool is_connected()
Return whether the node is connected to the network (through wifi, eth, ...)
Definition util.h:36
uint32_t value
Definition hal.cpp:41
size_t parse_hex(const char *str, size_t length, uint8_t *data, size_t count)
Parse bytes from a hex-encoded string into a byte array.
Definition helpers.cpp:370
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
void arch_restart()
Definition hal.cpp:36
Application App
Global storage of Application pointer - only one Application can exist.
bool valid
static void uint32_t
uint8_t end[39]
Definition sun_gtil2.cpp:17