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