ESPHome 2026.3.0
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<ESP8266OTABackend> make_ota_backend() { return make_unique<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->bytes_received_ = 0;
109 this->buffer_len_ = 0;
110 this->md5_set_ = false;
111
112 // Disable WiFi sleep during update
113 wifi_set_sleep_type(NONE_SLEEP_T);
114
115 // Prevent preference writes during update
117
118 // Initialize MD5 computation
119 this->md5_.init();
120
121 ESP_LOGD(TAG, "OTA begin: start=0x%08" PRIX32 ", size=%zu", this->start_address_, image_size);
122
123 return OTA_RESPONSE_OK;
124}
125
127 // Parse hex string to bytes
128 if (parse_hex(md5, this->expected_md5_, 16)) {
129 this->md5_set_ = true;
130 }
131}
132
134 if (!this->buffer_) {
136 }
137
138 size_t written = 0;
139 while (written < len) {
140 // Calculate how much we can buffer
141 size_t to_buffer = std::min(len - written, this->buffer_size_ - this->buffer_len_);
142 memcpy(this->buffer_.get() + this->buffer_len_, data + written, to_buffer);
143 this->buffer_len_ += to_buffer;
144 this->bytes_received_ += to_buffer;
145 written += to_buffer;
146
147 // If buffer is full, write to flash
148 if (this->buffer_len_ == this->buffer_size_ && !this->write_buffer_()) {
150 }
151 }
152
153 return OTA_RESPONSE_OK;
154}
155
157 if ((this->current_address_ % FLASH_SECTOR_SIZE) != 0) {
158 return true; // Not at sector boundary
159 }
160
161 App.feed_wdt();
162 if (spi_flash_erase_sector(this->current_address_ / FLASH_SECTOR_SIZE) != SPI_FLASH_RESULT_OK) {
163 ESP_LOGE(TAG, "Flash erase failed at 0x%08" PRIX32, this->current_address_);
164 return false;
165 }
166 return true;
167}
168
170 App.feed_wdt();
171 if (spi_flash_write(this->current_address_, reinterpret_cast<uint32_t *>(this->buffer_.get()), this->buffer_len_) !=
172 SPI_FLASH_RESULT_OK) {
173 ESP_LOGE(TAG, "Flash write failed at 0x%08" PRIX32, this->current_address_);
174 return false;
175 }
176 return true;
177}
178
180 if (this->buffer_len_ == 0) {
181 return true;
182 }
183
184 if (!this->erase_sector_if_needed_()) {
185 return false;
186 }
187
188 // Patch flash mode in first sector if needed
189 // This is analogous to what esptool.py does when it receives a --flash_mode argument
190 bool is_first_sector = (this->current_address_ == this->start_address_);
191 uint8_t original_flash_mode = 0;
192 bool patched_flash_mode = false;
193
194 // Only patch if we have enough bytes to access flash mode offset and it's not GZIP
195 if (is_first_sector && this->buffer_len_ > FLASH_MODE_OFFSET && this->buffer_[0] != GZIP_MAGIC_1) {
196 // Not GZIP compressed - check and patch flash mode
197 uint8_t current_flash_mode = this->get_flash_chip_mode_();
198 uint8_t buffer_flash_mode = this->buffer_[FLASH_MODE_OFFSET];
199
200 if (buffer_flash_mode != current_flash_mode) {
201 original_flash_mode = buffer_flash_mode;
202 this->buffer_[FLASH_MODE_OFFSET] = current_flash_mode;
203 patched_flash_mode = true;
204 }
205 }
206
207 if (!this->flash_write_()) {
208 return false;
209 }
210
211 // Restore original flash mode for MD5 calculation
212 if (patched_flash_mode) {
213 this->buffer_[FLASH_MODE_OFFSET] = original_flash_mode;
214 }
215
216 // Update MD5 with original (unpatched) data
217 this->md5_.add(this->buffer_.get(), this->buffer_len_);
218
219 this->current_address_ += this->buffer_len_;
220 this->buffer_len_ = 0;
221
222 return true;
223}
224
226 // Similar to write_buffer_(), but without flash mode patching or MD5 update (for final padded write)
227 if (this->buffer_len_ == 0) {
228 return true;
229 }
230
231 if (!this->erase_sector_if_needed_() || !this->flash_write_()) {
232 return false;
233 }
234
235 this->current_address_ += this->buffer_len_;
236 this->buffer_len_ = 0;
237
238 return true;
239}
240
242 // Write any remaining buffered data
243 if (this->buffer_len_ > 0) {
244 // Add actual data to MD5 before padding
245 this->md5_.add(this->buffer_.get(), this->buffer_len_);
246
247 // Pad to 4-byte alignment for flash write
248 while (this->buffer_len_ % 4 != 0) {
249 this->buffer_[this->buffer_len_++] = 0xFF;
250 }
251 if (!this->write_buffer_final_()) {
252 this->abort();
254 }
255 }
256
257 // Calculate actual bytes written (exact uploaded size, excluding flash write padding)
258 size_t actual_size = this->bytes_received_;
259
260 // Check if any data was written
261 if (actual_size == 0) {
262 ESP_LOGE(TAG, "No data written");
263 this->abort();
265 }
266
267 // Verify MD5 if set (strict mode), otherwise use lenient mode
268 // In lenient mode (no MD5), we accept whatever was written
269 if (this->md5_set_) {
270 this->md5_.calculate();
271 if (!this->md5_.equals_bytes(this->expected_md5_)) {
272 ESP_LOGE(TAG, "MD5 mismatch");
273 this->abort();
275 }
276 } else {
277 // Lenient mode: adjust size to what was actually written
278 // This matches Arduino's Update.end(true) behavior
279 this->image_size_ = actual_size;
280 }
281
282 // Verify firmware header
283 if (!this->verify_end_()) {
284 this->abort();
286 }
287
288 // Write eboot command to copy firmware on next boot
289 eboot_command ebcmd;
290 ebcmd.action = ACTION_COPY_RAW;
291 ebcmd.args[0] = this->start_address_;
292 ebcmd.args[1] = 0x00000; // Destination: start of flash
293 ebcmd.args[2] = this->image_size_;
294 eboot_command_write(&ebcmd);
295
296 ESP_LOGI(TAG, "OTA update staged: 0x%08" PRIX32 " -> 0x00000, size=%zu", this->start_address_, this->image_size_);
297
298 // Clean up
299 this->buffer_.reset();
301
302 return OTA_RESPONSE_OK;
303}
304
306 this->buffer_.reset();
307 this->buffer_len_ = 0;
308 this->image_size_ = 0;
309 this->bytes_received_ = 0;
311}
312
314 uint32_t buf;
315 if (spi_flash_read(this->start_address_, &buf, 4) != SPI_FLASH_RESULT_OK) {
316 ESP_LOGE(TAG, "Failed to read firmware header");
317 return false;
318 }
319
320 uint8_t *bytes = reinterpret_cast<uint8_t *>(&buf);
321
322 // Check for GZIP (compressed firmware)
323 if (bytes[0] == GZIP_MAGIC_1 && bytes[1] == GZIP_MAGIC_2) {
324 // GZIP compressed - can't verify further
325 return true;
326 }
327
328 // Check firmware magic byte
329 if (bytes[0] != FIRMWARE_MAGIC) {
330 ESP_LOGE(TAG, "Invalid firmware magic: 0x%02X (expected 0x%02X)", bytes[0], FIRMWARE_MAGIC);
331 return false;
332 }
333
334#if !FLASH_MAP_SUPPORT
335 // Check if new firmware's flash size fits (only when auto-detection is disabled)
336 // With FLASH_MAP_SUPPORT (modern cores), flash size is auto-detected from chip
337 // NOLINTNEXTLINE(readability-static-accessed-through-instance)
338 uint32_t bin_flash_size = ESP.magicFlashChipSize((bytes[3] & 0xf0) >> 4);
339 // NOLINTNEXTLINE(readability-static-accessed-through-instance)
340 if (bin_flash_size > ESP.getFlashChipRealSize()) {
341 ESP_LOGE(TAG, "Firmware flash size (%" PRIu32 ") exceeds chip size (%" PRIu32 ")", bin_flash_size,
342 ESP.getFlashChipRealSize());
343 return false;
344 }
345#endif
346
347 return true;
348}
349
351 uint32_t data;
352 if (spi_flash_read(0x0000, &data, 4) != SPI_FLASH_RESULT_OK) {
353 return 0; // Default to QIO
354 }
355 return (reinterpret_cast<uint8_t *>(&data))[FLASH_MODE_OFFSET];
356}
357
358} // namespace esphome::ota
359#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)
OTAResponseTypes write(uint8_t *data, size_t len)
std::unique_ptr< uint8_t[]> buffer_
OTAResponseTypes begin(size_t image_size)
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.
bool verify_end_()
Verify the firmware header is valid.
bool flash_write_()
Write buffer to flash (does not update address or clear buffer)
uint8_t get_flash_chip_mode_()
Get current flash chip mode from flash header.
void preferences_prevent_write(bool prevent)
@ 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::unique_ptr< ArduinoLibreTinyOTABackend > make_ota_backend()
std::string size_t len
Definition helpers.h:892
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
int written
Definition helpers.h:936
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t