#include "NodeMaintenance.h" // CUSTOM (TeTeHacko): moved out of examples/simple_repeater/main.cpp (4. 11. 2026), // history included. #define RADIO_SILENCE_FILE "/rsilence" #if defined(NRF52_PLATFORM) extern "C" { void enterUf2Dfu(void); void enterSerialDfu(void); void enterOTADfu(void); extern uint32_t g_hardfault_record[4]; // NRF52Board.cpp, .noinit: magic, pc, lr, psr } #endif // Why did this board last restart? The core latches NRF_POWER->RESETREAS in // init() before clearing it, and it is the only thing that distinguishes // "somebody typed `dfu`" from "the CPU locked up" or "the power went away" after // the fact -- the hole hit while chasing boards that vanished from USB after `dfu`. // The hardfault record is saved by the patched HardFault_Handler (framework // debug.cpp) in g_hardfault_record, .noinit (NRF52Board.cpp) -- the old fixed // 0x2003FFF0 at the end of RAM was where the bootloader's stack lands on reset. void NodeMaintenance::printBootDiag() { #if defined(NRF52_PLATFORM) uint32_t rr = readResetReason(); _reset_reason = rr; // The build epoch belongs next to it: it is what the clock comes up at when // nothing else sets it, so without it printed you cannot tell "fell back to // the build epoch" from "restored something" -- and comparing against the // epoch of a DIFFERENT build of the same tree invents discrepancies that are // not there. Cost one wrong conclusion here. Serial.printf("boot: FIRMWARE_BUILD_EPOCH=%lu\n", (unsigned long) FIRMWARE_BUILD_EPOCH); Serial.printf("boot: RESETREAS=0x%08lX%s%s%s%s%s\n", (unsigned long)rr, rr == 0 ? " (none set = power-on/brownout: power was removed)" : "", (rr & 0x01) ? " RESETPIN" : "", (rr & 0x02) ? " WATCHDOG" : "", (rr & 0x04) ? " SREQ(sw reset, e.g. `dfu`/`reboot`)" : "", (rr & 0x08) ? " LOCKUP(!)" : ""); volatile uint32_t* hf = g_hardfault_record; if (hf[0] == 0xFA010DEB) { _hardfault[0] = hf[1]; _hardfault[1] = hf[2]; _hardfault[2] = hf[3]; _hardfault_seen = true; Serial.printf("!!! HARDFAULT before last reboot: PC=%08lX LR=%08lX PSR=%08lX\n", (unsigned long)hf[1], (unsigned long)hf[2], (unsigned long)hf[3]); hf[0] = 0; // printed once; `get boot` keeps it until the next reset } #endif } // --- radio silence watchdog (#6), see RadioSilenceWatchdog.h ---------------- // Reboots it caused and the threshold backoff survive power loss in a small file, // written only right before such a reboot and once when the radio proves itself. void NodeMaintenance::silenceLoad(uint8_t* backoff) { *backoff = 0; if (!_fs || !_fs->exists(RADIO_SILENCE_FILE)) return; #if defined(RP2040_PLATFORM) File f = _fs->open(RADIO_SILENCE_FILE, "r"); #else File f = _fs->open(RADIO_SILENCE_FILE); #endif if (!f) return; if (f.read((uint8_t*)&_silence_reboots, sizeof(_silence_reboots)) != sizeof(_silence_reboots)) { _silence_reboots = 0; } if (f.read(backoff, 1) != 1) *backoff = 0; f.close(); } void NodeMaintenance::silenceSave(uint8_t backoff) { if (!_fs) return; #if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM) _fs->remove(RADIO_SILENCE_FILE); File f = _fs->open(RADIO_SILENCE_FILE, FILE_O_WRITE); #elif defined(RP2040_PLATFORM) File f = _fs->open(RADIO_SILENCE_FILE, "w"); #else File f = _fs->open(RADIO_SILENCE_FILE, "w", true); #endif if (!f) return; f.write((const uint8_t*)&_silence_reboots, sizeof(_silence_reboots)); f.write(&backoff, 1); f.close(); } void NodeMaintenance::begin(FILESYSTEM* fs, NodePrefs* prefs, CommonCLICallbacks* callbacks) { _fs = fs; _prefs = prefs; _callbacks = callbacks; uint8_t backoff; silenceLoad(&backoff); _silence.begin(millis(), radioActivity(), backoff); _silence.setMinutes(_prefs->radio_silence_min); Serial.printf("boot: radio silence watchdog %u min, reboots %lu, backoff x%u\n", (unsigned) _silence.minutes(), (unsigned long) _silence_reboots, (unsigned) (1u << _silence.backoff())); } void NodeMaintenance::loop() { dfuTick(); _fw.loop(); switch (_silence.poll(millis(), radioActivity())) { case RadioSilenceWatchdog::KICK_RX: Serial.printf("radio silence: nothing received for %lu min, re-arming RX\n", (unsigned long) (_silence.quietMs(millis()) / 60000)); _radio.kickRx(); break; case RadioSilenceWatchdog::REBOOT: Serial.printf("radio silence: still nothing after %lu min, rebooting\n", (unsigned long) (_silence.quietMs(millis()) / 60000)); _silence_reboots++; silenceSave(_silence.nextBackoff()); delay(100); // let the line out _board.reboot(); break; default: break; } if (_silence.takeBackoffCleared()) silenceSave(0); } bool NodeMaintenance::silenceCommand(const char* command, char* reply) { if (strcmp(command, "get radio.reboots") == 0) { sprintf(reply, "> %lu", (unsigned long) _silence_reboots); return true; } if (strcmp(command, "get radio.silence") == 0) { if (_silence.minutes() == 0) { strcpy(reply, "> off"); } else { sprintf(reply, "> %u min (now x%u), quiet %lu min, stage %u", (unsigned) _silence.minutes(), (unsigned) (1u << _silence.backoff()), (unsigned long) (_silence.quietMs(millis()) / 60000), (unsigned) _silence.stage()); } return true; } if (memcmp(command, "set radio.silence ", 18) == 0) { const char* arg = &command[18]; bool numeric = *arg != 0 && strspn(arg, "0123456789") == strlen(arg); int m = strcmp(arg, "off") == 0 ? 0 : (numeric ? atoi(arg) : -1); if (m < 0 || m > RadioSilenceWatchdog::MAX_MINUTES) { sprintf(reply, "ERR - minutes 0..%u (0/off = disabled)", (unsigned) RadioSilenceWatchdog::MAX_MINUTES); return true; } _prefs->radio_silence_min = (uint16_t) m; _callbacks->savePrefs(); _silence.setMinutes((uint16_t) m); strcpy(reply, "OK"); return true; } return false; } // --- dfu [uf2|serial|ota] ------------------------------------------------------ // Reboot straight into the bootloader, deterministically. // // This is what the 1200-baud touch was a bad approximation of. The Adafruit // bootloader picks its mode from GPREGRET at boot, and the core exposes exactly // that (cores/nRF5/wiring.c): reset_mcu() writes the magic and calls // NVIC_SystemReset(). // uf2 0x57 mass-storage drive, drop a .uf2 on it <- the usual one // serial 0x4e CDC only, for adafruit-nrfutil; no drive appears // ota 0xA8 BLE DFU // The touch only ever requested the *serial* mode, and on this build it worked // about half the time: twice it wedged a board out of USB and BLE entirely, with // no self-recovery (400 s) and no way back but a physical replug. This has no // such failure mode -- it is the same call the core makes, from a command. // // LOCAL ONLY. Over the mesh this would strand a node in a bootloader that waits // forever, on a mast, with no way back but a visit. sender_timestamp == 0 is the // same "physically present" test CommonCLI uses for `erase` and `set freq`. // Deferred so the reply reaches the console first -- the reset never returns. void NodeMaintenance::dfuTick() { #if defined(NRF52_PLATFORM) if (_dfu_at == 0 || (long)(millis() - _dfu_at) < 0) return; _dfu_at = 0; // Detach USB before the reset instead of letting the reset // yank it out from under the host. // // Measured 4. 8. 2026: 3 of 8 `dfu` commands left the board dead on USB *and* // BLE, recoverable only by a physical replug. The kernel log is unambiguous // about what that is and is not: // // good: usb 7-9: USB disconnect -> 3 s later idProduct=0045 (bootloader) // bad: usb 7-6: USB disconnect -> nothing, ever // // CORRECTION, same evening: "no enumeration errors, therefore the board is // wedged" was WRONG, and worth leaving here as a warning. The identical // signature -- disconnect, then nothing, no errors, port reporting // `not attached` -- was later produced on a KNOWN GOOD board purely by // toggling the root-hub port's `disable` from the host. So the log tells you // the host stopped seeing a device; it does NOT tell you why, and a missing // error message is not evidence of a dead board. // // What is still true: the failure follows resets that happen with USB active, // in BOTH directions (app->bootloader and bootloader->app), and a reset via // the RESET pin -- the double tap -- has never failed. That is what this // change is aimed at, and it is a hypothesis about the transition, not a // diagnosis of the chip. // // reset_mcu() (core wiring.c) disables the SoftDevice and resets with USBD // still enabled and possibly mid-transfer. Detaching first drops D+ while the // application is still alive and in control, which gives the host an // unambiguous disconnect and leaves USBD in a defined state at reset. // // Honest scope: this removes a class of race, it is NOT yet proven to be the // cause -- the failure is intermittent, so only a run of trials can say. The // RESETREAS line printed at boot is the other half of the instrument. // Dropping the D+ pullup directly rather than through TinyUSBDevice.detach(): // one register write, no dependency on the USB stack's headers being reachable // from here, and it is exactly what detach() does on this chip. NRF_USBD->USBPULLUP = 0; delay(150); if (_dfu_mode == 1) enterSerialDfu(); else if (_dfu_mode == 2) enterOTADfu(); else enterUf2Dfu(); #endif } bool NodeMaintenance::dfuCommand(uint32_t sender_timestamp, const char* command, char* reply) { if (memcmp(command, "dfu", 3) != 0 || (command[3] != 0 && command[3] != ' ')) return false; #if defined(NRF52_PLATFORM) if (sender_timestamp != 0) { strcpy(reply, "ERR: dfu is local-only (would strand the node in the bootloader)"); return true; } const char* arg = (command[3] == ' ') ? &command[4] : ""; while (*arg == ' ') arg++; if (strcmp(arg, "serial") == 0) { strcpy(reply, "OK - rebooting into serial DFU (CDC only, no drive)"); } else if (strcmp(arg, "ota") == 0) { strcpy(reply, "OK - rebooting into BLE OTA DFU"); } else if (arg[0] == 0 || strcmp(arg, "uf2") == 0) { strcpy(reply, "OK - rebooting into UF2 (drive appears in a few seconds)"); } else { strcpy(reply, "ERR: dfu [uf2|serial|ota]"); return true; } _dfu_at = millis() + 700; _dfu_mode = (strcmp(arg, "serial") == 0) ? 1 : (strcmp(arg, "ota") == 0 ? 2 : 0); #else strcpy(reply, "ERR: not an nRF52 board"); #endif return true; } bool NodeMaintenance::handleCommand(uint32_t sender_timestamp, const char* command, char* reply) { if (dfuCommand(sender_timestamp, command, reply)) return true; if (_fw.handleCommand(sender_timestamp, command, reply)) return true; if (silenceCommand(command, reply)) return true; if (strcmp(command, "get boot") == 0) { #if defined(NRF52_PLATFORM) if (_hardfault_seen) { sprintf(reply, "> RESETREAS=0x%08lX, HARDFAULT before it: PC=%08lX LR=%08lX PSR=%08lX", (unsigned long) _reset_reason, (unsigned long) _hardfault[0], (unsigned long) _hardfault[1], (unsigned long) _hardfault[2]); } else { sprintf(reply, "> RESETREAS=0x%08lX, no hardfault", (unsigned long) _reset_reason); } #else strcpy(reply, "> not recorded on this platform"); #endif return true; } return false; }