Home IO Control
ESPHome add-on for IO-Homecontrol devices
Loading...
Searching...
No Matches
lr1121_firmware_update_controller.cpp
Go to the documentation of this file.
1// IOHOME_LR1121_FIRMWARE_UPDATE is only visible after something pulls in esphome/core/defines.h
2// (via hub_internal.h -> hub_core.h -> esphome/core/hal.h) — these #includes must run before the
3// #ifdef check below, not after (see radio_lr1121_firmware_updater.h for the fuller explanation).
5#include "hub_internal.h"
8
9#ifdef IOHOME_LR1121_FIRMWARE_UPDATE
10
11// Only ever generated when this define is set (components/home_io_control/__init__.py), so this
12// #include must stay inside the guard above.
13#include "lr1121_firmware_update_image.h"
14
15#ifdef IOHOME_LR1121_BOOTLOADER_UPDATE
16// Only ever generated when the nested bootloader: sub-block is configured (__init__.py's
17// _create_lr1121_bootloader_update()), so this #include must stay inside this guard too.
18#include "lr1121_bootloader_loader_image.h"
19#endif
20
21#include "esphome/core/application.h"
22
23#include <algorithm>
24#include <cinttypes>
25#include <cstdio>
26#include <string>
27
28/// @file lr1121_firmware_update_controller.cpp
29/// @brief LR1121 transceiver-firmware-update feature — orchestration collaborator.
30/// @ingroup hioc_hub
31///
32/// Owns the impure side of the feature: the boot-time bootloader-version excursion, the cached
33/// flash verdict, the two-press confirmation window, and the button-triggered flash sequence
34/// itself. The pure decision logic lives in lr1121_firmware_decisions.h; the bootloader-mode SPI
35/// transport lives in radio_lr1121_firmware_updater.h/.cpp. ADR 0020 and ADR 0021 record the
36/// design; the single most important rule they state is repeated here because it is easy to
37/// violate by accident:
38///
39/// After any bootloader excursion, the chip is unconfigured. Exactly one of two things must
40/// happen next: radio_->init() runs (the boot-time excursion below), or the ESP32 reboots
41/// (run_flash_sequence_(), every exit after calling enter_bootloader()). There is no third
42/// option — an early `return` on an error path would leave the radio silently dead: it would
43/// answer SPI, look initialized to the driver, and never work again.
44///
45/// This applies even when enter_bootloader() itself returns false. Its RST-pulse/BUSY-strap entry
46/// sequence (radio_lr1121_firmware_updater.cpp) runs unconditionally, before the GetVersion read
47/// that determines its return value — so a false return (e.g. that confirmatory read timing out)
48/// does not mean the chip is untouched. It means entry was attempted and cannot be confirmed,
49/// which is reason to reboot, not reason to skip rebooting.
50
51namespace esphome {
52namespace home_io_control {
53
54namespace {
55
56constexpr uint32_t LR1121_FLASH_CONFIRM_WINDOW_MS = 60 * 1000; ///< Q3: ~60s, a button two paces away.
57
58std::string format_lr1121_fw_version(uint16_t version) {
59 if (version == 0)
60 return "unknown";
61 char buf[8];
62 snprintf(buf, sizeof(buf), "%u.%u", static_cast<unsigned>(version >> 8), static_cast<unsigned>(version & 0xFF));
63 return buf;
64}
65
66std::string format_hex16(uint16_t value) {
67 char buf[8];
68 snprintf(buf, sizeof(buf), "0x%04X", value);
69 return buf;
70}
71
72std::string format_hex8(uint8_t value) {
73 char buf[6];
74 snprintf(buf, sizeof(buf), "0x%02X", value);
75 return buf;
76}
77
78/// "unknown" for the same sentinel reason format_lr1121_fw_version() uses -- 0 means the boot-time
79/// excursion never successfully read a bootloader version.
80std::string format_lr1121_bootloader_version(uint16_t version) {
81 return version == 0 ? "unknown" : format_hex16(version);
82}
83
84/// @brief Outcome of the post-bootloader-entry sanity read, factored out of run_flash_sequence_()
85/// to keep its cognitive complexity within clang-tidy's threshold.
86enum class Lr1121SanityResult {
87 OK, ///< type matches, and either the version matches what boot recorded, or boot
88 ///< recorded nothing and the freshly-read version positively identifies an LR1121.
89 WRONG_TYPE, ///< type != LR1121_UPDATER_BOOTLOADER_TYPE -- not in bootloader mode at all.
90 VERSION_MISMATCH, ///< type is fine, but the version boot recorded no longer matches.
91 WRONG_CHIP_FAMILY, ///< Boot recorded nothing to compare against, and the freshly-read version
92 ///< does not identify an LR1121 -- see lr1121_check_bootloader_sanity()'s
93 ///< comment for why type alone cannot catch this.
94};
95
96/// @brief When the boot-time excursion never read a bootloader version (`known` is
97/// false), there is nothing to compare `sanity_bootloader_version` against a prior reading, but it
98/// must still be checked against something: `sanity_type` (LR11XX_TYPE_PRODUCTION_MODE, 0xDF) is
99/// reported by an LR1120 or LR1110 too, so passing the type check alone does not prove this chip is
100/// an LR1121 -- only the bootloader *version* does that (lr1121_bootloader_is_lr1121()). Without
101/// this, the "boot-time read failed, adopt whatever bootloader-mode read we get now" recovery path
102/// would erase and overwrite an LR1120/LR1110 with an LR1121 image on nothing more than a byte both
103/// chips share. This is the last check before EraseFlash.
104Lr1121SanityResult lr1121_check_bootloader_sanity(bool known, uint16_t known_bootloader_version, uint8_t sanity_type,
105 uint16_t sanity_bootloader_version) {
106 if (sanity_type != LR1121_UPDATER_BOOTLOADER_TYPE)
107 return Lr1121SanityResult::WRONG_TYPE;
108 if (known) {
109 if (sanity_bootloader_version != known_bootloader_version)
110 return Lr1121SanityResult::VERSION_MISMATCH;
111 return Lr1121SanityResult::OK;
112 }
113 if (!lr1121_bootloader_is_lr1121(sanity_bootloader_version))
114 return Lr1121SanityResult::WRONG_CHIP_FAMILY;
115 return Lr1121SanityResult::OK;
116}
117
118/// @brief Human-readable reason for a sanity-check failure, for the abort log line in
119/// run_flash_sequence_(). Factored out so that line stays one statement regardless of how many
120/// distinct sanity failures exist.
121std::string lr1121_sanity_failure_reason(Lr1121SanityResult sanity, uint16_t sanity_bootloader_version) {
122 switch (sanity) {
123 case Lr1121SanityResult::WRONG_TYPE:
124 return "wrong type";
125 case Lr1121SanityResult::WRONG_CHIP_FAMILY:
126 return "bootloader version " + format_hex16(sanity_bootloader_version) + " identifies " +
127 lr1121_chip_family_for_bootloader(sanity_bootloader_version) + ", not an LR1121";
128 case Lr1121SanityResult::VERSION_MISMATCH:
129 default:
130 return "bootloader version changed since boot";
131 }
132}
133
134/// @brief Log the post-flash version read-back. target_fw == 0 ("unknown", an explicitly
135/// supported config when a renamed image's filename carries no version) must not be compared
136/// numerically -- doing so flags a "post-flash version is X, expected unknown" mismatch that is
137/// not real.
138void lr1121_log_post_flash_verify_result(uint16_t new_fw, uint16_t target_fw) {
139 if (target_fw == 0) {
140 ESP_LOGI(detail::TAG,
141 "LR1121 firmware update: now running %s; this build had no expected version to compare against",
142 format_lr1121_fw_version(new_fw).c_str());
143 } else if (new_fw == target_fw) {
144 ESP_LOGI(detail::TAG, "LR1121 firmware update: success -- now running %s",
145 format_lr1121_fw_version(new_fw).c_str());
146 } else {
147 ESP_LOGW(detail::TAG, "LR1121 firmware update: post-flash version is %s, expected %s",
148 format_lr1121_fw_version(new_fw).c_str(), format_lr1121_fw_version(target_fw).c_str());
149 }
150}
151
152/// @brief Read and log GetHash (0x8004) after a successful write, while still in bootloader mode.
153///
154/// INFORMATIONAL ONLY -- never a pass/fail gate, and it cannot become one.
155///
156/// GetHash (0x8004) is undocumented: it is absent from the LR1121 User Manual's bootloader command
157/// table (which lists 0x8000/0x8003/0x8005/0x800B/0x800C/0x800D), and Semtech's own reference
158/// updater defines the opcode but never calls it. No algorithm, no hashed range, no published
159/// expected value.
160///
161/// The obvious hypothesis -- 16 bytes is MD5-sized and every published image ships a `.bin.md5`
162/// sidecar, so perhaps this is the image's MD5 -- was DISPROVEN on real hardware 2026-08-07:
163/// flashing lr1121_transceiver_0103.bin produced 321388054ac482d5ae703d0ab5e7af09, while that
164/// image's sidecar reads 7e44170c815485559880592e7713407f.
165///
166/// That result has a likely structural explanation: WriteFlashEncrypted decrypts on the fly, so
167/// flash holds *plaintext* firmware while the `.bin` is ciphertext. A hash over flash contents can
168/// therefore never equal the file's MD5 -- reproducing it host-side would need the decrypted image,
169/// and the key is Semtech's. So this value is not merely unverified, it is unverifiable by this
170/// project, and no future code change should try to gate on it.
171///
172/// It is worth logging where it works: a stable fingerprint of what is actually in flash makes "do
173/// these two boards hold the same image?" answerable. But it does not work everywhere -- bootloader
174/// 0x2101 returns a fixed non-value (0x14 then fifteen zero bytes), observed twice on hardware
175/// 2026-08-07 across two code paths and two images, where 0x2100 returned a plausible digest. That
176/// case is detected and reported as "unavailable" rather than printed as though it identified
177/// anything. The real correctness check is the post-flash version read-back that follows, which is
178/// also what Semtech's reference relies on.
179///
180/// A failed read (BUSY timeout) is logged and otherwise ignored: this diagnostic must never block
181/// or fail an otherwise-successful write, and the established recovery messaging elsewhere in this
182/// sequence already covers what to do about a genuinely bad flash.
183void lr1121_log_post_write_hash(Lr1121FirmwareUpdater &updater) {
184 uint8_t hash[LR1121_UPDATER_HASH_LENGTH] = {0};
185 if (!updater.read_hash(hash, sizeof(hash))) {
186 ESP_LOGW(detail::TAG,
187 "LR1121 firmware update: could not read the flash fingerprint (BUSY timeout). Harmless -- it is "
188 "only an identifier, not a correctness check; the version check below is what confirms the flash.");
189 return;
190 }
191 // Bootloader 0x2101 answers GetHash with a fixed non-value (0x14 then fifteen zero bytes),
192 // observed twice on hardware across two different code paths and two different images, where
193 // 0x2100 returned a plausible digest. Printing that as an "identifier for the image" would be a
194 // lie: it is the same bytes whatever is flashed. Detect it generically rather than matching the
195 // exact constant -- a genuine 16-byte digest ending in fifteen zero bytes is not a case worth
196 // designing around.
197 const bool degenerate = std::all_of(hash + 1, hash + LR1121_UPDATER_HASH_LENGTH, [](uint8_t b) { return b == 0; });
198 if (degenerate) {
199 ESP_LOGI(detail::TAG,
200 "LR1121 firmware update: no flash fingerprint available on this bootloader (GetHash returned a "
201 "fixed non-value). Harmless -- it was only ever an identifier, never a correctness check; the "
202 "firmware version reported below is what confirms the flash worked.");
203 return;
204 }
205 char hex[LR1121_UPDATER_HASH_LENGTH * 2 + 1];
206 for (size_t i = 0; i < LR1121_UPDATER_HASH_LENGTH; i++)
207 snprintf(hex + i * 2, 3, "%02x", hash[i]);
208 ESP_LOGI(detail::TAG,
209 "LR1121 firmware update: flash fingerprint %s -- an identifier for the image now on the chip, useful "
210 "for comparing two boards. It is not the image's MD5 and cannot be checked against anything; the "
211 "firmware version reported below is what confirms the flash worked.",
212 hex);
213}
214
215/// @brief Erase, then chunk-write, one image -- with percentage progress logging prefixed by
216/// `stage_label`. Shared by run_flash_sequence_() (the single-image transceiver flash) and,
217/// under IOHOME_LR1121_BOOTLOADER_UPDATE, run_bootloader_upgrade_sequence_()'s two writes
218/// so the erase/write/progress shape exists in exactly one place rather than being duplicated
219/// per stage.
220/// @return true if both erase and write succeeded; false leaves the region partially written --
221/// the caller decides what that means for recovery.
222bool lr1121_erase_and_write_image_(Lr1121FirmwareUpdater &updater, const char *stage_label, const uint32_t *image,
223 size_t word_count, uint32_t &erase_elapsed_ms, uint32_t &write_elapsed_ms) {
224 ESP_LOGI(detail::TAG, "%s: erasing radio flash, this takes a few seconds...", stage_label);
225 const uint32_t erase_start_ms = millis();
226 if (!updater.erase_flash()) {
227 ESP_LOGE(detail::TAG, "%s: erase failed (BUSY timeout)", stage_label);
228 return false;
229 }
230 erase_elapsed_ms = millis() - erase_start_ms;
231
232 size_t last_logged_words = 0;
233 const size_t log_step = std::max<size_t>(word_count / 10, 1);
234 const uint32_t write_start_ms = millis();
235 const bool write_ok = updater.write_image(image, word_count, [&](size_t done, size_t total) {
236 // Percentage-based, not time-based: gives a consistent ~10 lines regardless of how long the
237 // write actually takes, since image sizes differ nearly 4x between published versions and the
238 // total duration is unknown until measured on real hardware.
239 if (done - last_logged_words < log_step && done != total)
240 return;
241 last_logged_words = done;
242 ESP_LOGI(detail::TAG, "%s: flashing %zu/%zu words (%u%%)", stage_label, done, total,
243 static_cast<unsigned>((done * 100) / total));
244 });
245 write_elapsed_ms = millis() - write_start_ms;
246 if (!write_ok) {
247 ESP_LOGE(detail::TAG, "%s: write failed (BUSY timeout) after %" PRIu32 " ms", stage_label, write_elapsed_ms);
248 return false;
249 }
250 ESP_LOGI(detail::TAG, "%s: erase took %" PRIu32 " ms, write took %" PRIu32 " ms", stage_label, erase_elapsed_ms,
251 write_elapsed_ms);
252 return true;
253}
254
255/// The specific reason behind a NEEDS_CONFIRMATION verdict. Re-derives the reason from the same
256/// inputs lr1121_flash_decision() used, in the same priority order that function checks them, so
257/// the two can never drift apart:
258/// 1. the boot-time bootloader read never completed;
259/// 2. the normal-mode read never completed (no installed-firmware read to compare against);
260/// 3. no target version could be determined at all;
261/// 4. the target is absent from this build's advisory compatibility table (unverified, not
262/// refused);
263/// 5. the installed version specifically is unknown (device_type known-good, firmware bytes
264/// were not);
265/// 6. target not newer than installed.
266std::string lr1121_needs_confirmation_reason(uint8_t device_type, uint16_t bootloader_version, uint16_t installed_fw,
267 uint16_t target_fw) {
268 if (bootloader_version == 0)
269 return "the bootloader version could not be read at boot, so chip identity and bootloader compatibility "
270 "cannot be verified";
271 if (device_type == 0)
272 return "the installed firmware version could not be read (radio failed to initialize, or the read itself "
273 "failed)";
274 if (target_fw == 0)
275 return "no target firmware version could be determined for the configured image";
276 if (lr1121_bootloader_supports_target(target_fw, bootloader_version) == BootloaderSupport::UNKNOWN_TARGET) {
277 return "target firmware " + format_lr1121_fw_version(target_fw) +
278 " is not in this build's known bootloader-compatibility table (unverified, not refused)";
279 }
280 if (installed_fw == 0)
281 return "the installed firmware version is unknown";
282 return "target firmware " + format_lr1121_fw_version(target_fw) + " is not newer than the installed " +
283 format_lr1121_fw_version(installed_fw);
284}
285
286} // namespace
287
288Lr1121FirmwareUpdateController::Lr1121FirmwareUpdateController(RadioDriver **radio, SpiAccess *spi,
289 InternalGPIOPin **rst_pin, InternalGPIOPin **busy_pin,
290 bool *busy,
291 BeginBlockingExcursionFn begin_blocking_excursion,
293 : lr1121_flash_verdict_(FlashDecision::NEEDS_CONFIRMATION),
294 radio_(radio),
295 spi_(spi),
296 rst_pin_(rst_pin),
297 busy_pin_(busy_pin),
298 busy_(busy),
299 begin_blocking_excursion_(std::move(begin_blocking_excursion)),
300 hub_(hub) {}
301
302void Lr1121FirmwareUpdateController::run_boot_time_bootloader_read() {
303 this->lr1121_firmware_updater_ =
304 new (std::nothrow) Lr1121FirmwareUpdater(this->spi_, *this->rst_pin_, *this->busy_pin_);
305 if (this->lr1121_firmware_updater_ == nullptr) {
306 ESP_LOGE(detail::TAG, "LR1121 firmware update: failed to allocate the updater; bootloader version unknown");
307 return;
308 }
309
310 uint8_t type = 0;
311 uint16_t bootloader_version = 0;
312 if (!this->lr1121_firmware_updater_->enter_bootloader(type, bootloader_version)) {
313 ESP_LOGW(detail::TAG, "LR1121 firmware update: could not read the bootloader version at boot (BUSY timeout) -- "
314 "bootloader version stays unknown until the next boot");
315 return;
316 }
317 this->lr1121_bootloader_chip_type_ = type;
318 this->lr1121_bootloader_version_ = bootloader_version;
319 this->lr1121_bootloader_version_known_ = true;
320
321 // Boot back into normal firmware so the radio_->init() called right after this finds the chip
322 // in the mode it expects. If this specific command fails to send, init()'s own hardware-level
323 // RST pulse forces the chip out of the bootloader anyway -- this is a courtesy, not a
324 // dependency, so a failure here is a warning, not cause to skip caching the version above.
325 if (!this->lr1121_firmware_updater_->reboot(false)) {
326 ESP_LOGW(detail::TAG, "LR1121 firmware update: reboot-out-of-bootloader command failed to send (BUSY timeout); the "
327 "upcoming radio init's own hardware reset will recover it");
328 }
329}
330
331void Lr1121FirmwareUpdateController::cache_flash_verdict() {
332 uint8_t device_type = 0;
333 uint16_t installed_fw = 0;
334 if (*this->radio_ != nullptr && this->lr1121_firmware_updater_ != nullptr) {
335 // Re-read via the updater's own transport rather than plumbing a getter through
336 // RadioDriver/RadioLR1121 for this one caller, so radio_lr1121.h gains zero new surface area.
337 // GetVersion is the same benign, side-effect-free read
338 // RadioLR1121::dump_debug() already issues at arbitrary times without disrupting RX.
339 uint8_t fw_major = 0, fw_minor = 0;
340 // device_type/fw_major/fw_minor are left at their zero-initialized values above on a failed
341 // read (BUSY timeout), which is exactly the "unknown" sentinel lr1121_flash_decision() expects.
342 if (this->lr1121_firmware_updater_->read_normal_version(device_type, fw_major, fw_minor))
343 installed_fw = (static_cast<uint16_t>(fw_major) << 8) | fw_minor;
344 }
345 this->lr1121_installed_device_type_ = device_type;
346 this->lr1121_installed_fw_ = installed_fw;
347 // device_type (normal-mode chip identity, layer 3) and lr1121_bootloader_chip_type_
348 // (bootloader-mode `type` byte, layer 4) are distinct inputs -- passing the bootloader-mode byte
349 // where device_type belongs made every real LR1121 fail its own chip-identity check.
350 this->lr1121_flash_verdict_ =
351 lr1121_flash_decision(device_type, this->lr1121_bootloader_chip_type_, this->lr1121_bootloader_version_,
352 installed_fw, LR1121_FIRMWARE_UPDATE_TARGET_VERSION, false);
353 this->lr1121_flash_verdict_known_ = true;
354}
355
356// Returns a complete verdict sentence with no assumption about what (if anything) is armed --
357// callers append their own context-appropriate follow-up (or none, at boot). Splitting the
358// "press again" wording out of here is what keeps the boot-time config dump honest: nothing is
359// armed at boot, so a sentence claiming otherwise would be false there.
360std::string Lr1121FirmwareUpdateController::describe_flash_verdict() const {
361 const uint16_t target = LR1121_FIRMWARE_UPDATE_TARGET_VERSION;
362 const std::string prefix = "Firmware update target: " + format_lr1121_fw_version(target) + " -- ";
363
364 switch (this->lr1121_flash_verdict_) {
365 case FlashDecision::REJECT_WRONG_CHIP: {
366 // lr1121_flash_decision() checks layer 4 (bootloader-mode identity) before layer 3
367 // (normal-mode identity), and never reaches either while bootloader_version is the
368 // "unknown" sentinel -- so re-checking layer 4 here fully determines which one rejected.
369 if (this->lr1121_bootloader_chip_type_ != LR1121_BOOTLOADER_TYPE_FOR_FIRMWARE_DECISIONS ||
370 !lr1121_bootloader_is_lr1121(this->lr1121_bootloader_version_)) {
371 return prefix + "CANNOT PROCEED: bootloader version " + format_hex16(this->lr1121_bootloader_version_) +
372 " identifies " + lr1121_chip_family_for_bootloader(this->lr1121_bootloader_version_) + ", not an LR1121";
373 }
374 return prefix + "CANNOT PROCEED: normal-mode chip identity byte " +
375 format_hex8(this->lr1121_installed_device_type_) + " identifies " +
376 lr1121_chip_family_for_device_type(this->lr1121_installed_device_type_) + ", not an LR1121";
377 }
378 case FlashDecision::REJECT_BOOTLOADER_TOO_OLD: {
379 // REJECT_BOOTLOADER_TOO_OLD covers a bootloader/target mismatch in EITHER direction (see
380 // lr1121_bootloader_mismatch_kind()'s doc comment) -- the "too new" direction only became
381 // reachable once a chip could actually be running 0x2101, and its message would be exactly
382 // backwards if it reused the "too old" wording below.
383 const uint16_t required = lr1121_required_bootloader_for(target);
384 if (lr1121_bootloader_mismatch_kind(target, this->lr1121_bootloader_version_) ==
385 BootloaderMismatch::TARGET_NEEDS_OLDER) {
386 return prefix + "CANNOT PROCEED: this chip's bootloader " + format_hex16(this->lr1121_bootloader_version_) +
387 " is newer than this firmware supports (needs " + format_hex16(required) +
388 ") -- there is no downgrade path";
389 }
390 std::string message = prefix + "CANNOT PROCEED: needs bootloader " + format_hex16(required) + ", this chip has " +
391 format_hex16(this->lr1121_bootloader_version_);
392#ifndef IOHOME_LR1121_BOOTLOADER_UPDATE
393 // Only meaningful advice when the feature isn't compiled in at all: a build with the
394 // bootloader: sub-block already configured knows exactly which upgrade path applies (or
395 // doesn't), and trigger()/debug_lines() already append their own path-specific suffix --
396 // appending this one unconditionally would tell the user to add a block they already added,
397 // or contradict the path-specific suffix outright.
398 message += " -- add a bootloader: sub-block to lr1121_firmware_update: to enable the (irreversible) upgrade "
399 "path";
400#endif
401 return message;
402 }
403 case FlashDecision::ALREADY_INSTALLED:
404 return prefix + "already running the configured firmware, nothing to do";
405 case FlashDecision::NEEDS_CONFIRMATION:
406 return prefix +
407 lr1121_needs_confirmation_reason(this->lr1121_installed_device_type_, this->lr1121_bootloader_version_,
408 this->lr1121_installed_fw_, target) +
409 " (bootloader version " + format_lr1121_bootloader_version(this->lr1121_bootloader_version_) + ")";
410 case FlashDecision::PROCEED:
411 default:
412 return prefix + "ready to flash (press \"Flash LR1121 Radio Firmware\")";
413 }
414}
415
416// The verdict line must still be included when the bootloader version is unknown: the verdict is
417// cached independently (cache_flash_verdict() runs in setup() regardless of whether the boot-time
418// excursion succeeded), so an early return here on a failed boot-time excursion would drop a
419// verdict line that is actually available.
420#ifdef IOHOME_LR1121_BOOTLOADER_UPDATE
421std::string Lr1121FirmwareUpdateController::describe_bootloader_refusal(BootloaderUpgradePath path) const {
422 // Deliberately NOT built by appending to describe_flash_verdict(): that function opens with
423 // "CANNOT PROCEED", which reads as final and then contradicts a suffix explaining that the
424 // rewrite is in fact available. Someone who has just pressed a button wants, in this order: what
425 // happened, why, and what to do next. A returned string (rather than a direct ESP_LOGE) is what
426 // makes these testable at all -- host builds compile the logging macros to no-ops.
427 const std::string target_text = format_lr1121_fw_version(LR1121_FIRMWARE_UPDATE_TARGET_VERSION);
428 const std::string chip_text = format_hex16(this->lr1121_bootloader_version_);
429 const std::string required_text = format_hex16(lr1121_required_bootloader_for(LR1121_FIRMWARE_UPDATE_TARGET_VERSION));
430 const std::string prefix = "LR1121 firmware update: nothing was done, the radio was not touched. ";
431
432 switch (path) {
433 case BootloaderUpgradePath::AVAILABLE:
434 return prefix + "Firmware " + target_text + " needs bootloader " + required_text + " and this chip has " +
435 chip_text +
436 ", so the bootloader has to be rewritten first. To do that, turn on the \"Allow LR1121 Bootloader "
437 "Rewrite (Irreversible)\" switch and press this button again. A bootloader rewrite cannot be undone.";
438 case BootloaderUpgradePath::BLOCKED_UNKNOWN_TARGET:
439 return prefix + "This build does not recognise firmware " + target_text +
440 ", so it cannot tell which bootloader that image needs. The bootloader rewrite stays disabled rather "
441 "than risk an irreversible write on a guess.";
442 case BootloaderUpgradePath::BLOCKED_BOOTLOADER_NEWER:
443 return prefix + "This chip's bootloader " + chip_text + " is already newer than firmware " + target_text +
444 " supports (that image needs " + required_text + "), and there is no way back to an older bootloader.";
445 case BootloaderUpgradePath::NOT_APPLICABLE:
446 default:
447 // Not reached from trigger(), which falls through to the ordinary transceiver-only refusal
448 // for NOT_APPLICABLE; present so the switch is total.
449 return this->describe_flash_verdict();
450 }
451}
452#endif // IOHOME_LR1121_BOOTLOADER_UPDATE
453
454std::vector<std::string> Lr1121FirmwareUpdateController::debug_lines() const {
455 std::vector<std::string> lines;
456 if (this->lr1121_bootloader_version_known_) {
457 lines.push_back("LR1121 bootloader version: " + format_hex16(this->lr1121_bootloader_version_));
458 } else {
459 lines.push_back("LR1121 firmware update: bootloader version could not be read at boot");
460 }
461 if (this->lr1121_flash_verdict_known_)
462 lines.push_back(this->describe_flash_verdict());
463#ifdef IOHOME_LR1121_BOOTLOADER_UPDATE
464 // Computed independently of the cached verdict/press logic --
465 // lr1121_bootloader_upgrade_path() already folds in every precondition (known bootloader,
466 // right chip family, loader match), so this is correct however it's called.
468 /*block_present=*/true, this->lr1121_bootloader_version_known_, this->lr1121_bootloader_version_,
469 LR1121_BOOTLOADER_LOADER_FW, LR1121_FIRMWARE_UPDATE_TARGET_VERSION);
470 if (upgrade_path == BootloaderUpgradePath::AVAILABLE) {
471 // Deliberately short: this prints on every boot. The switch is discoverable in Home Assistant
472 // and the full reasoning (why the rewrite exists, why there is no reason to rush it) lives in
473 // docs/home_io_control.md and ADR 0021 -- a config dump is the wrong place to repeat it. What
474 // must survive the trim is the pair of versions and the fact that it cannot be undone.
475 lines.push_back("LR1121 bootloader rewrite: AVAILABLE -- needs bootloader " +
476 format_hex16(lr1121_required_bootloader_for(LR1121_FIRMWARE_UPDATE_TARGET_VERSION)) +
477 ", this chip has " + format_hex16(this->lr1121_bootloader_version_) +
478 ". A bootloader rewrite cannot be undone.");
479 } else if (upgrade_path == BootloaderUpgradePath::BLOCKED_UNKNOWN_TARGET) {
480 lines.push_back("LR1121 bootloader rewrite: configured, but inert -- this build does not know what bootloader the "
481 "configured target requires, so it will not gamble an irreversible write on it.");
482 } else if (upgrade_path == BootloaderUpgradePath::BLOCKED_BOOTLOADER_NEWER) {
483 lines.push_back("LR1121 bootloader rewrite: configured, but inert -- this chip's bootloader is already newer than "
484 "the configured target needs; there is no downgrade path.");
485 }
486#endif
487 return lines;
488}
489
490void Lr1121FirmwareUpdateController::dump_debug() const {
491 for (const auto &line : this->debug_lines())
492 ESP_LOGCONFIG(detail::TAG, " %s", line.c_str());
493}
494
495void Lr1121FirmwareUpdateController::arm_flash_confirmation_() {
496 this->lr1121_flash_confirmation_armed_ = true;
497 // Deliberately App.scheduler's self-keyed overload, not Component::set_timeout() (the
498 // key_extraction_responder.cpp idiom this would otherwise mirror). Component::set_timeout() records
499 // this component, and ESPHome's scheduler skips any scheduled item belonging to a *failed*
500 // component (Scheduler::should_skip_item_() -> is_item_failed_()). This method exists precisely
501 // for the recovery path where radio_->init() has failed and mark_failed() has already run -- if
502 // the callback were skipped there too, the confirmation window would never auto-disarm on
503 // exactly the board most likely to need a second press, degrading the two-press protection to
504 // "two presses ever". The self-keyed overload stores no Component, so it always fires. Do not
505 // "fix" this back to the named Component::set_timeout() idiom. The self key is the hub pointer
506 // (not this collaborator's `this`), so the recorded key is unchanged by the F5 move.
507 App.scheduler.set_timeout(static_cast<const void *>(this->hub_), LR1121_FLASH_CONFIRM_WINDOW_MS, [this]() {
508 // Guards against a stale timeout firing after a fresh press already consumed/re-armed the
509 // window — mirrors key_extraction_responder.cpp's KEY_EXTRACTION_AUTO_OFF_MS idiom.
510 if (!this->lr1121_flash_confirmation_armed_)
511 return;
512 this->lr1121_flash_confirmation_armed_ = false;
513 ESP_LOGI(detail::TAG, "LR1121 firmware update: confirmation window expired without a second press");
514 });
515}
516
517void Lr1121FirmwareUpdateController::trigger() {
518 // Guard 0: setup() deletes the driver and nulls radio_ when init() fails, but this button is a
519 // separate component whose press_action() still reaches the hub even after mark_failed().
520 // Deliberately still allow the attempt -- skipping only the standby call below -- since a radio
521 // that failed to initialize is exactly the case reflashing is meant to recover.
522 if (*this->radio_ == nullptr)
523 ESP_LOGW(detail::TAG, "LR1121 firmware update: radio_ is null (failed init); proceeding without standby");
524
525 // loop() guards every radio action behind `if (!this->busy_)`, so this is the same mechanism a
526 // blocking exchange already uses -- no new coordination. The safety here comes from ESPHome's
527 // cooperative single-threaded loop: an API-dispatched button press cannot land in the middle of
528 // a blocking exchange to begin with.
529 if (*this->busy_) {
530 ESP_LOGW(detail::TAG, "LR1121 firmware update: radio busy with another operation, ignoring press");
531 return;
532 }
533
534 if (this->lr1121_firmware_updater_ == nullptr || !this->lr1121_flash_verdict_known_) {
535 ESP_LOGE(detail::TAG, "LR1121 firmware update: no cached verdict available (setup() may have failed early)");
536 return;
537 }
538
539 const FlashDecision verdict = this->lr1121_flash_verdict_;
540
541 // REJECT_WRONG_CHIP never proceeds no matter what, including the bootloader-rewrite switch
542 // (hard rule 6) -- the verdict was already computed and logged at boot, so refusing here is a
543 // cached-verdict read, not a fresh bootloader entry.
544 if (verdict == FlashDecision::REJECT_WRONG_CHIP) {
545 ESP_LOGE(detail::TAG, "%s", this->describe_flash_verdict().c_str());
546 return;
547 }
548
549 if (verdict == FlashDecision::REJECT_BOOTLOADER_TOO_OLD) {
550#ifdef IOHOME_LR1121_BOOTLOADER_UPDATE
551 // The one place BootloaderUpgradePath::AVAILABLE can convert a hard rejection into the
552 // three-stage sequence -- see lr1121_bootloader_upgrade_path()'s doc comment for the full
553 // evaluation order. Every other outcome here still refuses without touching the chip.
555 /*block_present=*/true, this->lr1121_bootloader_version_known_, this->lr1121_bootloader_version_,
556 LR1121_BOOTLOADER_LOADER_FW, LR1121_FIRMWARE_UPDATE_TARGET_VERSION);
557 if (upgrade_path == BootloaderUpgradePath::AVAILABLE) {
558 if (!this->bootloader_rewrite_allowed_) {
559 ESP_LOGE(detail::TAG, "%s", this->describe_bootloader_refusal(upgrade_path).c_str());
560 return;
561 }
562 // The switch is read once, here, and replaces the two-press confirmation for this path --
563 // it is a permission, not something that stacks with the two-press window (hard rule 6's
564 // "never an override" applies the other way too: it only ever *adds* this one path).
565 ESP_LOGW(detail::TAG, "LR1121 bootloader rewrite: arming switch is on -- running the three-stage sequence now.");
566 this->run_bootloader_upgrade_sequence_();
567 return;
568 }
569 if (upgrade_path == BootloaderUpgradePath::BLOCKED_UNKNOWN_TARGET ||
570 upgrade_path == BootloaderUpgradePath::BLOCKED_BOOTLOADER_NEWER) {
571 ESP_LOGE(detail::TAG, "%s", this->describe_bootloader_refusal(upgrade_path).c_str());
572 return;
573 }
574 // upgrade_path == NOT_APPLICABLE: no upgrade possible/needed from this state (e.g. the
575 // boot-time bootloader read failed, or the configured loader doesn't match this bootloader) --
576 // fall through to the same refusal the transceiver-only build always gave.
577#endif
578 ESP_LOGE(detail::TAG, "%s", this->describe_flash_verdict().c_str());
579 return;
580 }
581
582 const bool proceeding = (verdict == FlashDecision::PROCEED) || this->lr1121_flash_confirmation_armed_;
583 if (!proceeding) {
584 // ALREADY_INSTALLED is the state a *successful* user spends the rest of the build's life
585 // in -- it must not read as a warning, and its "press again" follow-up talks about re-flashing
586 // rather than proceeding. Both facts are decided here, at the one call site where anything is
587 // actually about to be armed; describe_flash_verdict() itself stays neutral about it (see that
588 // function's comment) so the boot-time config dump never claims a window is armed.
589 const bool already_installed = (verdict == FlashDecision::ALREADY_INSTALLED);
590 const std::string confirm_suffix = " -- press \"Flash LR1121 Radio Firmware\" again within " +
591 std::to_string(LR1121_FLASH_CONFIRM_WINDOW_MS / 1000) + "s to " +
592 (already_installed ? "re-flash anyway" : "proceed anyway");
593 const std::string message = this->describe_flash_verdict() + confirm_suffix;
594 if (already_installed) {
595 ESP_LOGI(detail::TAG, "%s", message.c_str());
596 } else {
597 ESP_LOGW(detail::TAG, "%s", message.c_str());
598 }
599 this->arm_flash_confirmation_();
600 return;
601 }
602
603 this->lr1121_flash_confirmation_armed_ = false;
604 this->run_flash_sequence_();
605}
606
607void Lr1121FirmwareUpdateController::run_flash_sequence_() {
608 *this->busy_ = true;
609 // Raised for the duration of the flash so the log fills with the progress output below rather
610 // than component-blocking warnings. Component::warn_if_blocking_over_ is a centisecond uint8_t
611 // (max 2550ms) -- a flash can run far longer than that regardless, so this reduces warning
612 // spam, it cannot eliminate every warning for a longer block. Never restored -- every exit from
613 // this point on is App.safe_reboot(), which makes the saved value moot. (Injected: the hub's
614 // lambda sets the protected Component member.)
615 this->begin_blocking_excursion_();
616 if (*this->radio_ != nullptr)
617 (*this->radio_)->set_mode_standby(); // Never enter bootloader mode with RX armed.
618
619 // Every exit from here on is App.safe_reboot() -- see the file header's invariant. That includes
620 // the enter_bootloader() failure branch immediately below: its entry sequence runs unconditionally
621 // before the read that can time out, so a false return here does not mean the chip is untouched.
622 uint8_t sanity_type = 0;
623 uint16_t sanity_bootloader_version = 0;
624 if (!this->lr1121_firmware_updater_->enter_bootloader(sanity_type, sanity_bootloader_version)) {
625 ESP_LOGE(detail::TAG,
626 "LR1121 firmware update: bootloader entry could not be confirmed (BUSY timeout on the verification "
627 "read) -- the entry sequence itself already ran, so the chip may be unconfigured; rebooting to "
628 "recover it rather than risking a silently dead radio");
629 App.safe_reboot();
630 return;
631 }
632
633 const Lr1121SanityResult sanity = lr1121_check_bootloader_sanity(
634 this->lr1121_bootloader_version_known_, this->lr1121_bootloader_version_, sanity_type, sanity_bootloader_version);
635 if (sanity != Lr1121SanityResult::OK) {
636 const std::string sanity_reason = lr1121_sanity_failure_reason(sanity, sanity_bootloader_version);
637 ESP_LOGE(
638 detail::TAG,
639 "LR1121 firmware update: bootloader-entry sanity check failed (%s; read type=0x%02X bootloader=%s, "
640 "boot-time bootloader was %s) -- aborting before erasing anything",
641 sanity_reason.c_str(), sanity_type, format_hex16(sanity_bootloader_version).c_str(),
642 this->lr1121_bootloader_version_known_ ? format_hex16(this->lr1121_bootloader_version_).c_str() : "unknown");
643 this->lr1121_firmware_updater_->reboot(false);
644 App.safe_reboot();
645 return;
646 }
647 if (!this->lr1121_bootloader_version_known_) {
648 // Boot never got a reading, and a radio that failed to initialize is exactly the case
649 // reflashing is meant to recover, so this path stays open; the type check just
650 // above is all we could verify, so adopt this read for the rest of the attempt and future log
651 // lines rather than leaving lr1121_bootloader_version_ stuck at the "unknown" sentinel.
652 ESP_LOGI(detail::TAG,
653 "LR1121 firmware update: boot-time bootloader version was unknown; type check passed and bootloader "
654 "%s is now adopted",
655 format_hex16(sanity_bootloader_version).c_str());
656 this->lr1121_bootloader_chip_type_ = sanity_type;
657 this->lr1121_bootloader_version_ = sanity_bootloader_version;
658 this->lr1121_bootloader_version_known_ = true;
659 }
660
661 uint32_t erase_elapsed_ms = 0, write_elapsed_ms = 0;
662 if (!lr1121_erase_and_write_image_(*this->lr1121_firmware_updater_, "LR1121 firmware update",
663 LR1121_FIRMWARE_UPDATE_IMAGE, LR1121_FIRMWARE_UPDATE_IMAGE_WORDS, erase_elapsed_ms,
664 write_elapsed_ms)) {
665 ESP_LOGE(detail::TAG,
666 "LR1121 firmware update: the radio firmware is now incomplete. This is recoverable: after this "
667 "reboot, press the button again to re-flash.");
668 App.safe_reboot();
669 return;
670 }
671
672 // Read while still in bootloader mode, before rebooting into the newly written image -- see
673 // lr1121_log_post_write_hash()'s comment for why this is diagnostic-only.
674 lr1121_log_post_write_hash(*this->lr1121_firmware_updater_);
675
676 if (!this->lr1121_firmware_updater_->reboot(false)) {
677 ESP_LOGW(detail::TAG, "LR1121 firmware update: reboot-to-image command failed to send (BUSY timeout)");
678 } else {
679 uint8_t device_type = 0, fw_major = 0, fw_minor = 0;
680 if (this->lr1121_firmware_updater_->read_normal_version(device_type, fw_major, fw_minor)) {
681 const uint16_t new_fw = (static_cast<uint16_t>(fw_major) << 8) | fw_minor;
682 lr1121_log_post_flash_verify_result(new_fw, LR1121_FIRMWARE_UPDATE_TARGET_VERSION);
683 } else {
684 ESP_LOGW(detail::TAG, "LR1121 firmware update: could not read back the post-flash version (BUSY timeout)");
685 }
686 }
687
688 // A clean ESP32 restart is the post-flash path rather than re-running radio_->init() in place:
689 // by now init() has long since run and attached a DIO9 interrupt, so re-attachment, stale
690 // driver state and partial reconfiguration are all avoided at once.
691 App.safe_reboot();
692}
693
694#ifdef IOHOME_LR1121_BOOTLOADER_UPDATE
695
696void Lr1121FirmwareUpdateController::run_bootloader_upgrade_sequence_() {
697 *this->busy_ = true;
698 this->begin_blocking_excursion_();
699 if (*this->radio_ != nullptr)
700 (*this->radio_)->set_mode_standby();
701
702 ESP_LOGW(detail::TAG,
703 "LR1121 bootloader rewrite: starting the three-stage sequence, ~10s total. Mains power, not "
704 "battery -- do not interrupt power. Stage 2 has no recovery path in this project if power is lost.");
705
706 // --- Stage 1a: bootloader mode -- erase + write the loader image. Every exit from here on is
707 // App.safe_reboot() (see this method's doc comment in lr1121_firmware_update_controller.h). ---
708 uint8_t sanity_type = 0;
709 uint16_t sanity_bootloader_version = 0;
710 if (!this->lr1121_firmware_updater_->enter_bootloader(sanity_type, sanity_bootloader_version)) {
711 ESP_LOGE(detail::TAG,
712 "LR1121 bootloader rewrite: Stage 1a bootloader entry could not be confirmed (BUSY timeout) -- "
713 "the bootloader itself is untouched, this is recoverable: press the button again to retry.");
714 App.safe_reboot();
715 return;
716 }
717
718 const Lr1121SanityResult sanity = lr1121_check_bootloader_sanity(
719 this->lr1121_bootloader_version_known_, this->lr1121_bootloader_version_, sanity_type, sanity_bootloader_version);
720 if (sanity != Lr1121SanityResult::OK) {
721 const std::string sanity_reason = lr1121_sanity_failure_reason(sanity, sanity_bootloader_version);
722 ESP_LOGE(detail::TAG,
723 "LR1121 bootloader rewrite: Stage 1a sanity check failed (%s) -- aborting before erasing anything; "
724 "the bootloader is untouched, this is recoverable: press the button again to retry.",
725 sanity_reason.c_str());
726 this->lr1121_firmware_updater_->reboot(false);
727 App.safe_reboot();
728 return;
729 }
730 // No "adopt an unknown boot-time reading" branch here, unlike run_flash_sequence_()'s
731 // equivalent point: this function only ever runs when lr1121_bootloader_upgrade_path() returned
732 // AVAILABLE (trigger(), the only caller), and that function's rule 2 returns NOT_APPLICABLE
733 // whenever !lr1121_bootloader_version_known_ -- so an unknown bootloader can never reach this
734 // far. Not adding that branch here is deliberate: it would silently imply a reachable state that
735 // doesn't exist, right next to the irreversible write.
736
737 uint32_t erase_elapsed_ms = 0, write_elapsed_ms = 0;
738 if (!lr1121_erase_and_write_image_(
739 *this->lr1121_firmware_updater_, "LR1121 bootloader rewrite: Stage 1a (loader write)",
740 LR1121_BOOTLOADER_LOADER_IMAGE, LR1121_BOOTLOADER_LOADER_IMAGE_WORDS, erase_elapsed_ms, write_elapsed_ms)) {
741 ESP_LOGE(detail::TAG,
742 "LR1121 bootloader rewrite: Stage 1a failed -- the bootloader is untouched, this is recoverable: "
743 "press the button again to retry.");
744 App.safe_reboot();
745 return;
746 }
747
748 // --- Stage 1b: reboot into the loader; require it reports fw == 0x2100. Last checkpoint before
749 // the irreversible write -- a loader that did not land is caught here, not in Stage 2. ---
750 if (!this->lr1121_firmware_updater_->reboot(false)) {
751 ESP_LOGE(detail::TAG,
752 "LR1121 bootloader rewrite: Stage 1b reboot-into-loader command failed to send (BUSY timeout) -- "
753 "the bootloader is untouched, this is recoverable: press the button again to retry.");
754 App.safe_reboot();
755 return;
756 }
757 uint8_t loader_device_type = 0, loader_fw_major = 0, loader_fw_minor = 0;
758 // Read failure and version mismatch are deliberately not folded into one "fw == 0" check: this
759 // is the last checkpoint before the irreversible write, so a BUSY timeout (the chip reported
760 // nothing) must not be logged as though the chip positively reported firmware 0x0000.
761 if (!this->lr1121_firmware_updater_->read_normal_version(loader_device_type, loader_fw_major, loader_fw_minor)) {
762 ESP_LOGE(detail::TAG,
763 "LR1121 bootloader rewrite: Stage 1b checkpoint failed -- could not read the chip's firmware version "
764 "after the reboot (BUSY timeout). Aborting before the irreversible write; the bootloader is "
765 "untouched, this is recoverable: press the button again to retry.");
766 App.safe_reboot();
767 return;
768 }
769 // The version alone does NOT prove the loader is running: the loader image reports 0x2100, and
770 // so does the *bootloader* (LR1121_LOADER_2100 and LR1121_BOOTLOADER_2100 are the same number by
771 // design). reboot() only confirms the command was sent, never that the chip acted on it, so a
772 // chip that stayed in the bootloader would answer this read with exactly the bytes a successful
773 // loader boot produces -- and 0x8100 would then be sent to the bootloader, which does not
774 // implement it. `type` is the discriminator, and it is checked *positively* against the value the
775 // loader is known to report (LR1121_UPDATER_LOADER_DEVICE_TYPE, 0xDE, observed on hardware):
776 // 0xDE and the bootloader's 0xDF differ by one bit, so "anything but 0xDF" would accept a
777 // single-bit corruption of exactly the byte this check exists to trust.
778 if (loader_device_type != LR1121_UPDATER_LOADER_DEVICE_TYPE) {
779 const bool still_in_bootloader = loader_device_type == LR1121_UPDATER_BOOTLOADER_TYPE;
780 ESP_LOGE(detail::TAG,
781 "LR1121 bootloader rewrite: Stage 1b checkpoint failed -- chip reports type=0x%02X, expected the "
782 "loader's 0x%02X%s. The loader is not confirmed to be running, so 0x8100 must not be sent. "
783 "Aborting before the irreversible write; the bootloader is untouched, this is recoverable: press "
784 "the button again to retry.",
785 loader_device_type, LR1121_UPDATER_LOADER_DEVICE_TYPE,
786 still_in_bootloader ? " (0xDF means the chip never left bootloader mode)" : "");
787 App.safe_reboot();
788 return;
789 }
790 const uint16_t loader_running_fw = (static_cast<uint16_t>(loader_fw_major) << 8) | loader_fw_minor;
791 if (loader_running_fw != LR1121_LOADER_2100) {
792 ESP_LOGE(detail::TAG,
793 "LR1121 bootloader rewrite: Stage 1b checkpoint failed -- chip reports firmware %s after the "
794 "reboot, expected the loader's %s. Aborting before the irreversible write; the bootloader is "
795 "untouched, this is recoverable: press the button again to retry.",
796 format_lr1121_fw_version(loader_running_fw).c_str(), format_lr1121_fw_version(LR1121_LOADER_2100).c_str());
797 App.safe_reboot();
798 return;
799 }
800 ESP_LOGI(detail::TAG,
801 "LR1121 bootloader rewrite: Stage 1b checkpoint passed -- chip in transceiver mode: type=0x%02X fw=%s",
802 loader_device_type, format_lr1121_fw_version(loader_running_fw).c_str());
803
804 // --- Stage 2: normal mode, the loader is the running firmware. The one irreversible write. ---
805 ESP_LOGW(detail::TAG,
806 "LR1121 bootloader rewrite: Stage 2 -- rewriting the bootloader now. This step cannot be undone. Do "
807 "not interrupt power.");
808 if (!this->lr1121_firmware_updater_->update_bootloader()) {
809 ESP_LOGE(detail::TAG,
810 "LR1121 bootloader rewrite: Stage 2 UpdateBootloader timed out waiting for BUSY -- outcome "
811 "unknown, the bootloader may be mid-write. There is no recovery path in this project for this "
812 "failure. Rebooting.");
813 App.safe_reboot();
814 return;
815 }
816
817 // Semtech's reference tool issues exactly this read between UpdateBootloader and
818 // VerifyBootloader. Kept so the wire traffic through the one untestable stage stays identical to
819 // the vendor's known-working sequence, and because command_status is the only direct report of
820 // whether 0x8100 was accepted -- without it, a rejected command is indistinguishable from a
821 // completed-but-bad write. Diagnostic only (Semtech ignores the result too); the gate is the six
822 // check bits below.
823 Lr1121UpdaterStatus updater_status;
824 if (!this->lr1121_firmware_updater_->read_updater_status(updater_status)) {
825 ESP_LOGW(detail::TAG,
826 "LR1121 bootloader rewrite: Stage 2 status read timed out (BUSY) -- continuing to the verification "
827 "read, which is what actually decides the outcome");
828 } else if (updater_status.command_status != Lr1121UpdaterCommandStatus::OK &&
829 updater_status.command_status != Lr1121UpdaterCommandStatus::DATA) {
830 ESP_LOGE(detail::TAG,
831 "LR1121 bootloader rewrite: Stage 2 chip reports command_status=%u after UpdateBootloader (0=FAIL, "
832 "1=PERR) -- the chip did not accept 0x8100, which most likely means the bootloader was NOT "
833 "rewritten. The verification below decides; report this line if it appears.",
834 static_cast<unsigned>(updater_status.command_status));
835 } else {
836 ESP_LOGI(detail::TAG, "LR1121 bootloader rewrite: Stage 2 chip accepted UpdateBootloader (command_status=%u)",
837 static_cast<unsigned>(updater_status.command_status));
838 }
839
840 Lr1121BootloaderVerification verification;
841 if (!this->lr1121_firmware_updater_->verify_bootloader(verification)) {
842 ESP_LOGE(detail::TAG,
843 "LR1121 bootloader rewrite: Stage 2 VerifyBootloader read timed out (BUSY) after the write already "
844 "ran -- outcome unknown. There is no recovery path in this project for this failure. Rebooting.");
845 App.safe_reboot();
846 return;
847 }
848 if (!verification.all_checks_passed()) {
849 ESP_LOGE(detail::TAG,
850 "LR1121 bootloader rewrite: Stage 2 verification failed after the write already ran (signature=%d "
851 "version=%d use_case=%d version_major=%d version_minor=%d anti_rollback=%d) -- the write already "
852 "happened; do NOT retry Stage 2. There is no recovery path in this project for this failure. "
853 "Rebooting.",
854 verification.signature_verified, verification.version_verified, verification.use_case_verified,
855 verification.version_major_verified, verification.version_minor_verified,
856 verification.anti_rollback_verified);
857 App.safe_reboot();
858 return;
859 }
860
861 if (!this->lr1121_firmware_updater_->updater_reboot(false)) {
862 ESP_LOGE(detail::TAG,
863 "LR1121 bootloader rewrite: Stage 2 post-verify reboot command failed to send (BUSY timeout) -- "
864 "the write and verification both succeeded, but the chip's resulting state cannot be confirmed. "
865 "Rebooting the ESP32.");
866 App.safe_reboot();
867 return;
868 }
869 // Success is INVERTED here: the new bootloader is expected to refuse the loader image (built for
870 // the OLD bootloader) and stay in the bootloader rather than boot it (ADR 0021). A boot back
871 // into the loader here would mean the new bootloader is not actually running.
872 uint8_t post_update_type = 0;
873 uint16_t post_update_bootloader_version = 0;
874 const bool post_update_read_ok =
875 this->lr1121_firmware_updater_->read_bootloader_version(post_update_type, post_update_bootloader_version);
876 if (!post_update_read_ok || post_update_type != LR1121_UPDATER_BOOTLOADER_TYPE ||
877 post_update_bootloader_version != LR1121_BOOTLOADER_2101) {
878 ESP_LOGE(detail::TAG,
879 "LR1121 bootloader rewrite: Stage 2 succeeded but the chip is not behaving as expected afterward "
880 "(read_ok=%d type=0x%02X bootloader=%s; expected to stay in the bootloader reporting 0x2101) -- "
881 "the write already happened; this is NOT the recoverable kind of failure. If the chip still "
882 "answers a bootloader-mode GetVersion with a sane version, the strap works and a transceiver "
883 "image can be written for whichever bootloader it reports -- but do not auto-retry Stage 2. "
884 "Rebooting.",
885 post_update_read_ok, post_update_type, format_hex16(post_update_bootloader_version).c_str());
886 App.safe_reboot();
887 return;
888 }
889 this->lr1121_bootloader_chip_type_ = post_update_type;
890 this->lr1121_bootloader_version_ = post_update_bootloader_version;
891 ESP_LOGI(detail::TAG, "LR1121 bootloader rewrite: Stage 2 complete -- bootloader is now 0x2101.");
892
893 // --- Stage 3: re-enter the bootloader explicitly (do not rely on Stage 2's implicit state) and
894 // write the transceiver image. Full recovery from here: the bootloader is already 0x2101 and the
895 // transceiver image is already resident in ESP32 flash (the compile-time recovery-image rule). ---
896 uint8_t stage3_type = 0;
897 uint16_t stage3_bootloader_version = 0;
898 if (!this->lr1121_firmware_updater_->enter_bootloader(stage3_type, stage3_bootloader_version)) {
899 ESP_LOGE(detail::TAG,
900 "LR1121 bootloader rewrite: Stage 3 bootloader entry could not be confirmed (BUSY timeout) -- the "
901 "bootloader was already rewritten successfully in Stage 2, so this is recoverable: press the "
902 "ordinary flash button again (no switch needed) once power is stable.");
903 App.safe_reboot();
904 return;
905 }
906 if (stage3_type != LR1121_UPDATER_BOOTLOADER_TYPE || stage3_bootloader_version != LR1121_BOOTLOADER_2101) {
907 ESP_LOGE(detail::TAG,
908 "LR1121 bootloader rewrite: Stage 3 sanity check failed (type=0x%02X bootloader=%s, expected "
909 "0x2101) -- aborting before erasing the transceiver region. The bootloader was already rewritten "
910 "successfully in Stage 2; this is recoverable: press the ordinary flash button again.",
911 stage3_type, format_hex16(stage3_bootloader_version).c_str());
912 App.safe_reboot();
913 return;
914 }
915 this->lr1121_bootloader_chip_type_ = stage3_type;
916 this->lr1121_bootloader_version_ = stage3_bootloader_version;
917
918 if (!lr1121_erase_and_write_image_(
919 *this->lr1121_firmware_updater_, "LR1121 bootloader rewrite: Stage 3 (transceiver write)",
920 LR1121_FIRMWARE_UPDATE_IMAGE, LR1121_FIRMWARE_UPDATE_IMAGE_WORDS, erase_elapsed_ms, write_elapsed_ms)) {
921 ESP_LOGE(detail::TAG,
922 "LR1121 bootloader rewrite: Stage 3 failed -- the bootloader is already on 0x2101 (that part is "
923 "done and does not need to be repeated); this is recoverable: after this reboot, the ordinary "
924 "flash button (no switch needed) can retry the transceiver write.");
925 App.safe_reboot();
926 return;
927 }
928
929 lr1121_log_post_write_hash(*this->lr1121_firmware_updater_);
930
931 if (!this->lr1121_firmware_updater_->reboot(false)) {
932 ESP_LOGW(detail::TAG, "LR1121 bootloader rewrite: Stage 3 reboot-to-image command failed to send (BUSY timeout)");
933 } else {
934 uint8_t device_type = 0, fw_major = 0, fw_minor = 0;
935 if (this->lr1121_firmware_updater_->read_normal_version(device_type, fw_major, fw_minor)) {
936 const uint16_t new_fw = (static_cast<uint16_t>(fw_major) << 8) | fw_minor;
937 lr1121_log_post_flash_verify_result(new_fw, LR1121_FIRMWARE_UPDATE_TARGET_VERSION);
938 } else {
939 ESP_LOGW(detail::TAG, "LR1121 bootloader rewrite: could not read back the post-flash version (BUSY timeout)");
940 }
941 }
942
943 App.safe_reboot();
944}
945
946#endif // IOHOME_LR1121_BOOTLOADER_UPDATE
947
948} // namespace home_io_control
949} // namespace esphome
950
951#endif // IOHOME_LR1121_FIRMWARE_UPDATE
The main IO-Homecontrol component.
Definition hub_core.h:90
Abstract radio driver for IO-Homecontrol.
Interface for SPI bus access.
Internal helpers shared by the hub implementation .cpp files.
Pure decision logic for the LR1121 transceiver-firmware-update feature.
LR1121 transceiver-firmware-update feature — orchestration collaborator.
constexpr const char * TAG
Shared log tag for hub-level messages.
constexpr uint16_t lr1121_required_bootloader_for(uint16_t target_fw)
Required bootloader for a known target firmware version.
constexpr BootloaderSupport lr1121_bootloader_supports_target(uint16_t target_fw, uint16_t bootloader_version)
Look up whether target_fw is known to require bootloader_version.
constexpr BootloaderUpgradePath lr1121_bootloader_upgrade_path(bool block_present, bool bootloader_version_known, uint16_t bootloader_version, uint16_t loader_fw, uint16_t target_fw)
Whether the three-stage bootloader upgrade is applicable for the current cached state.
BootloaderUpgradePath
Whether the three-stage bootloader-rewrite sequence (ADR 0021) is applicable, and if not,...
constexpr const char * lr1121_chip_family_for_bootloader(uint16_t bootloader_version)
Human-readable chip family for a bootloader version that is not one of the two LR1121 values above,...
constexpr bool lr1121_bootloader_is_lr1121(uint16_t bootloader_version)
@ UNKNOWN_TARGET
target_fw does not appear in LR1121_KNOWN_BOOTLOADER_REQUIREMENTS at all.
constexpr FlashDecision lr1121_flash_decision(uint8_t device_type, uint8_t bootloader_chip_type, uint16_t bootloader_version, uint16_t installed_fw, uint16_t target_fw, bool already_confirmed)
The single decision point for whether/how to flash target_fw.
FlashDecision
Outcome of lr1121_flash_decision().
@ NEEDS_CONFIRMATION
Not unsafe, but not an unambiguous "yes" either — needs a second press.
std::function< void()> BeginBlockingExcursionFn
Raises the hub's "operation took a long time" warning threshold for a blocking radio excursion — writ...
Definition hub_hooks.h:39
constexpr BootloaderMismatch lr1121_bootloader_mismatch_kind(uint16_t target_fw, uint16_t bootloader_version)
Classify a bootloader/target mismatch by direction; see BootloaderMismatch.
constexpr const char * lr1121_chip_family_for_device_type(uint8_t device_type)
Human-readable chip family for a normal-mode device_type that is not the LR1121 value above,...
LR1121 bootloader-mode-*and*-loader-mode SPI transport, standalone from the running RadioDriver.