Files
meshcore-tth/src/helpers/NodeMaintenance.cpp
T

474 lines
19 KiB
C++

#include "NodeMaintenance.h"
// CUSTOM (TeTeHacko): moved out of examples/simple_repeater/main.cpp (4. 11. 2026),
// history included.
#define RADIO_SILENCE_FILE "/rsilence"
#ifndef RADIO_TXSTALL_MIN
#define RADIO_TXSTALL_MIN 15
#endif
#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;
#ifdef NODE_PWR_GUARD
pwrBegin(); // first: below the bootlock nothing else should run
#endif
uint8_t backoff;
silenceLoad(&backoff);
_silence.begin(millis(), radioActivity(), backoff);
_silence.setMinutes(_prefs->radio_silence_min);
_txstall.begin(millis(), _radio.getPacketsSent(), 0);
_txstall.setMinutes(RADIO_TXSTALL_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(int tx_queued, int tx_due) {
dfuTick();
#ifdef NODE_PWR_GUARD
pwrTick();
#endif
txStallTick(tx_queued, tx_due);
#ifdef FW_OTA
_fw.loop();
#endif
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);
}
// --- TX stall watchdog ----------------------------------------------------------
// The other half of the silence watchdog: a node that hears fine but no longer
// transmits. mast-three, 14. 11. 2026, during an rxps trial: `sent` frozen for 6+
// hours with the outbound queue full (32), RX counting, no tx_start_fail, no
// tx_timeout, no CAD timeout -- so no adverts, no replies, no admin login over
// the mesh, and nothing the silence watchdog could see. `rxps off` did not bring
// TX back, a reboot did. The cause is not known, so this keys on the symptom:
// packets waiting while the sent counter does not move. Never normal -- the
// longest legitimate holds (airtime budget, CAD retries) are seconds.
// Same staging as the silence watchdog: re-arm the radio (clears latched IRQ
// flags), then reboot. No persisted backoff: a node that cannot send is useless
// either way, and the queue-length/due numbers in the log say where it hung.
void NodeMaintenance::txStallTick(int tx_queued, int tx_due) {
_tx_queued = tx_queued;
_tx_due = tx_due;
uint32_t now = millis();
if (tx_queued <= 0) { // nothing waiting (or not reported): nothing can stall
_txstall.begin(now, _radio.getPacketsSent(), 0);
return;
}
switch (_txstall.poll(now, _radio.getPacketsSent())) {
case RadioSilenceWatchdog::KICK_RX:
Serial.printf("tx stall: %d queued (%d due), nothing sent for %lu min, re-arming radio\n",
tx_queued, tx_due, (unsigned long) (_txstall.quietMs(now) / 60000));
_radio.kickRx();
break;
case RadioSilenceWatchdog::REBOOT:
Serial.printf("tx stall: %d queued (%d due), still nothing sent after %lu min, rebooting\n",
tx_queued, tx_due, (unsigned long) (_txstall.quietMs(now) / 60000));
_silence_reboots++;
silenceSave(_silence.backoff());
delay(100); // let the line out
_board.reboot();
break;
default:
break;
}
}
bool NodeMaintenance::txStallCommand(const char* command, char* reply) {
if (strcmp(command, "get radio.txstall") == 0) {
if (_tx_queued < 0) {
strcpy(reply, "> n/a (this role does not report its queue)");
} else if (_txstall.minutes() == 0) {
strcpy(reply, "> off");
} else {
sprintf(reply, "> %u min, queued %d (due %d), no TX for %lu min, stage %u",
(unsigned) _txstall.minutes(), _tx_queued, _tx_due,
_tx_queued > 0 ? (unsigned long) (_txstall.quietMs(millis()) / 60000) : 0UL,
(unsigned) _txstall.stage());
}
return true;
}
if (memcmp(command, "set radio.txstall ", 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;
}
_txstall.setMinutes((uint16_t) m);
strcpy(reply, "OK (until reboot)");
return true;
}
return false;
}
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;
#ifdef FW_OTA
if (_fw.handleCommand(sender_timestamp, command, reply)) return true;
#endif
if (silenceCommand(command, reply)) return true;
if (txStallCommand(command, reply)) return true;
#ifdef NODE_PWR_GUARD
if (pwrCommand(command, reply)) return true;
#endif
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;
}
// --- battery thresholds (PWRMGT_RUNTIME), see helpers/LowVoltageGuard.h ---------
// Saved in their own small file, not in the prefs: no prefs-layout change, and a
// node without the file runs on the build defaults.
#ifdef NODE_PWR_GUARD
#define PWR_GUARD_FILE "/pwr_guard"
#ifndef PWRMGT_BOOTLOCK_DEFAULT
#ifdef PWRMGT_VOLTAGE_BOOTLOCK
#define PWRMGT_BOOTLOCK_DEFAULT PWRMGT_VOLTAGE_BOOTLOCK
#else
#define PWRMGT_BOOTLOCK_DEFAULT 0
#endif
#endif
#ifndef PWRMGT_CUTOFF_DEFAULT
#define PWRMGT_CUTOFF_DEFAULT 0
#endif
static void fmtMv(char* out, uint16_t mv) {
if (mv == 0) strcpy(out, "off"); else sprintf(out, "%u mV", (unsigned) mv);
}
void NodeMaintenance::pwrBegin() {
uint16_t v[2] = { PWRMGT_BOOTLOCK_DEFAULT, PWRMGT_CUTOFF_DEFAULT };
if (_fs && _fs->exists(PWR_GUARD_FILE)) {
#if defined(RP2040_PLATFORM)
File f = _fs->open(PWR_GUARD_FILE, "r");
#else
File f = _fs->open(PWR_GUARD_FILE);
#endif
if (f) {
uint16_t r[2];
if (f.read((uint8_t*) r, sizeof(r)) == sizeof(r) && !LowVoltageGuard::validate(r[0], r[1])) {
v[0] = r[0]; v[1] = r[1];
}
f.close();
}
}
_pwr.begin(millis(), v[0], v[1]);
Serial.printf("boot: pwr bootlock %u mV, cutoff %u mV (0 = off), battery %u mV\n",
(unsigned) v[0], (unsigned) v[1], (unsigned) _board.getBattMilliVolts());
// Below the bootlock this does not return: SYSTEMOFF until the LPCOMP wakes it.
// Also latches the reset/shutdown reasons, so it runs with the bootlock off too.
nrf().bootVoltageCheck(v[0]);
}
void NodeMaintenance::pwrSave() {
if (!_fs) return;
uint16_t v[2] = { _pwr.bootlock(), _pwr.cutoff() };
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
_fs->remove(PWR_GUARD_FILE);
File f = _fs->open(PWR_GUARD_FILE, FILE_O_WRITE);
#elif defined(RP2040_PLATFORM)
File f = _fs->open(PWR_GUARD_FILE, "w");
#else
File f = _fs->open(PWR_GUARD_FILE, "w", true);
#endif
if (!f) return;
f.write((const uint8_t*) v, sizeof(v));
f.close();
}
void NodeMaintenance::pwrTick() {
uint32_t now = millis();
if (!_pwr.due(now)) return;
uint16_t mv = _board.getBattMilliVolts();
if (_pwr.poll(now, mv, _board.isExternalPowered())) {
Serial.printf("pwr: battery %u mV, below the cutoff %u mV %u times in a row, switching off\n",
(unsigned) mv, (unsigned) _pwr.cutoff(), (unsigned) LowVoltageGuard::CUTOFF_SAMPLES);
delay(100); // let the line out
nrf().lowVoltageShutdown(); // does not return; the LPCOMP wakes it
}
}
bool NodeMaintenance::pwrCommand(const char* command, char* reply) {
char a[12], b[12];
if (strcmp(command, "get pwr") == 0) {
fmtMv(a, _pwr.bootlock());
fmtMv(b, _pwr.cutoff());
uint8_t why = nrf().getShutdownReason();
sprintf(reply, "> bootlock %s, cutoff %s, battery %u mV (at boot %u)%s, last off: %s",
a, b, (unsigned) _board.getBattMilliVolts(), (unsigned) nrf().getBootVoltage(),
_board.isExternalPowered() ? ", USB" : "", nrf().getShutdownReasonString(why));
return true;
}
bool is_boot = strncmp(command, "set pwr.bootlock ", 17) == 0;
bool is_cut = strncmp(command, "set pwr.cutoff ", 15) == 0;
if (!is_boot && !is_cut) return false;
const char* arg = command + (is_boot ? 17 : 15);
uint16_t mv = (strcmp(arg, "off") == 0) ? 0 : (uint16_t) atoi(arg);
uint16_t boot = is_boot ? mv : _pwr.bootlock();
uint16_t cut = is_cut ? mv : _pwr.cutoff();
const char* err = LowVoltageGuard::validate(boot, cut);
if (err) {
sprintf(reply, "Error: %s (%u-%u mV or off)", err,
(unsigned) LowVoltageGuard::MIN_MV, (unsigned) LowVoltageGuard::MAX_MV);
return true;
}
// No threshold above the battery right now: a mast admin would lock the node
// out -- it would not start after a reboot, or switch off within minutes.
uint16_t batt = _board.getBattMilliVolts();
if (mv != 0 && !_board.isExternalPowered() && batt >= LowVoltageGuard::GLITCH_MV && mv >= batt) {
sprintf(reply, "Error: battery is %u mV now, a threshold of %u mV would lock the node out",
(unsigned) batt, (unsigned) mv);
return true;
}
_pwr.set(boot, cut);
pwrSave();
fmtMv(a, _pwr.bootlock());
fmtMv(b, _pwr.cutoff());
sprintf(reply, "OK - bootlock %s, cutoff %s", a, b);
return true;
}
#endif // NODE_PWR_GUARD