ESPHome 2026.1.0-dev
Loading...
Searching...
No Matches
ota_backend_esp8266.cpp
Go to the documentation of this file.
1#ifdef USE_ESP8266
3#include "ota_backend.h"
4
9#include "esphome/core/log.h"
10
11#include <Esp.h>
12#include <esp8266_peri.h>
13
14#include <cinttypes>
15
16extern "C" {
17#include <c_types.h>
18#include <eboot_command.h>
19#include <flash_hal.h>
20#include <spi_flash.h>
21#include <user_interface.h>
22}
23
24// Note: FLASH_SECTOR_SIZE (0x1000) is already defined in spi_flash_geometry.h
25
26// Flash header offsets
27static constexpr uint8_t FLASH_MODE_OFFSET = 2;
28
29// Firmware magic bytes
30static constexpr uint8_t FIRMWARE_MAGIC = 0xE9;
31static constexpr uint8_t GZIP_MAGIC_1 = 0x1F;
32static constexpr uint8_t GZIP_MAGIC_2 = 0x8B;
33
34// ESP8266 flash memory base address (memory-mapped flash starts here)
35static constexpr uint32_t FLASH_BASE_ADDRESS = 0x40200000;
36
37// Boot mode extraction from GPI register (bits 16-19 contain boot mode)
38static constexpr int BOOT_MODE_SHIFT = 16;
39static constexpr int BOOT_MODE_MASK = 0xf;
40
41// Boot mode indicating UART download mode (OTA not possible)
42static constexpr int BOOT_MODE_UART_DOWNLOAD = 1;
43
44// Minimum buffer size when memory is constrained
45static constexpr size_t MIN_BUFFER_SIZE = 256;
46
47namespace esphome::ota {
48
49static const char *const TAG = "ota.esp8266";
50
51std::unique_ptr<ota::OTABackend> make_ota_backend() { return make_unique<ota::ESP8266OTABackend>(); }
52
54 // Handle UPDATE_SIZE_UNKNOWN (0) by calculating available space
55 if (image_size == 0) {
56 // Round down to sector boundary: subtract one sector, then mask to sector alignment
57 // NOLINTNEXTLINE(readability-static-accessed-through-instance)
58 image_size = (ESP.getFreeSketchSpace() - FLASH_SECTOR_SIZE) & ~(FLASH_SECTOR_SIZE - 1);
59 }
60
61 // Check boot mode - if boot mode is UART download mode,
62 // we will not be able to reset into normal mode once update is done
63 int boot_mode = (GPI >> BOOT_MODE_SHIFT) & BOOT_MODE_MASK;
64 if (boot_mode == BOOT_MODE_UART_DOWNLOAD) {
66 }
67
68 // Check flash configuration - real size must be >= configured size
69 // NOLINTNEXTLINE(readability-static-accessed-through-instance)
70 if (!ESP.checkFlashConfig(false)) {
72 }
73
74 // Get current sketch size
75 // NOLINTNEXTLINE(readability-static-accessed-through-instance)
76 uint32_t sketch_size = ESP.getSketchSize();
77
78 // Size of current sketch rounded to sector boundary
79 uint32_t current_sketch_size = (sketch_size + FLASH_SECTOR_SIZE - 1) & (~(FLASH_SECTOR_SIZE - 1));
80
81 // Size of update rounded to sector boundary
82 uint32_t rounded_size = (image_size + FLASH_SECTOR_SIZE - 1) & (~(FLASH_SECTOR_SIZE - 1));
83
84 // End of available space for sketch and update (start of filesystem)
85 uint32_t update_end_address = FS_start - FLASH_BASE_ADDRESS;
86
87 // Calculate start address for the update (write from end backwards)
88 this->start_address_ = (update_end_address > rounded_size) ? (update_end_address - rounded_size) : 0;
89
90 // Check if there's enough space for both current sketch and update
91 if (this->start_address_ < current_sketch_size) {
93 }
94
95 // Allocate buffer for sector writes (use smaller buffer if memory constrained)
96 // NOLINTNEXTLINE(readability-static-accessed-through-instance)
97 this->buffer_size_ = (ESP.getFreeHeap() > 2 * FLASH_SECTOR_SIZE) ? FLASH_SECTOR_SIZE : MIN_BUFFER_SIZE;
98
99 // ESP8266's umm_malloc guarantees 4-byte aligned allocations, which is required
100 // for spi_flash_write(). This is the same pattern used by Arduino's Updater class.
101 this->buffer_ = make_unique<uint8_t[]>(this->buffer_size_);
102 if (!this->buffer_) {
104 }
105
106 this->current_address_ = this->start_address_;
107 this->image_size_ = image_size;
108 this->buffer_len_ = 0;
109 this->md5_set_ = false;
110
111 // Disable WiFi sleep during update
112 wifi_set_sleep_type(NONE_SLEEP_T);
113
114 // Prevent preference writes during update
116
117 // Initialize MD5 computation
118 this->md5_.init();
119
120 ESP_LOGD(TAG, "OTA begin: start=0x%08" PRIX32 ", size=%zu", this->start_address_, image_size);
121
122 return OTA_RESPONSE_OK;
123}
124
126 // Parse hex string to bytes
127 if (parse_hex(md5, this->expected_md5_, 16)) {
128 this->md5_set_ = true;
129 }
130}
131
133 if (!this->buffer_) {
135 }
136
137 size_t written = 0;
138 while (written < len) {
139 // Calculate how much we can buffer
140 size_t to_buffer = std::min(len - written, this->buffer_size_ - this->buffer_len_);
141 memcpy(this->buffer_.get() + this->buffer_len_, data + written, to_buffer);
142 this->buffer_len_ += to_buffer;
143 written += to_buffer;
144
145 // If buffer is full, write to flash
146 if (this->buffer_len_ == this->buffer_size_ && !this->write_buffer_()) {
148 }
149 }
150
151 return OTA_RESPONSE_OK;
152}
153
155 if ((this->current_address_ % FLASH_SECTOR_SIZE) != 0) {
156 return true; // Not at sector boundary
157 }
158
159 App.feed_wdt();
160 if (spi_flash_erase_sector(this->current_address_ / FLASH_SECTOR_SIZE) != SPI_FLASH_RESULT_OK) {
161 ESP_LOGE(TAG, "Flash erase failed at 0x%08" PRIX32, this->current_address_);
162 return false;
163 }
164 return true;
165}
166
168 App.feed_wdt();
169 if (spi_flash_write(this->current_address_, reinterpret_cast<uint32_t *>(this->buffer_.get()), this->buffer_len_) !=
170 SPI_FLASH_RESULT_OK) {
171 ESP_LOGE(TAG, "Flash write failed at 0x%08" PRIX32, this->current_address_);
172 return false;
173 }
174 return true;
175}
176
178 if (this->buffer_len_ == 0) {
179 return true;
180 }
181
182 if (!this->erase_sector_if_needed_()) {
183 return false;
184 }
185
186 // Patch flash mode in first sector if needed
187 // This is analogous to what esptool.py does when it receives a --flash_mode argument
188 bool is_first_sector = (this->current_address_ == this->start_address_);
189 uint8_t original_flash_mode = 0;
190 bool patched_flash_mode = false;
191
192 // Only patch if we have enough bytes to access flash mode offset and it's not GZIP
193 if (is_first_sector && this->buffer_len_ > FLASH_MODE_OFFSET && this->buffer_[0] != GZIP_MAGIC_1) {
194 // Not GZIP compressed - check and patch flash mode
195 uint8_t current_flash_mode = this->get_flash_chip_mode_();
196 uint8_t buffer_flash_mode = this->buffer_[FLASH_MODE_OFFSET];
197
198 if (buffer_flash_mode != current_flash_mode) {
199 original_flash_mode = buffer_flash_mode;
200 this->buffer_[FLASH_MODE_OFFSET] = current_flash_mode;
201 patched_flash_mode = true;
202 }
203 }
204
205 if (!this->flash_write_()) {
206 return false;
207 }
208
209 // Restore original flash mode for MD5 calculation
210 if (patched_flash_mode) {
211 this->buffer_[FLASH_MODE_OFFSET] = original_flash_mode;
212 }
213
214 // Update MD5 with original (unpatched) data
215 this->md5_.add(this->buffer_.get(), this->buffer_len_);
216
217 this->current_address_ += this->buffer_len_;
218 this->buffer_len_ = 0;
219
220 return true;
221}
222
224 // Similar to write_buffer_(), but without flash mode patching or MD5 update (for final padded write)
225 if (this->buffer_len_ == 0) {
226 return true;
227 }
228
229 if (!this->erase_sector_if_needed_() || !this->flash_write_()) {
230 return false;
231 }
232
233 this->current_address_ += this->buffer_len_;
234 this->buffer_len_ = 0;
235
236 return true;
237}
238
240 // Write any remaining buffered data
241 if (this->buffer_len_ > 0) {
242 // Add actual data to MD5 before padding
243 this->md5_.add(this->buffer_.get(), this->buffer_len_);
244
245 // Pad to 4-byte alignment for flash write
246 while (this->buffer_len_ % 4 != 0) {
247 this->buffer_[this->buffer_len_++] = 0xFF;
248 }
249 if (!this->write_buffer_final_()) {
250 this->abort();
252 }
253 }
254
255 // Calculate actual bytes written
256 size_t actual_size = this->current_address_ - this->start_address_;
257
258 // Check if any data was written
259 if (actual_size == 0) {
260 ESP_LOGE(TAG, "No data written");
261 this->abort();
263 }
264
265 // Verify MD5 if set (strict mode), otherwise use lenient mode
266 // In lenient mode (no MD5), we accept whatever was written
267 if (this->md5_set_) {
268 this->md5_.calculate();
269 if (!this->md5_.equals_bytes(this->expected_md5_)) {
270 ESP_LOGE(TAG, "MD5 mismatch");
271 this->abort();
273 }
274 } else {
275 // Lenient mode: adjust size to what was actually written
276 // This matches Arduino's Update.end(true) behavior
277 this->image_size_ = actual_size;
278 }
279
280 // Verify firmware header
281 if (!this->verify_end_()) {
282 this->abort();
284 }
285
286 // Write eboot command to copy firmware on next boot
287 eboot_command ebcmd;
288 ebcmd.action = ACTION_COPY_RAW;
289 ebcmd.args[0] = this->start_address_;
290 ebcmd.args[1] = 0x00000; // Destination: start of flash
291 ebcmd.args[2] = this->image_size_;
292 eboot_command_write(&ebcmd);
293
294 ESP_LOGI(TAG, "OTA update staged: 0x%08" PRIX32 " -> 0x00000, size=%zu", this->start_address_, this->image_size_);
295
296 // Clean up
297 this->buffer_.reset();
299
300 return OTA_RESPONSE_OK;
301}
302
304 this->buffer_.reset();
305 this->buffer_len_ = 0;
306 this->image_size_ = 0;
308}
309
311 uint32_t buf;
312 if (spi_flash_read(this->start_address_, &buf, 4) != SPI_FLASH_RESULT_OK) {
313 ESP_LOGE(TAG, "Failed to read firmware header");
314 return false;
315 }
316
317 uint8_t *bytes = reinterpret_cast<uint8_t *>(&buf);
318
319 // Check for GZIP (compressed firmware)
320 if (bytes[0] == GZIP_MAGIC_1 && bytes[1] == GZIP_MAGIC_2) {
321 // GZIP compressed - can't verify further
322 return true;
323 }
324
325 // Check firmware magic byte
326 if (bytes[0] != FIRMWARE_MAGIC) {
327 ESP_LOGE(TAG, "Invalid firmware magic: 0x%02X (expected 0x%02X)", bytes[0], FIRMWARE_MAGIC);
328 return false;
329 }
330
331#if !FLASH_MAP_SUPPORT
332 // Check if new firmware's flash size fits (only when auto-detection is disabled)
333 // With FLASH_MAP_SUPPORT (modern cores), flash size is auto-detected from chip
334 // NOLINTNEXTLINE(readability-static-accessed-through-instance)
335 uint32_t bin_flash_size = ESP.magicFlashChipSize((bytes[3] & 0xf0) >> 4);
336 // NOLINTNEXTLINE(readability-static-accessed-through-instance)
337 if (bin_flash_size > ESP.getFlashChipRealSize()) {
338 ESP_LOGE(TAG, "Firmware flash size (%" PRIu32 ") exceeds chip size (%" PRIu32 ")", bin_flash_size,
339 ESP.getFlashChipRealSize());
340 return false;
341 }
342#endif
343
344 return true;
345}
346
348 uint32_t data;
349 if (spi_flash_read(0x0000, &data, 4) != SPI_FLASH_RESULT_OK) {
350 return 0; // Default to QIO
351 }
352 return (reinterpret_cast<uint8_t *>(&data))[FLASH_MODE_OFFSET];
353}
354
355} // namespace esphome::ota
356#endif // USE_ESP8266
void feed_wdt(uint32_t time=0)
bool equals_bytes(const uint8_t *expected)
Compare the hash against a provided byte-encoded hash.
Definition hash_base.h:32
void calculate() override
Compute the digest, based on the provided data.
Definition md5.cpp:17
void add(const uint8_t *data, size_t len) override
Add bytes of data for the digest.
Definition md5.cpp:15
void init() override
Initialize a new MD5 digest computation.
Definition md5.cpp:10
bool write_buffer_final_()
Write buffered data to flash without MD5 update (for final padded write)
std::unique_ptr< uint8_t[]> buffer_
OTAResponseTypes write(uint8_t *data, size_t len) override
bool erase_sector_if_needed_()
Erase flash sector if current address is at sector boundary.
bool write_buffer_()
Write buffered data to flash and update MD5.
OTAResponseTypes begin(size_t image_size) override
bool verify_end_()
Verify the firmware header is valid.
bool flash_write_()
Write buffer to flash (does not update address or clear buffer)
OTAResponseTypes end() override
void set_update_md5(const char *md5) override
uint8_t get_flash_chip_mode_()
Get current flash chip mode from flash header.
void preferences_prevent_write(bool prevent)
std::unique_ptr< ota::OTABackend > make_ota_backend()
@ OTA_RESPONSE_ERROR_MD5_MISMATCH
Definition ota_backend.h:39
@ OTA_RESPONSE_ERROR_WRONG_CURRENT_FLASH_CONFIG
Definition ota_backend.h:34
@ OTA_RESPONSE_ERROR_WRITING_FLASH
Definition ota_backend.h:31
@ OTA_RESPONSE_ERROR_ESP8266_NOT_ENOUGH_SPACE
Definition ota_backend.h:36
@ OTA_RESPONSE_ERROR_UPDATE_END
Definition ota_backend.h:32
@ OTA_RESPONSE_ERROR_UNKNOWN
Definition ota_backend.h:41
@ OTA_RESPONSE_ERROR_INVALID_BOOTSTRAPPING
Definition ota_backend.h:33
std::string size_t len
Definition helpers.h:533
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:272
Application App
Global storage of Application pointer - only one Application can exist.