ESPHome 2026.2.3
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
13#ifdef USE_ESP32_HOSTED_HTTP_UPDATE
17#endif
18
19extern "C" {
20#include <esp_hosted_ota.h>
21}
22
24
25static const char *const TAG = "esp32_hosted.update";
26
27// Older coprocessor firmware versions have a 1500-byte limit per RPC call
28constexpr size_t CHUNK_SIZE = 1500;
29
30#ifdef USE_ESP32_HOSTED_HTTP_UPDATE
31// Interval/timeout IDs (uint32_t to avoid string comparison)
32constexpr uint32_t INITIAL_CHECK_INTERVAL_ID = 0;
33#endif
34
35// Compile-time version string from esp_hosted_host_fw_ver.h macros
36#define STRINGIFY_(x) #x
37#define STRINGIFY(x) STRINGIFY_(x)
38static const char *const ESP_HOSTED_VERSION_STR = STRINGIFY(ESP_HOSTED_VERSION_MAJOR_1) "." STRINGIFY(
39 ESP_HOSTED_VERSION_MINOR_1) "." STRINGIFY(ESP_HOSTED_VERSION_PATCH_1);
40
41#ifdef USE_ESP32_HOSTED_HTTP_UPDATE
42// Parse an integer from str, advancing ptr past the number
43// Returns false if no digits were parsed
44static bool parse_int(const char *&ptr, int &value) {
45 char *end;
46 value = static_cast<int>(strtol(ptr, &end, 10));
47 if (end == ptr)
48 return false;
49 ptr = end;
50 return true;
51}
52
53// Parse version string "major.minor.patch" into components
54// Returns true if at least major.minor was parsed
55static bool parse_version(const std::string &version_str, int &major, int &minor, int &patch) {
56 major = minor = patch = 0;
57 const char *ptr = version_str.c_str();
58
59 if (!parse_int(ptr, major) || *ptr++ != '.' || !parse_int(ptr, minor))
60 return false;
61 if (*ptr == '.')
62 parse_int(++ptr, patch);
63
64 return true;
65}
66
67// Compare two versions, returns:
68// -1 if v1 < v2
69// 0 if v1 == v2
70// 1 if v1 > v2
71static int compare_versions(int major1, int minor1, int patch1, int major2, int minor2, int patch2) {
72 if (major1 != major2)
73 return major1 < major2 ? -1 : 1;
74 if (minor1 != minor2)
75 return minor1 < minor2 ? -1 : 1;
76 if (patch1 != patch2)
77 return patch1 < patch2 ? -1 : 1;
78 return 0;
79}
80#endif
81
83 this->update_info_.title = "ESP32 Hosted Coprocessor";
84
85#ifndef USE_WIFI
86 // If WiFi is not present, connect to the coprocessor
87 esp_hosted_connect_to_slave(); // NOLINT
88#endif
89
90 // Get coprocessor version
91 esp_hosted_coprocessor_fwver_t ver_info;
92 if (esp_hosted_get_coprocessor_fwversion(&ver_info) == ESP_OK) {
93 // 16 bytes: "255.255.255" (11 chars) + null + safety margin
94 char buf[16];
95 snprintf(buf, sizeof(buf), "%d.%d.%d", ver_info.major1, ver_info.minor1, ver_info.patch1);
96 this->update_info_.current_version = buf;
97 } else {
98 this->update_info_.current_version = "unknown";
99 }
100 ESP_LOGD(TAG, "Coprocessor version: %s", this->update_info_.current_version.c_str());
101
102#ifndef USE_ESP32_HOSTED_HTTP_UPDATE
103 // Embedded mode: get image version from embedded firmware
104 const int app_desc_offset = sizeof(esp_image_header_t) + sizeof(esp_image_segment_header_t);
105 if (this->firmware_size_ >= app_desc_offset + sizeof(esp_app_desc_t)) {
106 esp_app_desc_t *app_desc = (esp_app_desc_t *) (this->firmware_data_ + app_desc_offset);
107 if (app_desc->magic_word == ESP_APP_DESC_MAGIC_WORD) {
108 ESP_LOGD(TAG,
109 "Firmware version: %s\n"
110 "Project name: %s\n"
111 "Build date: %s\n"
112 "Build time: %s\n"
113 "IDF version: %s",
114 app_desc->version, app_desc->project_name, app_desc->date, app_desc->time, app_desc->idf_ver);
115 this->update_info_.latest_version = app_desc->version;
116 if (this->update_info_.latest_version != this->update_info_.current_version) {
118 } else {
120 }
121 } else {
122 ESP_LOGW(TAG, "Invalid app description magic word: 0x%08x (expected 0x%08x)", app_desc->magic_word,
123 ESP_APP_DESC_MAGIC_WORD);
125 }
126 } else {
127 ESP_LOGW(TAG, "Firmware too small to contain app description");
129 }
130
131 // Publish state
132 this->status_clear_error();
133 this->publish_state();
134#else
135 // HTTP mode: check every 10s until network is ready (max 6 attempts)
136 // Only if update interval is > 1 minute to avoid redundant checks
137 if (this->get_update_interval() > 60000) {
138 this->initial_check_remaining_ = 6;
139 this->set_interval(INITIAL_CHECK_INTERVAL_ID, 10000, [this]() {
140 bool connected = network::is_connected();
141 if (--this->initial_check_remaining_ == 0 || connected) {
142 this->cancel_interval(INITIAL_CHECK_INTERVAL_ID);
143 if (connected) {
144 this->check();
145 }
146 }
147 });
148 }
149#endif
150}
151
153 ESP_LOGCONFIG(TAG,
154 "ESP32 Hosted Update:\n"
155 " Host Library Version: %s\n"
156 " Coprocessor Version: %s\n"
157 " Latest Version: %s",
158 ESP_HOSTED_VERSION_STR, this->update_info_.current_version.c_str(),
159 this->update_info_.latest_version.c_str());
160#ifdef USE_ESP32_HOSTED_HTTP_UPDATE
161 ESP_LOGCONFIG(TAG,
162 " Mode: HTTP\n"
163 " Source URL: %s",
164 this->source_url_.c_str());
165#else
166 ESP_LOGCONFIG(TAG,
167 " Mode: Embedded\n"
168 " Firmware Size: %zu bytes",
169 this->firmware_size_);
170#endif
171}
172
174#ifdef USE_ESP32_HOSTED_HTTP_UPDATE
175 if (!network::is_connected()) {
176 ESP_LOGD(TAG, "Network not connected, skipping update check");
177 return;
178 }
179
180 if (!this->fetch_manifest_()) {
181 return;
182 }
183
184 // Compare versions
185 if (this->update_info_.latest_version.empty() ||
186 this->update_info_.latest_version == this->update_info_.current_version) {
188 } else {
190 }
191
192 this->update_info_.has_progress = false;
193 this->update_info_.progress = 0.0f;
194 this->status_clear_error();
195 this->publish_state();
196#endif
197}
198
199#ifdef USE_ESP32_HOSTED_HTTP_UPDATE
201 ESP_LOGD(TAG, "Fetching manifest");
202
203 auto container = this->http_request_parent_->get(this->source_url_);
204 if (container == nullptr || container->status_code != 200) {
205 ESP_LOGE(TAG, "Failed to fetch manifest from %s", this->source_url_.c_str());
206 this->status_set_error(LOG_STR("Failed to fetch manifest"));
207 return false;
208 }
209
210 // Read manifest JSON into string (manifest is small, ~1KB max)
211 // NOTE: HttpContainer::read() has non-BSD socket semantics - see http_request.h
212 // Use http_read_loop_result() helper instead of checking return values directly
213 std::string json_str;
214 json_str.reserve(container->content_length);
215 uint8_t buf[256];
216 uint32_t last_data_time = millis();
217 const uint32_t read_timeout = this->http_request_parent_->get_timeout();
218 while (container->get_bytes_read() < container->content_length) {
219 int read_or_error = container->read(buf, sizeof(buf));
220 App.feed_wdt();
221 yield();
222 auto result =
223 http_request::http_read_loop_result(read_or_error, last_data_time, read_timeout, container->is_read_complete());
225 continue;
226 // Note: COMPLETE is currently unreachable since the loop condition checks bytes_read < content_length,
227 // but this is defensive code in case chunked transfer encoding support is added in the future.
229 break; // COMPLETE, ERROR, or TIMEOUT
230 json_str.append(reinterpret_cast<char *>(buf), read_or_error);
231 }
232 container->end();
233
234 // Parse JSON manifest
235 // Format: {"versions": [{"version": "2.7.0", "url": "...", "sha256": "..."}]}
236 // Only consider versions <= host library version to avoid compatibility issues
237 bool valid = json::parse_json(json_str, [this](JsonObject root) -> bool {
238 if (!root["versions"].is<JsonArray>()) {
239 ESP_LOGE(TAG, "Manifest does not contain 'versions' array");
240 return false;
241 }
242
243 JsonArray versions = root["versions"].as<JsonArray>();
244 if (versions.size() == 0) {
245 ESP_LOGE(TAG, "Manifest 'versions' array is empty");
246 return false;
247 }
248
249 // Find the highest version that is compatible with the host library
250 // (version <= host version to avoid upgrading coprocessor ahead of host)
251 int best_major = -1, best_minor = -1, best_patch = -1;
252 std::string best_version, best_url, best_sha256;
253
254 for (JsonObject entry : versions) {
255 if (!entry["version"].is<const char *>() || !entry["url"].is<const char *>() ||
256 !entry["sha256"].is<const char *>()) {
257 continue; // Skip malformed entries
258 }
259
260 std::string ver_str = entry["version"].as<std::string>();
261 int major, minor, patch;
262 if (!parse_version(ver_str, major, minor, patch)) {
263 ESP_LOGW(TAG, "Failed to parse version: %s", ver_str.c_str());
264 continue;
265 }
266
267 // Check if this version is compatible (not newer than host)
268 if (compare_versions(major, minor, patch, ESP_HOSTED_VERSION_MAJOR_1, ESP_HOSTED_VERSION_MINOR_1,
269 ESP_HOSTED_VERSION_PATCH_1) > 0) {
270 continue;
271 }
272
273 // Check if this is better than our current best
274 if (best_major < 0 || compare_versions(major, minor, patch, best_major, best_minor, best_patch) > 0) {
275 best_major = major;
276 best_minor = minor;
277 best_patch = patch;
278 best_version = ver_str;
279 best_url = entry["url"].as<std::string>();
280 best_sha256 = entry["sha256"].as<std::string>();
281 }
282 }
283
284 if (best_major < 0) {
285 ESP_LOGW(TAG, "No compatible firmware version found (host is %s)", ESP_HOSTED_VERSION_STR);
286 return false;
287 }
288
289 this->update_info_.latest_version = best_version;
290 this->firmware_url_ = best_url;
291
292 // Parse SHA256 hex string to bytes
293 if (!parse_hex(best_sha256, this->firmware_sha256_.data(), 32)) {
294 ESP_LOGE(TAG, "Invalid SHA256: %s", best_sha256.c_str());
295 return false;
296 }
297
298 ESP_LOGD(TAG, "Best compatible version: %s", this->update_info_.latest_version.c_str());
299
300 return true;
301 });
302
303 if (!valid) {
304 ESP_LOGE(TAG, "Failed to parse manifest JSON");
305 this->status_set_error(LOG_STR("Failed to parse manifest"));
306 return false;
307 }
308
309 return true;
310}
311
313 ESP_LOGI(TAG, "Downloading firmware");
314
315 auto container = this->http_request_parent_->get(this->firmware_url_);
316 if (container == nullptr || container->status_code != 200) {
317 ESP_LOGE(TAG, "Failed to fetch firmware");
318 this->status_set_error(LOG_STR("Failed to fetch firmware"));
319 return false;
320 }
321
322 size_t total_size = container->content_length;
323 ESP_LOGI(TAG, "Firmware size: %zu bytes", total_size);
324
325 // Begin OTA on coprocessor
326 esp_err_t err = esp_hosted_slave_ota_begin(); // NOLINT
327 if (err != ESP_OK) {
328 ESP_LOGE(TAG, "Failed to begin OTA: %s", esp_err_to_name(err));
329 container->end();
330 this->status_set_error(LOG_STR("Failed to begin OTA"));
331 return false;
332 }
333
334 // Stream firmware to coprocessor while computing SHA256
335 // NOTE: HttpContainer::read() has non-BSD socket semantics - see http_request.h
336 // Use http_read_loop_result() helper instead of checking return values directly
337 sha256::SHA256 hasher;
338 hasher.init();
339
340 uint8_t buffer[CHUNK_SIZE];
341 uint32_t last_data_time = millis();
342 const uint32_t read_timeout = this->http_request_parent_->get_timeout();
343 while (container->get_bytes_read() < total_size) {
344 int read_or_error = container->read(buffer, sizeof(buffer));
345
346 // Feed watchdog and give other tasks a chance to run
347 App.feed_wdt();
348 yield();
349
350 auto result =
351 http_request::http_read_loop_result(read_or_error, last_data_time, read_timeout, container->is_read_complete());
353 continue;
354 // Note: COMPLETE is currently unreachable since the loop condition checks bytes_read < content_length,
355 // but this is defensive code in case chunked transfer encoding support is added in the future.
357 break;
360 ESP_LOGE(TAG, "Timeout reading firmware data");
361 } else {
362 ESP_LOGE(TAG, "Error reading firmware data: %d", read_or_error);
363 }
364 esp_hosted_slave_ota_end(); // NOLINT
365 container->end();
366 this->status_set_error(LOG_STR("Download failed"));
367 return false;
368 }
369
370 hasher.add(buffer, read_or_error);
371 err = esp_hosted_slave_ota_write(buffer, read_or_error); // NOLINT
372 if (err != ESP_OK) {
373 ESP_LOGE(TAG, "Failed to write OTA data: %s", esp_err_to_name(err));
374 esp_hosted_slave_ota_end(); // NOLINT
375 container->end();
376 this->status_set_error(LOG_STR("Failed to write OTA data"));
377 return false;
378 }
379 }
380 container->end();
381
382 // Verify SHA256
383 hasher.calculate();
384 if (!hasher.equals_bytes(this->firmware_sha256_.data())) {
385 ESP_LOGE(TAG, "SHA256 mismatch");
386 esp_hosted_slave_ota_end(); // NOLINT
387 this->status_set_error(LOG_STR("SHA256 verification failed"));
388 return false;
389 }
390
391 ESP_LOGI(TAG, "SHA256 verified successfully");
392 return true;
393}
394#else
396 if (this->firmware_data_ == nullptr || this->firmware_size_ == 0) {
397 ESP_LOGE(TAG, "No firmware data available");
398 this->status_set_error(LOG_STR("No firmware data available"));
399 return false;
400 }
401
402 // Verify SHA256 before writing
403 sha256::SHA256 hasher;
404 hasher.init();
405 hasher.add(this->firmware_data_, this->firmware_size_);
406 hasher.calculate();
407 if (!hasher.equals_bytes(this->firmware_sha256_.data())) {
408 ESP_LOGE(TAG, "SHA256 mismatch");
409 this->status_set_error(LOG_STR("SHA256 verification failed"));
410 return false;
411 }
412
413 ESP_LOGI(TAG, "Starting OTA update (%zu bytes)", this->firmware_size_);
414
415 esp_err_t err = esp_hosted_slave_ota_begin(); // NOLINT
416 if (err != ESP_OK) {
417 ESP_LOGE(TAG, "Failed to begin OTA: %s", esp_err_to_name(err));
418 this->status_set_error(LOG_STR("Failed to begin OTA"));
419 return false;
420 }
421
422 uint8_t chunk[CHUNK_SIZE];
423 const uint8_t *data_ptr = this->firmware_data_;
424 size_t remaining = this->firmware_size_;
425 while (remaining > 0) {
426 size_t chunk_size = std::min(remaining, static_cast<size_t>(CHUNK_SIZE));
427 memcpy(chunk, data_ptr, chunk_size);
428 err = esp_hosted_slave_ota_write(chunk, chunk_size); // NOLINT
429 if (err != ESP_OK) {
430 ESP_LOGE(TAG, "Failed to write OTA data: %s", esp_err_to_name(err));
431 esp_hosted_slave_ota_end(); // NOLINT
432 this->status_set_error(LOG_STR("Failed to write OTA data"));
433 return false;
434 }
435 data_ptr += chunk_size;
436 remaining -= chunk_size;
437 App.feed_wdt();
438 }
439
440 return true;
441}
442#endif
443
445 if (this->state_ != update::UPDATE_STATE_AVAILABLE && !force) {
446 ESP_LOGW(TAG, "Update not available");
447 return;
448 }
449
450 update::UpdateState prev_state = this->state_;
452 this->update_info_.has_progress = false;
453 this->publish_state();
454
455 watchdog::WatchdogManager watchdog(60000);
456
457#ifdef USE_ESP32_HOSTED_HTTP_UPDATE
459#else
461#endif
462 {
463 this->state_ = prev_state;
464 this->publish_state();
465 return;
466 }
467
468 // End OTA and activate new firmware
469 esp_err_t end_err = esp_hosted_slave_ota_end(); // NOLINT
470 if (end_err != ESP_OK) {
471 ESP_LOGE(TAG, "Failed to end OTA: %s", esp_err_to_name(end_err));
472 this->state_ = prev_state;
473 this->status_set_error(LOG_STR("Failed to end OTA"));
474 this->publish_state();
475 return;
476 }
477
478 esp_err_t activate_err = esp_hosted_slave_ota_activate(); // NOLINT
479 if (activate_err != ESP_OK) {
480 ESP_LOGE(TAG, "Failed to activate OTA: %s", esp_err_to_name(activate_err));
481 this->state_ = prev_state;
482 this->status_set_error(LOG_STR("Failed to activate OTA"));
483 this->publish_state();
484 return;
485 }
486
487 // Update state
488 ESP_LOGI(TAG, "OTA update successful");
490 this->status_clear_error();
491 this->publish_state();
492
493#ifdef USE_OTA_ROLLBACK
494 // Mark the host partition as valid before rebooting, in case the safe mode
495 // timer hasn't expired yet.
496 esp_ota_mark_app_valid_cancel_rollback();
497#endif
498
499 // Schedule a restart to ensure everything is in sync
500 ESP_LOGI(TAG, "Restarting in 1 second");
501 this->set_timeout(1000, []() { App.safe_reboot(); });
502}
503
504} // namespace esphome::esp32_hosted
505#endif
void feed_wdt(uint32_t time=0)
ESPDEPRECATED("Use const char* or uint32_t overload instead. Removed in 2026.7.0", "2026.1.0") void set_timeout(const std voi set_timeout)(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a unique name.
Definition component.h:429
ESPDEPRECATED("Use const char* or uint32_t overload instead. Removed in 2026.7.0", "2026.1.0") void set_interval(const std voi set_interval)(const char *name, uint32_t interval, std::function< void()> &&f)
Set an interval function with a unique name.
Definition component.h:336
ESPDEPRECATED("Use const char* or uint32_t overload instead. Removed in 2026.7.0", "2026.1.0") bool cancel_interval(const std boo cancel_interval)(const char *name)
Cancel an interval function.
Definition component.h:358
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 std::string &url)
SHA256 hash implementation.
Definition sha256.h:38
void calculate() override
Definition sha256.cpp:56
void add(const uint8_t *data, size_t len) override
Definition sha256.cpp:54
void init() override
Definition sha256.cpp:49
constexpr uint32_t INITIAL_CHECK_INTERVAL_ID
@ 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:27
bool is_connected()
Return whether the node is connected to the network (through wifi, eth, ...)
Definition util.cpp:26
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:294
void IRAM_ATTR HOT yield()
Definition core.cpp:24
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:25
Application App
Global storage of Application pointer - only one Application can exist.
uint8_t end[39]
Definition sun_gtil2.cpp:17