ESPHome 2026.3.0-dev
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 "ESP32 Hosted firmware:\n"
110 " Firmware version: %s\n"
111 " Project name: %s\n"
112 " Build date: %s\n"
113 " Build time: %s\n"
114 " IDF version: %s",
115 app_desc->version, app_desc->project_name, app_desc->date, app_desc->time, app_desc->idf_ver);
116 this->update_info_.latest_version = app_desc->version;
117 if (this->update_info_.latest_version != this->update_info_.current_version) {
119 } else {
121 }
122 } else {
123 ESP_LOGW(TAG, "Invalid app description magic word: 0x%08x (expected 0x%08x)", app_desc->magic_word,
124 ESP_APP_DESC_MAGIC_WORD);
126 }
127 } else {
128 ESP_LOGW(TAG, "Firmware too small to contain app description");
130 }
131
132 // Publish state
133 this->status_clear_error();
134 this->publish_state();
135#else
136 // HTTP mode: check every 10s until network is ready (max 6 attempts)
137 // Only if update interval is > 1 minute to avoid redundant checks
138 if (this->get_update_interval() > 60000) {
139 this->initial_check_remaining_ = 6;
140 this->set_interval(INITIAL_CHECK_INTERVAL_ID, 10000, [this]() {
141 bool connected = network::is_connected();
142 if (--this->initial_check_remaining_ == 0 || connected) {
143 this->cancel_interval(INITIAL_CHECK_INTERVAL_ID);
144 if (connected) {
145 this->check();
146 }
147 }
148 });
149 }
150#endif
151}
152
154 ESP_LOGCONFIG(TAG,
155 "ESP32 Hosted Update:\n"
156 " Host Library Version: %s\n"
157 " Coprocessor Version: %s\n"
158 " Latest Version: %s",
159 ESP_HOSTED_VERSION_STR, this->update_info_.current_version.c_str(),
160 this->update_info_.latest_version.c_str());
161#ifdef USE_ESP32_HOSTED_HTTP_UPDATE
162 ESP_LOGCONFIG(TAG,
163 " Mode: HTTP\n"
164 " Source URL: %s",
165 this->source_url_.c_str());
166#else
167 ESP_LOGCONFIG(TAG,
168 " Mode: Embedded\n"
169 " Firmware Size: %zu bytes",
170 this->firmware_size_);
171#endif
172}
173
175#ifdef USE_ESP32_HOSTED_HTTP_UPDATE
176 if (!network::is_connected()) {
177 ESP_LOGD(TAG, "Network not connected, skipping update check");
178 return;
179 }
180
181 if (!this->fetch_manifest_()) {
182 return;
183 }
184
185 // Compare versions
186 if (this->update_info_.latest_version.empty() ||
187 this->update_info_.latest_version == this->update_info_.current_version) {
189 } else {
191 }
192
193 this->update_info_.has_progress = false;
194 this->update_info_.progress = 0.0f;
195 this->status_clear_error();
196 this->publish_state();
197#endif
198}
199
200#ifdef USE_ESP32_HOSTED_HTTP_UPDATE
202 ESP_LOGD(TAG, "Fetching manifest");
203
204 auto container = this->http_request_parent_->get(this->source_url_);
205 if (container == nullptr || container->status_code != 200) {
206 ESP_LOGE(TAG, "Failed to fetch manifest from %s", this->source_url_.c_str());
207 this->status_set_error(LOG_STR("Failed to fetch manifest"));
208 return false;
209 }
210
211 // Read manifest JSON into string (manifest is small, ~1KB max)
212 // NOTE: HttpContainer::read() has non-BSD socket semantics - see http_request.h
213 // Use http_read_loop_result() helper instead of checking return values directly
214 std::string json_str;
215 json_str.reserve(container->content_length);
216 uint8_t buf[256];
217 uint32_t last_data_time = millis();
218 const uint32_t read_timeout = this->http_request_parent_->get_timeout();
219 while (container->get_bytes_read() < container->content_length) {
220 int read_or_error = container->read(buf, sizeof(buf));
221 App.feed_wdt();
222 yield();
223 auto result =
224 http_request::http_read_loop_result(read_or_error, last_data_time, read_timeout, container->is_read_complete());
226 continue;
227 // Note: COMPLETE is currently unreachable since the loop condition checks bytes_read < content_length,
228 // but this is defensive code in case chunked transfer encoding support is added in the future.
230 break; // COMPLETE, ERROR, or TIMEOUT
231 json_str.append(reinterpret_cast<char *>(buf), read_or_error);
232 }
233 container->end();
234
235 // Parse JSON manifest
236 // Format: {"versions": [{"version": "2.7.0", "url": "...", "sha256": "..."}]}
237 // Only consider versions <= host library version to avoid compatibility issues
238 bool valid = json::parse_json(json_str, [this](JsonObject root) -> bool {
239 if (!root["versions"].is<JsonArray>()) {
240 ESP_LOGE(TAG, "Manifest does not contain 'versions' array");
241 return false;
242 }
243
244 JsonArray versions = root["versions"].as<JsonArray>();
245 if (versions.size() == 0) {
246 ESP_LOGE(TAG, "Manifest 'versions' array is empty");
247 return false;
248 }
249
250 // Find the highest version that is compatible with the host library
251 // (version <= host version to avoid upgrading coprocessor ahead of host)
252 int best_major = -1, best_minor = -1, best_patch = -1;
253 std::string best_version, best_url, best_sha256;
254
255 for (JsonObject entry : versions) {
256 if (!entry["version"].is<const char *>() || !entry["url"].is<const char *>() ||
257 !entry["sha256"].is<const char *>()) {
258 continue; // Skip malformed entries
259 }
260
261 std::string ver_str = entry["version"].as<std::string>();
262 int major, minor, patch;
263 if (!parse_version(ver_str, major, minor, patch)) {
264 ESP_LOGW(TAG, "Failed to parse version: %s", ver_str.c_str());
265 continue;
266 }
267
268 // Check if this version is compatible (not newer than host)
269 if (compare_versions(major, minor, patch, ESP_HOSTED_VERSION_MAJOR_1, ESP_HOSTED_VERSION_MINOR_1,
270 ESP_HOSTED_VERSION_PATCH_1) > 0) {
271 continue;
272 }
273
274 // Check if this is better than our current best
275 if (best_major < 0 || compare_versions(major, minor, patch, best_major, best_minor, best_patch) > 0) {
276 best_major = major;
277 best_minor = minor;
278 best_patch = patch;
279 best_version = ver_str;
280 best_url = entry["url"].as<std::string>();
281 best_sha256 = entry["sha256"].as<std::string>();
282 }
283 }
284
285 if (best_major < 0) {
286 ESP_LOGW(TAG, "No compatible firmware version found (host is %s)", ESP_HOSTED_VERSION_STR);
287 return false;
288 }
289
290 this->update_info_.latest_version = best_version;
291 this->firmware_url_ = best_url;
292
293 // Parse SHA256 hex string to bytes
294 if (!parse_hex(best_sha256, this->firmware_sha256_.data(), 32)) {
295 ESP_LOGE(TAG, "Invalid SHA256: %s", best_sha256.c_str());
296 return false;
297 }
298
299 ESP_LOGD(TAG, "Best compatible version: %s", this->update_info_.latest_version.c_str());
300
301 return true;
302 });
303
304 if (!valid) {
305 ESP_LOGE(TAG, "Failed to parse manifest JSON");
306 this->status_set_error(LOG_STR("Failed to parse manifest"));
307 return false;
308 }
309
310 return true;
311}
312
314 ESP_LOGI(TAG, "Downloading firmware");
315
316 auto container = this->http_request_parent_->get(this->firmware_url_);
317 if (container == nullptr || container->status_code != 200) {
318 ESP_LOGE(TAG, "Failed to fetch firmware");
319 this->status_set_error(LOG_STR("Failed to fetch firmware"));
320 return false;
321 }
322
323 size_t total_size = container->content_length;
324 ESP_LOGI(TAG, "Firmware size: %zu bytes", total_size);
325
326 // Begin OTA on coprocessor
327 esp_err_t err = esp_hosted_slave_ota_begin(); // NOLINT
328 if (err != ESP_OK) {
329 ESP_LOGE(TAG, "Failed to begin OTA: %s", esp_err_to_name(err));
330 container->end();
331 this->status_set_error(LOG_STR("Failed to begin OTA"));
332 return false;
333 }
334
335 // Stream firmware to coprocessor while computing SHA256
336 // NOTE: HttpContainer::read() has non-BSD socket semantics - see http_request.h
337 // Use http_read_loop_result() helper instead of checking return values directly
338 sha256::SHA256 hasher;
339 hasher.init();
340
341 uint8_t buffer[CHUNK_SIZE];
342 uint32_t last_data_time = millis();
343 const uint32_t read_timeout = this->http_request_parent_->get_timeout();
344 while (container->get_bytes_read() < total_size) {
345 int read_or_error = container->read(buffer, sizeof(buffer));
346
347 // Feed watchdog and give other tasks a chance to run
348 App.feed_wdt();
349 yield();
350
351 auto result =
352 http_request::http_read_loop_result(read_or_error, last_data_time, read_timeout, container->is_read_complete());
354 continue;
355 // Note: COMPLETE is currently unreachable since the loop condition checks bytes_read < content_length,
356 // but this is defensive code in case chunked transfer encoding support is added in the future.
358 break;
361 ESP_LOGE(TAG, "Timeout reading firmware data");
362 } else {
363 ESP_LOGE(TAG, "Error reading firmware data: %d", read_or_error);
364 }
365 esp_hosted_slave_ota_end(); // NOLINT
366 container->end();
367 this->status_set_error(LOG_STR("Download failed"));
368 return false;
369 }
370
371 hasher.add(buffer, read_or_error);
372 err = esp_hosted_slave_ota_write(buffer, read_or_error); // NOLINT
373 if (err != ESP_OK) {
374 ESP_LOGE(TAG, "Failed to write OTA data: %s", esp_err_to_name(err));
375 esp_hosted_slave_ota_end(); // NOLINT
376 container->end();
377 this->status_set_error(LOG_STR("Failed to write OTA data"));
378 return false;
379 }
380 }
381 container->end();
382
383 // Verify SHA256
384 hasher.calculate();
385 if (!hasher.equals_bytes(this->firmware_sha256_.data())) {
386 ESP_LOGE(TAG, "SHA256 mismatch");
387 esp_hosted_slave_ota_end(); // NOLINT
388 this->status_set_error(LOG_STR("SHA256 verification failed"));
389 return false;
390 }
391
392 ESP_LOGI(TAG, "SHA256 verified successfully");
393 return true;
394}
395#else
397 if (this->firmware_data_ == nullptr || this->firmware_size_ == 0) {
398 ESP_LOGE(TAG, "No firmware data available");
399 this->status_set_error(LOG_STR("No firmware data available"));
400 return false;
401 }
402
403 // Verify SHA256 before writing
404 sha256::SHA256 hasher;
405 hasher.init();
406 hasher.add(this->firmware_data_, this->firmware_size_);
407 hasher.calculate();
408 if (!hasher.equals_bytes(this->firmware_sha256_.data())) {
409 ESP_LOGE(TAG, "SHA256 mismatch");
410 this->status_set_error(LOG_STR("SHA256 verification failed"));
411 return false;
412 }
413
414 ESP_LOGI(TAG, "Starting OTA update (%zu bytes)", this->firmware_size_);
415
416 esp_err_t err = esp_hosted_slave_ota_begin(); // NOLINT
417 if (err != ESP_OK) {
418 ESP_LOGE(TAG, "Failed to begin OTA: %s", esp_err_to_name(err));
419 this->status_set_error(LOG_STR("Failed to begin OTA"));
420 return false;
421 }
422
423 uint8_t chunk[CHUNK_SIZE];
424 const uint8_t *data_ptr = this->firmware_data_;
425 size_t remaining = this->firmware_size_;
426 while (remaining > 0) {
427 size_t chunk_size = std::min(remaining, static_cast<size_t>(CHUNK_SIZE));
428 memcpy(chunk, data_ptr, chunk_size);
429 err = esp_hosted_slave_ota_write(chunk, chunk_size); // NOLINT
430 if (err != ESP_OK) {
431 ESP_LOGE(TAG, "Failed to write OTA data: %s", esp_err_to_name(err));
432 esp_hosted_slave_ota_end(); // NOLINT
433 this->status_set_error(LOG_STR("Failed to write OTA data"));
434 return false;
435 }
436 data_ptr += chunk_size;
437 remaining -= chunk_size;
438 App.feed_wdt();
439 }
440
441 return true;
442}
443#endif
444
446 if (this->state_ != update::UPDATE_STATE_AVAILABLE && !force) {
447 ESP_LOGW(TAG, "Update not available");
448 return;
449 }
450
451 update::UpdateState prev_state = this->state_;
453 this->update_info_.has_progress = false;
454 this->publish_state();
455
456 watchdog::WatchdogManager watchdog(60000);
457
458#ifdef USE_ESP32_HOSTED_HTTP_UPDATE
460#else
462#endif
463 {
464 this->state_ = prev_state;
465 this->publish_state();
466 return;
467 }
468
469 // End OTA and activate new firmware
470 esp_err_t end_err = esp_hosted_slave_ota_end(); // NOLINT
471 if (end_err != ESP_OK) {
472 ESP_LOGE(TAG, "Failed to end OTA: %s", esp_err_to_name(end_err));
473 this->state_ = prev_state;
474 this->status_set_error(LOG_STR("Failed to end OTA"));
475 this->publish_state();
476 return;
477 }
478
479 esp_err_t activate_err = esp_hosted_slave_ota_activate(); // NOLINT
480 if (activate_err != ESP_OK) {
481 ESP_LOGE(TAG, "Failed to activate OTA: %s", esp_err_to_name(activate_err));
482 this->state_ = prev_state;
483 this->status_set_error(LOG_STR("Failed to activate OTA"));
484 this->publish_state();
485 return;
486 }
487
488 // Update state
489 ESP_LOGI(TAG, "OTA update successful");
491 this->status_clear_error();
492 this->publish_state();
493
494#ifdef USE_OTA_ROLLBACK
495 // Mark the host partition as valid before rebooting, in case the safe mode
496 // timer hasn't expired yet.
497 esp_ota_mark_app_valid_cancel_rollback();
498#endif
499
500 // Schedule a restart to ensure everything is in sync
501 ESP_LOGI(TAG, "Restarting in 1 second");
502 this->set_timeout(1000, []() { App.safe_reboot(); });
503}
504
505} // namespace esphome::esp32_hosted
506#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:443
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:350
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:372
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:25
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 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