From be46cfa5fbef53a4b82e91d50375335629ffef4c Mon Sep 17 00:00:00 2001 From: TeTeHacko Date: Mon, 23 Nov 2026 13:22:24 +0100 Subject: [PATCH] Repeater (SenseCAP Solar): battery thresholds settable at runtime, and a cutoff that switches a running node off before the cell runs flat Co-Authored-By: Claude Opus 5.5 --- README.md | 15 ++- docs/power.md | 56 +++++--- docs/tth-commands.md | 4 +- src/helpers/LowVoltageGuard.h | 81 ++++++++++++ src/helpers/NRF52Board.h | 8 ++ src/helpers/NodeMaintenance.cpp | 124 ++++++++++++++++++ src/helpers/NodeMaintenance.h | 20 +++ .../test_low_voltage_guard.cpp | 97 ++++++++++++++ .../sensecap_solar/SenseCapSolarBoard.cpp | 2 + variants/sensecap_solar/platformio.ini | 4 + 10 files changed, 392 insertions(+), 19 deletions(-) create mode 100644 src/helpers/LowVoltageGuard.h create mode 100644 test/test_low_voltage_guard/test_low_voltage_guard.cpp diff --git a/README.md b/README.md index 2c11f301..c888fe44 100644 --- a/README.md +++ b/README.md @@ -158,7 +158,12 @@ Repeater navíc: 3,3 V nepouštěl k životu uzly na LiFePO4 nebo LTO. Firmware tak naběhne na jakékoli chemii článku; před hlubokým vybitím má chránit BMS nebo ochranná destička článku. Konfigurovatelná pojistka podle chemie čeká na upstream - ([#2088](https://github.com/meshcore-dev/MeshCore/pull/2088)). + ([#2088](https://github.com/meshcore-dev/MeshCore/pull/2088)). Výjimkou je + `SenseCap_Solar_repeater` (Li-ion, naše stožáry): pojistka je zapnutá + a oba prahy jdou nastavit za běhu, i přes mesh jako admin – + `set pwr.bootlock |off` (výchozí 3300, pod ním uzel nenaběhne a spí, + dokud se článek nezotaví) a `set pwr.cutoff |off` (výchozí vypnuto, + pod ním se běžící uzel vypne); `get pwr` ([docs/power.md](docs/power.md)). ### Senzory a companiony @@ -477,7 +482,13 @@ The repeater also has: 3.3 V threshold kept LiFePO4 and LTO nodes from booting. The firmware boots on any cell chemistry; deep-discharge protection is up to the BMS or the cell's protection board. A configurable, chemistry-aware lock is waiting - for upstream ([#2088](https://github.com/meshcore-dev/MeshCore/pull/2088)). + for upstream ([#2088](https://github.com/meshcore-dev/MeshCore/pull/2088)). The exception + is `SenseCap_Solar_repeater` (Li-ion, our masts): the lock is on and both + thresholds are settable at runtime, also as an admin over the mesh -- + `set pwr.bootlock |off` (default 3300; below it the node does not start + and sleeps until the cell recovers) and `set pwr.cutoff |off` (default + off; below it a running node switches off); `get pwr` + ([docs/power.md](docs/power.md)). ### Sensors and companions diff --git a/docs/power.md b/docs/power.md index 9c562ba0..53221290 100644 --- a/docs/power.md +++ b/docs/power.md @@ -170,29 +170,53 @@ a half-drained `rxlog`/`pktlog` page would otherwise wait for the next connection event — the bridge drains those on a 2-minute duty cycle, so a slower drain directly costs collected frames. -## A mast that runs flat (boot protection) +## A mast that runs flat: bootlock and cutoff A panel that gets no direct sun in winter (remote-mast faces east, 11/2026: -50 mV a day from mid-November with consumption unchanged) eventually drains -the cell. Without protection the node then browns out, and every bit of -light restarts it on a cell that cannot hold it -- a boot loop at the edge. +the cell. Without protection the node runs until the brown-out, and every bit +of light then restarts it on a cell that cannot hold it -- a boot loop at the +edge, with the cell deep-discharged on the way. `SenseCap_Solar_repeater` builds with `NRF52_POWER_MANAGEMENT` (upstream code, -wired in `variants/sensecap_solar`, only the switch was off): at boot the -node reads the battery and, below **3.3 V** (`PWRMGT_VOLTAGE_BOOTLOCK`), goes to -SYSTEMOFF with the LPCOMP armed on the battery input; it wakes when the -battery rises past the comparator threshold (3/8 VDD, ~3.4-3.7 V on the cell -per `variant.h`) and boots normally. USB power skips the check. +wired in `variants/sensecap_solar`) and `PWRMGT_RUNTIME` (ours), which gives +two thresholds, both saved on the node and settable from the console or as an +admin over the mesh: -What it does **not** do: switch off a running node as the battery falls -- -nothing in the firmware calls the runtime low-voltage shutdown. It protects -the restart, not the discharge. The clock goes back to the build epoch after -such a restart, as after any power loss (`gps duty` resyncs it, `time` sets it). +| | default | | +|---|---|---| +| `set pwr.bootlock \|off` | 3300 mV (`variant.h`) | at boot, below it the node goes to SYSTEMOFF and the LPCOMP wakes it when the battery recovers | +| `set pwr.cutoff \|off` | off | while running, three readings in a row (one a minute) below it switch the node off into the same SYSTEMOFF | +| `get pwr` | | both, the battery now and at boot, USB, the reason of the last switch-off | -**Not yet verified on hardware**: the thresholds come from `variant.h`. Bench -test with an adjustable supply on the battery terminals: boot at 3.2 V must -stay dark, raising it to ~3.8 V must wake the node by itself; `get boot` -then shows `RESETREAS=0x00020000` (bit 17, wake from LPCOMP). +The cutoff must stay below the bootlock -- a node switched off at the cutoff +starts again only past the bootlock, which is the hysteresis (e.g. cutoff +3400, bootlock 3600). The node refuses a threshold above the battery voltage +at that moment (it would lock itself out of a mast), USB power disarms the +cutoff and skips the boot check, a reading under 1 V counts as an ADC glitch. +The values live in `/pwr_guard`, not in the prefs; without the file the build +defaults apply (`PWRMGT_BOOTLOCK_DEFAULT`, `PWRMGT_CUTOFF_DEFAULT`). + +The wake level is not one of the thresholds: it is the LPCOMP comparing the +battery divider with 3/8 VDD, ~3.4-3.7 V on the cell per `variant.h`, fixed in +hardware steps. A bootlock above it means the node wakes, checks, and sleeps +again until the cell is past the bootlock -- harmless, each wake is a few ms. +The clock goes back to the build epoch after such a restart, as after any +power loss (`gps duty` resyncs it, `time` sets it). + +Why upstream has it off: a fixed 3.3 V lock kept LiFePO4 and LTO nodes from +booting (#2377, v1.18.0); a chemistry-aware version is open as #2088 (FS read +before the check, per-chemistry thresholds). Ours is narrower -- one board +with a known Li-ion cell, two numbers, `off` for either -- and has to be +reconciled with #2088 if that lands. + +**Not yet verified on hardware**: the logic has host tests +(`test/test_low_voltage_guard`), the thresholds and the wake level do not. +Bench test with an adjustable supply on the battery terminals: boot at 3.2 V +must stay dark; raising it to ~3.8 V must wake the node by itself (`get boot` +then shows `RESETREAS=0x00020000`, bit 17, wake from LPCOMP); with a cutoff +set, lowering the supply below it must switch the node off within ~3 minutes +and `get pwr` after the wake must say `last off: Low Voltage`. ## Measuring this yourself — two traps diff --git a/docs/tth-commands.md b/docs/tth-commands.md index 4df4eb14..3dd4fe84 100644 --- a/docs/tth-commands.md +++ b/docs/tth-commands.md @@ -163,6 +163,7 @@ console shows its state. | `set radio.rxps off\|on\|balanced\|max`, `level <1-10> [preamble 16\|32]` / `get radio.rxps` | all, SX1262 only (`WITH_RX_POWERSAVING`, in the releases) | RX duty cycle: the radio sleeps between short listening windows. **Off by default.** `max` saved ~2.3 mA on the bench, but a mast on the live mesh lost 16 % of its reception -- see cli_commands.md and [power.md](power.md) | | `set batt.icon on\|off`, `set batt.icon.lo\|hi ` | all | battery level as an icon at the end of the advertised name (off by default; with a name too long for it the icon is left out, and the reply says so) | | `gps duty ...` | GPS boards | the receiver runs only around a clock sync; see cli_commands.md | +| `get pwr`, `set pwr.bootlock \|off`, `set pwr.cutoff \|off` | SenseCAP Solar repeater (`PWRMGT_RUNTIME`) | battery thresholds: don't start below the bootlock, switch a running node off below the cutoff (cutoff < bootlock, none above the battery right now); saved on the node, see [power.md](power.md) | | `clkreboot` | all | reset the clock to the build epoch and reboot -- the only way to move a clock backwards (`time` and `clock sync` refuse to) | ## Sensors @@ -192,7 +193,8 @@ The ones that change what a node does; set in `platformio.ini` / | `ACL_TS_MAX_AHEAD` | `86400` (s) | a client timestamp further ahead of the node's clock is not stored as the replay floor | | `LOCKED_NODE` | unset | a node that keeps its secrets from whoever holds it: `get prv.key`, `get guest.password` and `get bridge.secret` answer `Error: locked build` to everyone (USB and BLE console, an admin over the mesh); a companion serves only paired BLE (USB, UART and WiFi get the device info and nothing else) and its rescue CLI refuses `set pin`. Only half of it: [locked-bootloader.md](locked-bootloader.md) | | `LOGIN_FAIL_MAX`, `LOGIN_FAIL_SECS` | `4`, `180` (s) | after that many wrong passwords in the window no password is checked until it ends (an admin already in the ACL always gets in) | -| `NRF52_POWER_MANAGEMENT` | upstream: off; on in `SenseCap_Solar_repeater` (the masts) | boot protection: below `PWRMGT_VOLTAGE_BOOTLOCK` (SenseCAP: 3300 mV) the node does not start but sleeps in SYSTEMOFF until the battery recovers. Only at boot, nothing switches off a running node -- see [power.md](power.md) | +| `NRF52_POWER_MANAGEMENT`, `PWRMGT_RUNTIME` | upstream: off; on in `SenseCap_Solar_repeater` (the masts) | boot protection, and with `PWRMGT_RUNTIME` the runtime `pwr.bootlock` / `pwr.cutoff` above | +| `PWRMGT_BOOTLOCK_DEFAULT`, `PWRMGT_CUTOFF_DEFAULT` | `PWRMGT_VOLTAGE_BOOTLOCK` (SenseCAP 3300), `0` (mV) | thresholds for a node without `/pwr_guard` | Prefs saved on the node override the build defaults: a reflash keeps what a node already has; only a new node or one after `erase` takes them. diff --git a/src/helpers/LowVoltageGuard.h b/src/helpers/LowVoltageGuard.h new file mode 100644 index 00000000..ffa632b5 --- /dev/null +++ b/src/helpers/LowVoltageGuard.h @@ -0,0 +1,81 @@ +#pragma once + +#include + +// CUSTOM (TeTeHacko): battery thresholds of a solar node, settable at runtime. +// +// remote-mast (11/2026) faces east and gets no direct sun in winter: -50 mV a day +// with consumption unchanged. Upstream NRF52_POWER_MANAGEMENT only refuses to +// BOOT below a compiled threshold; nothing switches a RUNNING node off, so the +// cell runs down to the brown-out and the panel then restarts the node on a +// cell that cannot hold it. Two thresholds, both in mV, 0 = off: +// +// bootlock checked once at boot: below it the node goes to SYSTEMOFF and the +// board's LPCOMP wakes it when the battery recovers +// cutoff checked while running: CUTOFF_SAMPLES readings in a row below it +// (one every CHECK_MS, so a TX dip cannot trigger it) and the node +// goes to the same SYSTEMOFF +// +// cutoff must stay below bootlock: a node switched off at the cutoff then only +// starts again once the battery is past bootlock, which is the hysteresis. +// External power (USB) disarms the cutoff, a reading under 1 V is an ADC glitch +// and is ignored. The LPCOMP wake level is hardware (a fraction of VDD), not +// one of these. +// +// Pure logic, no Arduino: driven from NodeMaintenance, tested on the host. +class LowVoltageGuard { +public: + static constexpr uint16_t MIN_MV = 3000; + static constexpr uint16_t MAX_MV = 4200; + static constexpr uint32_t CHECK_MS = 60000; + static constexpr uint8_t CUTOFF_SAMPLES = 3; + static constexpr uint16_t GLITCH_MV = 1000; + + void begin(uint32_t now, uint16_t bootlock_mv, uint16_t cutoff_mv) { + _bootlock = bootlock_mv; + _cutoff = cutoff_mv; + _last_check = now; + _low = 0; + } + + uint16_t bootlock() const { return _bootlock; } + uint16_t cutoff() const { return _cutoff; } + uint8_t lowSamples() const { return _low; } + + // NULL if the pair is acceptable, else the reason (for the CLI reply). + static const char* validate(uint16_t bootlock_mv, uint16_t cutoff_mv) { + if (bootlock_mv != 0 && (bootlock_mv < MIN_MV || bootlock_mv > MAX_MV)) return "bootlock out of range"; + if (cutoff_mv != 0 && (cutoff_mv < MIN_MV || cutoff_mv > MAX_MV)) return "cutoff out of range"; + if (cutoff_mv != 0 && bootlock_mv != 0 && cutoff_mv >= bootlock_mv) return "cutoff must be below bootlock"; + return 0; + } + + bool set(uint16_t bootlock_mv, uint16_t cutoff_mv) { + if (validate(bootlock_mv, cutoff_mv)) return false; + _bootlock = bootlock_mv; + _cutoff = cutoff_mv; + _low = 0; + return true; + } + + // True when poll() would take a reading: read the battery only then (the ADC + // read is not free on every board -- SenseCAP waits 10 ms for the divider). + bool due(uint32_t now) const { return (uint32_t)(now - _last_check) >= CHECK_MS; } + + // Returns true when the node should switch off now. + bool poll(uint32_t now, uint16_t batt_mv, bool external_power) { + if (!due(now)) return false; + _last_check = now; + if (_cutoff == 0 || external_power) { _low = 0; return false; } + if (batt_mv < GLITCH_MV) return false; // not a reading, keep the count + if (batt_mv >= _cutoff) { _low = 0; return false; } + if (_low < CUTOFF_SAMPLES) _low++; + return _low >= CUTOFF_SAMPLES; + } + +private: + uint16_t _bootlock = 0; + uint16_t _cutoff = 0; + uint32_t _last_check = 0; + uint8_t _low = 0; +}; diff --git a/src/helpers/NRF52Board.h b/src/helpers/NRF52Board.h index 43944b5f..c7644334 100644 --- a/src/helpers/NRF52Board.h +++ b/src/helpers/NRF52Board.h @@ -71,6 +71,14 @@ public: #ifdef PWRMGT_LPCOMP_AIN bool getWakeLpcompSupported() const override { return true; } #endif + // CUSTOM (TeTeHacko): entry points for runtime battery thresholds + // (PWRMGT_RUNTIME, helpers/LowVoltageGuard.h via NodeMaintenance). The boot + // check reads only voltage_bootlock; the wake is armed by initiateShutdown(). + bool bootVoltageCheck(uint16_t bootlock_mv) { + PowerMgtConfig c = { 0, 0, bootlock_mv }; + return checkBootVoltage(&c); + } + void lowVoltageShutdown() { initiateShutdown(SHUTDOWN_REASON_LOW_VOLTAGE); } #endif }; diff --git a/src/helpers/NodeMaintenance.cpp b/src/helpers/NodeMaintenance.cpp index 50682bad..b96d07b2 100644 --- a/src/helpers/NodeMaintenance.cpp +++ b/src/helpers/NodeMaintenance.cpp @@ -93,6 +93,9 @@ void NodeMaintenance::begin(FILESYSTEM* fs, NodePrefs* prefs, CommonCLICallbacks _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); @@ -106,6 +109,9 @@ void NodeMaintenance::begin(FILESYSTEM* fs, NodePrefs* prefs, CommonCLICallbacks 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(); @@ -331,6 +337,9 @@ bool NodeMaintenance::handleCommand(uint32_t sender_timestamp, const char* comma #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) { @@ -347,3 +356,118 @@ bool NodeMaintenance::handleCommand(uint32_t sender_timestamp, const char* comma } 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 diff --git a/src/helpers/NodeMaintenance.h b/src/helpers/NodeMaintenance.h index 46c00073..7a00d089 100644 --- a/src/helpers/NodeMaintenance.h +++ b/src/helpers/NodeMaintenance.h @@ -19,6 +19,11 @@ // get radio.txstall TX stall watchdog: threshold, queue, time without TX // set radio.txstall 0/off = disabled; RAM only, RADIO_TXSTALL_MIN at boot // get boot why the board last reset, and the hardfault record +// get pwr battery thresholds, battery now and at boot, last shutdown +// set pwr.bootlock don't start below it, sleep until the battery recovers +// set pwr.cutoff switch a running node off below it; 0/off = disabled +// (both only with -D PWRMGT_RUNTIME, nRF52 power management, +// see helpers/LowVoltageGuard.h) // // Wiring (see simple_sensor/main.cpp): // setup(): maint.printBootDiag() early, maint.begin(fs, prefs, cb) after the @@ -34,6 +39,11 @@ #include #endif #include +#include +#if defined(NRF52_PLATFORM) && defined(NRF52_POWER_MANAGEMENT) && defined(PWRMGT_RUNTIME) +#include +#define NODE_PWR_GUARD 1 +#endif #include class NodeMaintenance { @@ -77,6 +87,13 @@ private: void txStallTick(int tx_queued, int tx_due); bool txStallCommand(const char* command, char* reply); void dfuTick(); +#ifdef NODE_PWR_GUARD + void pwrBegin(); + void pwrTick(); + void pwrSave(); + bool pwrCommand(const char* command, char* reply); + NRF52Board& nrf() { return static_cast(_board); } +#endif mesh::MainBoard& _board; RadioLibWrapper& _radio; @@ -90,6 +107,9 @@ private: RadioSilenceWatchdog _silence; uint32_t _silence_reboots = 0; RadioSilenceWatchdog _txstall; // same staging, `activity` = packets sent +#ifdef NODE_PWR_GUARD + LowVoltageGuard _pwr; +#endif int _tx_queued = -1, _tx_due = -1; unsigned long _dfu_at = 0; // 0 = nothing armed diff --git a/test/test_low_voltage_guard/test_low_voltage_guard.cpp b/test/test_low_voltage_guard/test_low_voltage_guard.cpp new file mode 100644 index 00000000..8a05d477 --- /dev/null +++ b/test/test_low_voltage_guard/test_low_voltage_guard.cpp @@ -0,0 +1,97 @@ +#include +#include "helpers/LowVoltageGuard.h" + +using G = LowVoltageGuard; + +static const uint32_t STEP = G::CHECK_MS; + +// Polls once per CHECK_MS starting one step after `from`; returns the number of +// polls until it asks to switch off, or 0 if it never does within `polls`. +static int pollsUntilOff(G& g, uint32_t from, int polls, uint16_t mv, bool ext = false) { + for (int i = 1; i <= polls; i++) { + if (g.poll(from + i * STEP, mv, ext)) return i; + } + return 0; +} + +TEST(LowVoltageGuard, CutoffOffNeverActs) { + G g; + g.begin(0, 3300, 0); + EXPECT_EQ(pollsUntilOff(g, 0, 100, 3000), 0); +} + +TEST(LowVoltageGuard, SwitchesOffAfterConsecutiveLowSamples) { + G g; + g.begin(0, 3600, 3400); + EXPECT_EQ(pollsUntilOff(g, 0, 10, 3399), (int)G::CUTOFF_SAMPLES); +} + +TEST(LowVoltageGuard, OneGoodReadingResetsTheCount) { + G g; + g.begin(0, 3600, 3400); + uint32_t t = 0; + for (int i = 0; i < G::CUTOFF_SAMPLES - 1; i++) EXPECT_FALSE(g.poll(t += STEP, 3300, false)); + EXPECT_FALSE(g.poll(t += STEP, 3450, false)); // e.g. the TX dip is over + EXPECT_EQ(g.lowSamples(), 0); + for (int i = 0; i < G::CUTOFF_SAMPLES - 1; i++) EXPECT_FALSE(g.poll(t += STEP, 3300, false)); + EXPECT_TRUE(g.poll(t += STEP, 3300, false)); +} + +TEST(LowVoltageGuard, ChecksOnlyEveryCheckMs) { + G g; + g.begin(0, 3600, 3400); + // a burst of polls within one interval counts as nothing + for (uint32_t t = 1; t < STEP; t += 100) EXPECT_FALSE(g.poll(t, 3000, false)); + EXPECT_EQ(g.lowSamples(), 0); +} + +TEST(LowVoltageGuard, ExternalPowerDisarms) { + G g; + g.begin(0, 3600, 3400); + EXPECT_EQ(pollsUntilOff(g, 0, 20, 3000, true), 0); + EXPECT_EQ(g.lowSamples(), 0); +} + +TEST(LowVoltageGuard, AdcGlitchIsIgnoredNotCounted) { + G g; + g.begin(0, 3600, 3400); + uint32_t t = 0; + EXPECT_FALSE(g.poll(t += STEP, 3300, false)); + EXPECT_FALSE(g.poll(t += STEP, 0, false)); // glitch: neither counts nor resets + EXPECT_EQ(g.lowSamples(), 1); + EXPECT_FALSE(g.poll(t += STEP, 3300, false)); + EXPECT_TRUE(g.poll(t += STEP, 3300, false)); +} + +TEST(LowVoltageGuard, SurvivesMillisWrap) { + G g; + uint32_t start = 0xFFFFFFFFu - STEP; // wraps after the first step + g.begin(start, 3600, 3400); + EXPECT_EQ(pollsUntilOff(g, start, 10, 3300), (int)G::CUTOFF_SAMPLES); +} + +TEST(LowVoltageGuard, Validate) { + EXPECT_EQ(G::validate(0, 0), nullptr); + EXPECT_EQ(G::validate(3300, 0), nullptr); + EXPECT_EQ(G::validate(3600, 3400), nullptr); + EXPECT_EQ(G::validate(0, 3400), nullptr); // cutoff without bootlock is allowed + EXPECT_NE(G::validate(3400, 3400), nullptr); // no hysteresis + EXPECT_NE(G::validate(3400, 3600), nullptr); + EXPECT_NE(G::validate(2999, 0), nullptr); + EXPECT_NE(G::validate(0, 4201), nullptr); +} + +TEST(LowVoltageGuard, SetRejectsAndKeepsOld) { + G g; + g.begin(0, 3600, 3400); + EXPECT_FALSE(g.set(3300, 3400)); + EXPECT_EQ(g.bootlock(), 3600); + EXPECT_EQ(g.cutoff(), 3400); + EXPECT_TRUE(g.set(3700, 3500)); + EXPECT_EQ(g.cutoff(), 3500); +} + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/variants/sensecap_solar/SenseCapSolarBoard.cpp b/variants/sensecap_solar/SenseCapSolarBoard.cpp index 058c1620..7414feb0 100644 --- a/variants/sensecap_solar/SenseCapSolarBoard.cpp +++ b/variants/sensecap_solar/SenseCapSolarBoard.cpp @@ -66,7 +66,9 @@ void SenseCapSolarBoard::begin() { #endif #ifdef NRF52_POWER_MANAGEMENT +#ifndef PWRMGT_RUNTIME // CUSTOM (TeTeHacko): NodeMaintenance checks it with the saved threshold checkBootVoltage(&power_config); +#endif #endif delay(10); // give sx1262 some time to power up diff --git a/variants/sensecap_solar/platformio.ini b/variants/sensecap_solar/platformio.ini index 67a18454..d6184911 100644 --- a/variants/sensecap_solar/platformio.ini +++ b/variants/sensecap_solar/platformio.ini @@ -71,6 +71,10 @@ build_flags = ; of a brown-out boot loop on a weak panel. variant.h and ; SenseCapSolarBoard.cpp had it all wired, only this switch was missing. -D NRF52_POWER_MANAGEMENT + ; ...with the thresholds settable at runtime (`set pwr.bootlock|cutoff`), + ; saved on the node; defaults bootlock 3300 mV (variant.h), cutoff off. + ; helpers/LowVoltageGuard.h, docs/power.md. + -D PWRMGT_RUNTIME ; -D MESH_PACKET_LOGGING=1 ; -D MESH_DEBUG=1 build_src_filter = ${SenseCap_Solar.build_src_filter}