From 457e4030176fb605437923cd768a9036164298c3 Mon Sep 17 00:00:00 2001 From: mikecarper Date: Wed, 14 Oct 2026 04:11:10 -0700 Subject: [PATCH] Adapt AGC maintenance cadence during device power saving --- .github/workflows/run-unit-tests.yml | 1 + docs/cli_commands.md | 28 ++ .../test-results/radio_receive_calibration.md | 6 +- examples/companion_radio/MyMesh.h | 1 + examples/simple_repeater/MyMesh.h | 1 + examples/simple_room_server/MyMesh.h | 1 + examples/simple_sensor/SensorMesh.h | 1 + src/Dispatcher.cpp | 69 ++-- src/Dispatcher.h | 24 +- src/helpers/AGCResetScheduler.h | 95 +++++ src/helpers/radiolib/RadioLibWrappers.cpp | 16 +- src/helpers/radiolib/RadioLibWrappers.h | 3 + test/test_adaptive_agc_roles.py | 53 +++ .../test_agc_reset_scheduler.cpp | 349 +++++++++++++++++ .../test_rx_reserve_packet_manager.cpp | 361 +++++++++++++++++- test/test_radio_receive_contract.py | 153 +++++++- test/test_sensor_tracker_sleep.py | 7 +- variants/rak3x72/platformio.ini | 2 + variants/wio-e5-mini/platformio.ini | 2 + 19 files changed, 1118 insertions(+), 55 deletions(-) create mode 100644 src/helpers/AGCResetScheduler.h create mode 100644 test/test_adaptive_agc_roles.py create mode 100644 test/test_agc_reset_scheduler/test_agc_reset_scheduler.cpp diff --git a/.github/workflows/run-unit-tests.yml b/.github/workflows/run-unit-tests.yml index 9ca560029..9f305e066 100644 --- a/.github/workflows/run-unit-tests.yml +++ b/.github/workflows/run-unit-tests.yml @@ -322,6 +322,7 @@ jobs: run: | python3 -B test/test_dispatcher_startup_watchdog.py -v python3 -B test/test_radio_receive_contract.py + python3 -B test/test_adaptive_agc_roles.py -v python3 - <<'PY' from pathlib import Path import re diff --git a/docs/cli_commands.md b/docs/cli_commands.md index cba6a9006..feb0a22ee 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -2762,6 +2762,34 @@ hardware busy-result count. **Default:** `0.0` +With device `powersaving` on and a nonzero AGC interval, Companion, Repeater, +Room Server, and Sensor firmware use adaptive reset scheduling. The saved +interval is the starting/minimum interval. After every two admitted maintenance +attempts without an observed radio recovery, the interval doubles, capped at +60 seconds (or the saved interval if it is already longer). For example, +8 -> 16 -> 32 -> 60 seconds, with two attempts at each step. An observed radio +recovery returns the schedule to the saved interval. Changing the interval or +power-saving mode starts a fresh schedule; adaptive history is not persisted. + +`get agc.reset.interval` still reports the saved starting interval, not the +current adaptive interval. `0` disables periodic AGC maintenance even with +power saving on. With power saving off, fixed-interval behavior is retained. +This follows device `powersaving`, independently of LoRa `radio.rxps`. + +Adaptive scheduling does not treat a quiet mesh, strong packets, a stable +noise floor, or a successful transmission as proof of full receiver sensitivity. +TX cannot continually postpone adaptive maintenance. Pending RX/TX, a BUSY +chip outside known RX duty cycling, carrier/Morse ownership, and an active +noise-floor block can defer it; deferred attempts do not advance backoff and +are retried after 50 ms. The +60-second bound is a scheduling interval, not permission to interrupt a packet. +An armed RXPS radio uses the existing explicit wake/reset path, avoiding retry +polling that could miss every short listen window. +Existing radio recovery watchdogs remain active. These conservative intervals +have host regression coverage, but are not hardware-qualified sensitivity or +battery-life results; noisy sites may require a short fixed interval with +device power saving off. + --- #### View or change the radio watchdog interval (MQTT observer only) diff --git a/docs/test-results/radio_receive_calibration.md b/docs/test-results/radio_receive_calibration.md index f9b8139a5..12adf80c2 100644 --- a/docs/test-results/radio_receive_calibration.md +++ b/docs/test-results/radio_receive_calibration.md @@ -22,8 +22,10 @@ promptly. Dual-profile scanning retains its separate refresh policy. Frequent configured AGC resets can still dominate calibration time: Cascade -repeater builds default to an eight-second AGC interval, and MQTT observers -use 28 seconds. Those resets are not throttled by the routine cooldown. After +repeater builds start with an eight-second AGC interval, and MQTT observers +use 28 seconds. With device power saving on, their adaptive AGC schedule backs +off separately, up to 60 seconds; see [AGC reset settings](../cli_commands.md). +AGC resets still bypass the routine noise-floor cooldown. After a timed-out startup block with no valid floor, the next routine RXPS attempt also waits 60 seconds; passive retries retain their existing bounded busy escape while waiting for a valid baseline. diff --git a/examples/companion_radio/MyMesh.h b/examples/companion_radio/MyMesh.h index 0d25830e9..de18a64fe 100644 --- a/examples/companion_radio/MyMesh.h +++ b/examples/companion_radio/MyMesh.h @@ -359,6 +359,7 @@ protected: int getAGCResetInterval() const override { return ((int)_prefs.agc_reset_interval) * 4000; // milliseconds } + bool useAdaptiveAGC() const override { return _prefs.powersaving_enabled != 0; } int calcRxDelay(float score, uint32_t air_time) const override; uint32_t getRetransmitDelay(const mesh::Packet *packet) override; uint32_t getDirectRetransmitDelay(const mesh::Packet *packet) override; diff --git a/examples/simple_repeater/MyMesh.h b/examples/simple_repeater/MyMesh.h index bd4059dff..5a7c38d5e 100644 --- a/examples/simple_repeater/MyMesh.h +++ b/examples/simple_repeater/MyMesh.h @@ -1018,6 +1018,7 @@ protected: int getAGCResetInterval() const override { return ((int)_prefs.agc_reset_interval) * 4000; // milliseconds } + bool useAdaptiveAGC() const override { return _prefs.powersaving_enabled != 0; } #ifdef WITH_MQTT_BRIDGE uint32_t getRadioWatchdogMillis() const override { return ((uint32_t)_cli.getObserverPrefs()->radio_watchdog_minutes) * 60000UL; diff --git a/examples/simple_room_server/MyMesh.h b/examples/simple_room_server/MyMesh.h index 4656db539..c94af4742 100644 --- a/examples/simple_room_server/MyMesh.h +++ b/examples/simple_room_server/MyMesh.h @@ -430,6 +430,7 @@ protected: int getAGCResetInterval() const override { return ((int)_prefs.agc_reset_interval) * 4000; // milliseconds } + bool useAdaptiveAGC() const override { return _prefs.powersaving_enabled != 0; } uint8_t getExtraAckTransmitCount() const override { return _prefs.multi_acks; } diff --git a/examples/simple_sensor/SensorMesh.h b/examples/simple_sensor/SensorMesh.h index 0ed10b253..a73c4012e 100644 --- a/examples/simple_sensor/SensorMesh.h +++ b/examples/simple_sensor/SensorMesh.h @@ -207,6 +207,7 @@ protected: int getInterferenceThreshold() const override; bool getCADEnabled() const override; int getAGCResetInterval() const override; + bool useAdaptiveAGC() const override { return _prefs.powersaving_enabled != 0; } uint8_t getDefaultTxCodingRate() const override { return active_cr; } diff --git a/src/Dispatcher.cpp b/src/Dispatcher.cpp index f4d55f1f5..a3d0d2b6e 100644 --- a/src/Dispatcher.cpp +++ b/src/Dispatcher.cpp @@ -60,8 +60,7 @@ void Dispatcher::setRadioAvailable(bool available) { const unsigned long now = _ms->getMillis(); radio_nonrx_start = now; next_floor_calib_time = now; - armed_agc_reset_interval = 0; - agc_reset_armed = false; + agc_reset.reset(); _radio->begin(); prev_isrecv_mode = _radio->isInRecvMode(); #ifdef RADIO_LIVENESS_SOFT_ONLY @@ -99,8 +98,7 @@ void Dispatcher::begin() { last_budget_update = _ms->getMillis(); const unsigned long now = _ms->getMillis(); - armed_agc_reset_interval = 0; - agc_reset_armed = false; + agc_reset.reset(); dispatcher_started = true; if (radio_available) { _radio->begin(); @@ -467,6 +465,17 @@ bool Dispatcher::getNextQueueWakeDelay(uint32_t& delay_millis) const { const uint32_t now = _ms->getMillis(); bool found = false; uint32_t shortest_delay = 0; + // Timed MCU sleep must not skip the adaptive maintenance/retry deadline. + // Preserve the legacy queue-only query when power saving is off. + if (radio_available && useAdaptiveAGC()) { + found = agc_reset.nextDelay(now, shortest_delay); + if (found && !agc_reset.recoveryMatches(_radio->getRecoveryCount())) { + // A Dispatcher-owned recovery can occur after configure() this loop. + // Poll once before sleeping so the base cadence is restored promptly. + delay_millis = 0; + return true; + } + } if (outbound != NULL) { if (outbound_radio_retry_pending) { @@ -481,7 +490,8 @@ bool Dispatcher::getNextQueueWakeDelay(uint32_t& delay_millis) const { if (outbound_restore_cr) { const int32_t restore_delay = (int32_t)(outbound_restore_retry_at - now); - shortest_delay = restore_delay > 0 ? (uint32_t)restore_delay : 0; + const uint32_t delay = restore_delay > 0 ? (uint32_t)restore_delay : 0; + if (!found || delay < shortest_delay) shortest_delay = delay; found = true; } @@ -541,6 +551,10 @@ void Dispatcher::loop() { #endif const unsigned long now = _ms->getMillis(); + const int agc_interval = getAGCResetInterval(); + const bool adaptive = useAdaptiveAGC(); + agc_reset.configure(now, agc_interval > 0 ? agc_interval : 0, + adaptive, adaptive ? _radio->getRecoveryCount() : 0); if (!radio_nonrx_timer_armed) { // Application setup can outlast the watchdog after begin() leaves the // radio in standby. Start observing when loop service actually begins, @@ -711,35 +725,26 @@ void Dispatcher::loop() { } // going back into receive mode now... - const int agc_interval = getAGCResetInterval(); - if (agc_interval > 0) { - next_agc_reset_time = futureMillis(agc_interval); - armed_agc_reset_interval = agc_interval; - agc_reset_armed = true; - } else { - armed_agc_reset_interval = 0; - agc_reset_armed = false; - } + agc_reset.noteTransmit(_ms->getMillis()); } - const int agc_interval = getAGCResetInterval(); - if (agc_interval <= 0) { - armed_agc_reset_interval = 0; - agc_reset_armed = false; - } else if (!agc_reset_armed - || agc_interval != armed_agc_reset_interval) { - // MyMesh loads persisted preferences after Dispatcher::begin(). Arm from - // the first loop so the real configured interval is used, and so a freshly - // initialized radio/frontend gets one full settle interval before the - // first warm-sleep AGC reset. A live interval change also gets a complete - // new interval instead of inheriting the old setting's deadline. - next_agc_reset_time = futureMillis(agc_interval); - armed_agc_reset_interval = agc_interval; - agc_reset_armed = true; - } else if (millisHasNowPassed(next_agc_reset_time)) { - _radio->resetAGC(); - next_agc_reset_time = futureMillis(agc_interval); - armed_agc_reset_interval = agc_interval; + const uint32_t agc_now = _ms->getMillis(); + if ((!adaptive || !recovered_this_loop) && agc_interval > 0 + && (adaptive ? agc_reset.due(agc_now) + : millisHasNowPassed(agc_reset.nextAt()))) { + bool attempted; + if (!adaptive) { + _radio->resetAGC(); + attempted = true; + } else { + attempted = !_radio->isCalibratingNoiseFloor() && _radio->tryResetAGC(); + } + if (attempted) { + agc_reset.noteAttempt(_ms->getMillis()); + } else { + // Ownership/calibration deferral is not a reset or health evidence. + agc_reset.noteDeferred(_ms->getMillis()); + } } // check inbound (delayed) queue diff --git a/src/Dispatcher.h b/src/Dispatcher.h index 7dceb14cb..4d6b54543 100644 --- a/src/Dispatcher.h +++ b/src/Dispatcher.h @@ -8,6 +8,7 @@ #include #include #include +#include #ifndef RADIO_LIVENESS_SOFT_ONLY #include #endif @@ -216,6 +217,10 @@ public: uint32_t getCADScanTimeoutMillis() const { return 0; } virtual void resetAGC() { } + // True means the maintenance sequence was admitted, not that receiver + // sensitivity has been measured. Busy implementations may defer it. + virtual bool tryResetAGC() { resetAGC(); return true; } + virtual uint32_t getRecoveryCount() const { return 0; } virtual uint8_t getRadioState() const { return 0; } virtual unsigned long getLastRecvMillis() const { return 0; } @@ -363,9 +368,7 @@ class Dispatcher { uint32_t ota_tx_airtime = 0; unsigned long cad_busy_start; unsigned long radio_nonrx_start; - unsigned long next_floor_calib_time, next_agc_reset_time; - int armed_agc_reset_interval; - bool agc_reset_armed; + unsigned long next_floor_calib_time; bool radio_nonrx_timer_armed; bool prev_isrecv_mode; bool radio_available; @@ -382,10 +385,6 @@ class Dispatcher { unsigned long tx_budget_ms; unsigned long last_budget_update; unsigned long duty_cycle_window_ms; - uint8_t receive_context_profile = 0; - uint32_t receive_context_generation = 0; - bool receive_context_active = false; - uint32_t profile_cad_busy[2] = {}; #if MESH_ENABLE_MESHTEXT_CHAT // One bounded user-send slot; never placed in the MeshCore packet pool. uint8_t foreign_radio_bytes[MAX_TRANS_UNIT] = {}; @@ -454,9 +453,7 @@ protected: last_meshcore_recv_millis = 0; next_tx_time = ms.getMillis(); cad_busy_start = 0; - next_floor_calib_time = next_agc_reset_time = 0; - armed_agc_reset_interval = 0; - agc_reset_armed = false; + next_floor_calib_time = 0; _err_flags = 0; radio_nonrx_start = 0; radio_nonrx_timer_armed = false; @@ -522,6 +519,7 @@ protected: virtual int getInterferenceThreshold() const { return 0; } // disabled by default virtual bool getCADEnabled() const { return false; } // hardware CAD disabled by default virtual int getAGCResetInterval() const { return 0; } // disabled by default + virtual bool useAdaptiveAGC() const { return false; } virtual unsigned long getDutyCycleWindowMs() const { return 3600000; } #ifdef WITH_MQTT_BRIDGE virtual uint32_t getRadioWatchdogMillis() const; // observer-only radio recovery @@ -591,6 +589,12 @@ public: unsigned long futureMillis(int millis_from_now) const; private: + // Keep the frequently accessed core fields at compact ARM load offsets. + AGCResetScheduler agc_reset; + uint32_t receive_context_generation = 0; + uint32_t profile_cad_busy[2] = {}; + uint8_t receive_context_profile = 0; + bool receive_context_active = false; #if MESH_PACKET_LOGGING void logPacketLine(const char* direction, const Packet* packet, int len, bool include_rx_metrics, float score, diff --git a/src/helpers/AGCResetScheduler.h b/src/helpers/AGCResetScheduler.h new file mode 100644 index 000000000..b297849aa --- /dev/null +++ b/src/helpers/AGCResetScheduler.h @@ -0,0 +1,95 @@ +#pragma once + +#include + +namespace mesh { + +// Bounded reset cadence, not an AGC-health detector. Only an accepted reset +// sequence advances the adaptive stage; quiet traffic is not proof of failure. +class AGCResetScheduler { + static constexpr uint32_t ADAPTIVE = 0x80000000UL; + static constexpr uint32_t BASE_MASK = 0xfffffUL; + static constexpr uint32_t STAGE = 0x100000UL; + static constexpr uint32_t STREAK = 0x2000000UL; + uint32_t _next = 0; + uint32_t _recovery_count = 0; + // Fixed mode stores the complete positive signed-millis interval. Adaptive + // preferences use at most 255 * 4000 ms, leaving room for a five-bit stage + // and one-bit attempt streak. This is RAM state, never a persisted format. + uint32_t _state = 0; + +public: + void reset() { + _next = _recovery_count = _state = 0; + } + + void configure(uint32_t now, uint32_t base_ms, bool adaptive, + uint32_t recovery_count) { + // All supported preference intervals fit in the signed millis half-range. + // Invalid external input must not turn into an immediately due reset loop. + if (base_ms == 0 || base_ms > INT32_MAX) { + reset(); + return; + } + // Larger external intervals retain their exact fixed cadence. Every + // supported preference fits the adaptive representation without rounding. + const uint32_t config = base_ms + | (adaptive && base_ms <= 1020000UL ? ADAPTIVE : 0); + const uint32_t previous = _state & ADAPTIVE + ? _state & (ADAPTIVE | BASE_MASK) : _state; + if (previous != config || _recovery_count != recovery_count) { + _state = config; + _next = now + base_ms; + _recovery_count = recovery_count; + } + } + + void noteTransmit(uint32_t now) { + if (_state && !(_state & ADAPTIVE)) _next = now + _state; + } + + bool due(uint32_t now) const { + return _state != 0 && static_cast(now - _next) >= 0; + } + + // A busy operation changes only its retry deadline, never the reset cadence + // or adaptive stage. This permits sleep instead of spinning on a due reset. + void noteDeferred(uint32_t now) { + if (_state) _next = now + 50; + } + + // Call only after an actual accepted reset sequence, not a busy/deferred one. + void noteAttempt(uint32_t now) { + if (!_state) return; + uint32_t value = interval(); + if (_state & ADAPTIVE) { + _state ^= STREAK; + if (!(_state & STREAK) && value < 60000UL) { + // Advance only below the ceiling: stage <= 16 even for a 1 ms base, + // and the shifted interval remains below 120000 before clamping. + _state += STAGE; + value *= 2; + if (value > 60000UL) value = 60000UL; + } + } + // Anchor one interval to this accepted attempt, never replay missed slots. + _next = now + value; + } + + uint32_t interval() const { + if (!(_state & ADAPTIVE)) return _state; + const uint32_t base = _state & BASE_MASK; + const uint32_t value = base << ((_state >> 20) & 31); + return base < 60000UL && value > 60000UL ? 60000UL : value; + } + uint32_t nextAt() const { return _next; } + bool recoveryMatches(uint32_t count) const { return _recovery_count == count; } + + bool nextDelay(uint32_t now, uint32_t& delay_ms) const { + if (!_state) return false; + delay_ms = due(now) ? 0 : _next - now; + return true; + } +}; + +} // namespace mesh diff --git a/src/helpers/radiolib/RadioLibWrappers.cpp b/src/helpers/radiolib/RadioLibWrappers.cpp index 0670f73e0..0af37d658 100644 --- a/src/helpers/radiolib/RadioLibWrappers.cpp +++ b/src/helpers/radiolib/RadioLibWrappers.cpp @@ -814,9 +814,20 @@ void RadioLibWrapper::doResetAGC() { } void RadioLibWrapper::resetAGC() { - if (_cw_active) return; + resetAGCIfIdle(); +} + +bool RadioLibWrapper::tryResetAGC() { + // BUSY is expected during RXPS sleep. Reuse the legacy explicit wake/reset + // sequence there; polling only every 50 ms can miss every short RX window. + // Outside known duty cycling, a busy SPI command still defers admission. + return (_rx_ps_armed || !isChipBusy()) && resetAGCIfIdle(); +} + +bool RadioLibWrapper::resetAGCIfIdle() { + if (_cw_active) return false; // make sure we're not mid-receiving and mid-sending of packet! - if (isPacketPendingOrReceiving() || (state == STATE_TX_WAIT)) return; + if (isPacketPendingOrReceiving() || (state == STATE_TX_WAIT)) return false; doResetAGC(); state = STATE_IDLE; // trigger a startReceive() @@ -830,6 +841,7 @@ void RadioLibWrapper::resetAGC() { recalibrateNoiseFloor(); _noise_floor_valid = previous_valid; _noise_floor_secondary_valid = previous_secondary_valid; + return true; } bool RadioLibWrapper::recoverRadio(bool hard) { diff --git a/src/helpers/radiolib/RadioLibWrappers.h b/src/helpers/radiolib/RadioLibWrappers.h index 24b7d9480..f7186384d 100644 --- a/src/helpers/radiolib/RadioLibWrappers.h +++ b/src/helpers/radiolib/RadioLibWrappers.h @@ -203,6 +203,7 @@ protected: void rxPsWatchdogCheck(); void requestPeriodicNoiseFloorRefresh(); void requestNoiseFloorRefresh(); + bool resetAGCIfIdle(); void requestRestartRecv(); bool isPacketPendingOrReceiving(); void noiseFloorCalibCheck(unsigned long now); @@ -463,6 +464,8 @@ public: return cadScanTimeoutMillis(); } void resetAGC() override; + bool tryResetAGC() override; + uint32_t getRecoveryCount() const override { return n_wd_soft + n_wd_hard; } void loop() override; bool setTrackerSleep(bool sleeping) override; diff --git a/test/test_adaptive_agc_roles.py b/test/test_adaptive_agc_roles.py new file mode 100644 index 000000000..6906eae36 --- /dev/null +++ b/test/test_adaptive_agc_roles.py @@ -0,0 +1,53 @@ +"""Execute each role's production device-power-saving AGC gate.""" +from pathlib import Path +import os +import subprocess +import tempfile +import unittest + +from test_radio_receive_contract import method + +ROOT = Path(__file__).resolve().parents[1] + + +class AdaptiveAGCRoleTests(unittest.TestCase): + def test_device_power_saving_not_rxps_controls_each_role(self): + for role, header in ( + ("companion", "examples/companion_radio/MyMesh.h"), + ("repeater", "examples/simple_repeater/MyMesh.h"), + ("room", "examples/simple_room_server/MyMesh.h"), + ("sensor", "examples/simple_sensor/SensorMesh.h"), + ): + with self.subTest(role=role), tempfile.TemporaryDirectory(prefix="meshcore-agc-role-") as tmp: + gate = method((ROOT / header).read_text(), "bool useAdaptiveAGC() const") + source = r''' +#include +#include +#include +struct Base { virtual bool useAdaptiveAGC() const { return false; } }; +struct Role : Base { + struct { uint8_t powersaving_enabled = 0, rx_powersaving_enabled = 0; } _prefs; + @GATE@ +}; +int main() { + Role role; + for (uint8_t power : {0, 1, 255}) for (uint8_t rxps : {0, 1}) { + role._prefs.powersaving_enabled = power; + role._prefs.rx_powersaving_enabled = rxps; + assert(role.useAdaptiveAGC() == (power != 0)); + } +} +''' + cpp, binary = Path(tmp) / "test.cpp", Path(tmp) / "test" + cpp.write_text(source.replace("@GATE@", gate), encoding="ascii") + result = subprocess.run([ + os.environ.get("CXX", "c++"), "-std=c++17", "-Wall", "-Wextra", "-Werror", + str(cpp), "-o", str(binary), + ], capture_output=True, text=True, timeout=60) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + result = subprocess.run([str(binary)], capture_output=True, text=True, timeout=10) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/test_agc_reset_scheduler/test_agc_reset_scheduler.cpp b/test/test_agc_reset_scheduler/test_agc_reset_scheduler.cpp new file mode 100644 index 000000000..18a104c8d --- /dev/null +++ b/test/test_agc_reset_scheduler/test_agc_reset_scheduler.cpp @@ -0,0 +1,349 @@ +#include + +#include +#include + +using mesh::AGCResetScheduler; + +static_assert(sizeof(AGCResetScheduler) <= 12, + "AGC scheduler must preserve the constrained Dispatcher layout"); + +namespace { + +// Independent unpacked cadence model. No bit masks or shift-based interval +// reconstruction from the production representation are used here. +struct ReferenceScheduler { + uint32_t base = 0, cadence = 0, deadline = 0, recovery = 0; + unsigned attempts = 0; + bool adaptive = false; + + void configure(uint32_t now, uint32_t requested, bool mode, uint32_t count) { + if (!requested || requested > INT32_MAX) { + *this = ReferenceScheduler(); + return; + } + if (base != requested || adaptive != mode || recovery != count) { + base = cadence = requested; + adaptive = mode; + recovery = count; + deadline = now + base; + attempts = 0; + } + } + void transmit(uint32_t now) { + if (base && !adaptive) deadline = now + base; + } + void deferred(uint32_t now) { if (base) deadline = now + 50; } + void attempted(uint32_t now) { + if (!base) return; + if (adaptive && ++attempts == 2) { + attempts = 0; + if (cadence < 60000) { + cadence *= 2; + if (cadence > 60000) cadence = 60000; + } + } + deadline = now + cadence; + } + bool due(uint32_t now) const { + return base && int32_t(now - deadline) >= 0; + } +}; + +void expectEquivalent(const AGCResetScheduler& actual, + const ReferenceScheduler& expected, uint32_t now) { + ASSERT_EQ(actual.interval(), expected.cadence); + ASSERT_EQ(actual.nextAt(), expected.deadline); + ASSERT_EQ(actual.due(now), expected.due(now)); + uint32_t delay = 123; + ASSERT_EQ(actual.nextDelay(now, delay), expected.base != 0); + ASSERT_EQ(delay, expected.base + ? (expected.due(now) ? 0 : expected.deadline - now) : 123); +} + +uint32_t nextRandom(uint32_t& value) { + value ^= value << 13; + value ^= value >> 17; + return value ^= value << 5; +} + +} // namespace + +TEST(AGCResetScheduler, DisabledAndInvalidIntervalsNeverSchedule) { + AGCResetScheduler scheduler; + uint32_t delay = 123; + EXPECT_FALSE(scheduler.due(0)); + EXPECT_FALSE(scheduler.nextDelay(100, delay)); + EXPECT_EQ(delay, 123u); + scheduler.noteTransmit(100); + scheduler.noteAttempt(100); + scheduler.noteDeferred(100); + EXPECT_EQ(scheduler.interval(), 0u); + for (uint32_t base : {0u, 0x80000000u, UINT32_MAX}) { + scheduler.configure(1, 8000, true, 0); + scheduler.configure(2, base, true, 0); + EXPECT_FALSE(scheduler.due(500000)); + EXPECT_FALSE(scheduler.nextDelay(500000, delay)); + EXPECT_EQ(scheduler.nextAt(), 0u); + } +} + +TEST(AGCResetScheduler, IdenticalConfigurationDoesNotMoveDeadlineOrStage) { + AGCResetScheduler scheduler; + scheduler.configure(100, 8000, true, 7); + for (uint32_t now = 100; now <= 8100; now += 100) { + scheduler.configure(now, 8000, true, 7); + EXPECT_EQ(scheduler.nextAt(), 8100u); + EXPECT_EQ(scheduler.due(now), now == 8100); + } + scheduler.noteAttempt(8100); + scheduler.configure(16099, 8000, true, 7); + EXPECT_EQ(scheduler.nextAt(), 16100u); + scheduler.noteAttempt(16100); + EXPECT_EQ(scheduler.interval(), 16000u); +} + +TEST(AGCResetScheduler, QuietAcceptedAttemptsBackOffEveryTwoWithoutHealthClaims) { + AGCResetScheduler scheduler; + scheduler.configure(0, 8000, true, 0); + uint32_t now = 0; + for (uint32_t interval : {8000u, 16000u, 16000u, 32000u, + 32000u, 60000u, 60000u, 60000u}) { + now = scheduler.nextAt(); + EXPECT_TRUE(scheduler.due(now)); + scheduler.noteAttempt(now); + EXPECT_EQ(scheduler.interval(), interval); + EXPECT_EQ(scheduler.nextAt(), now + interval); + EXPECT_FALSE(scheduler.due(now)); + } +} + +TEST(AGCResetScheduler, BaseAboveAdaptiveCeilingIsNeverShortened) { + for (uint32_t base : {60000u, 61000u, 300000u, 1020000u, + uint32_t(INT32_MAX)}) { + AGCResetScheduler scheduler; + scheduler.configure(100, base, true, 0); + for (unsigned attempt = 0; attempt < 20; ++attempt) { + const uint32_t now = scheduler.nextAt(); + EXPECT_TRUE(scheduler.due(now)); + scheduler.noteAttempt(now); + EXPECT_EQ(scheduler.interval(), base); + } + } +} + +TEST(AGCResetScheduler, FixedTransmitPostponesButAdaptiveTransmitDoesNot) { + for (bool adaptive : {false, true}) { + AGCResetScheduler scheduler; + scheduler.configure(100, 8000, adaptive, 0); + scheduler.noteTransmit(8000); + EXPECT_EQ(scheduler.nextAt(), adaptive ? 8100u : 16000u); + EXPECT_EQ(scheduler.due(8100), adaptive); + scheduler.noteAttempt(scheduler.nextAt()); + scheduler.noteAttempt(scheduler.nextAt()); + EXPECT_EQ(scheduler.interval(), adaptive ? 16000u : 8000u); + } +} + +TEST(AGCResetScheduler, BaseModeAndRecoveryChangesStartFreshIntervals) { + AGCResetScheduler scheduler; + scheduler.configure(0, 8000, true, 6); + scheduler.noteAttempt(8000); + scheduler.noteAttempt(16000); + ASSERT_EQ(scheduler.interval(), 16000u); + scheduler.configure(17000, 8000, true, 7); + EXPECT_EQ(scheduler.interval(), 8000u); + EXPECT_EQ(scheduler.nextAt(), 25000u); + scheduler.noteAttempt(25000); + EXPECT_EQ(scheduler.interval(), 8000u); + scheduler.configure(26000, 16000, true, 7); + EXPECT_EQ(scheduler.nextAt(), 42000u); + scheduler.noteAttempt(42000); + EXPECT_EQ(scheduler.interval(), 16000u); + scheduler.configure(43000, 16000, false, 7); + EXPECT_EQ(scheduler.nextAt(), 59000u); + scheduler.configure(44000, 16000, true, 7); + EXPECT_EQ(scheduler.nextAt(), 60000u); + scheduler.configure(45000, 16000, true, UINT32_MAX); + scheduler.configure(46000, 16000, true, 0); + EXPECT_EQ(scheduler.nextAt(), 62000u); +} + +TEST(AGCResetScheduler, DeferredAttemptsStayDueAndDoNotAdvanceStage) { + AGCResetScheduler scheduler; + scheduler.configure(0, 8000, true, 1); + uint32_t delay = 0; + ASSERT_TRUE(scheduler.nextDelay(7999, delay)); + EXPECT_EQ(delay, 1u); + for (uint32_t now : {8000u, 8050u, 9000u, 100000u}) { + scheduler.configure(now, 8000, true, 1); + EXPECT_TRUE(scheduler.due(now)); + EXPECT_EQ(scheduler.nextAt(), 8000u); + ASSERT_TRUE(scheduler.nextDelay(now, delay)); + EXPECT_EQ(delay, 0u); + } + scheduler.noteAttempt(100000); + EXPECT_EQ(scheduler.interval(), 8000u); + EXPECT_EQ(scheduler.nextAt(), 108000u); + EXPECT_FALSE(scheduler.due(100000)); +} + +TEST(AGCResetScheduler, DeferredRetriesWaitFiftyMillisWithoutPromotingStage) { + AGCResetScheduler scheduler; + scheduler.configure(0, 8000, true, 1); + scheduler.noteAttempt(8000); + ASSERT_EQ(scheduler.nextAt(), 16000u); + for (uint32_t now = 16000; now < 16500; now += 50) { + ASSERT_TRUE(scheduler.due(now)); + scheduler.noteDeferred(now); + EXPECT_EQ(scheduler.interval(), 8000u); + EXPECT_FALSE(scheduler.due(now + 49)); + EXPECT_TRUE(scheduler.due(now + 50)); + uint32_t delay = 0; + ASSERT_TRUE(scheduler.nextDelay(now + 49, delay)); + EXPECT_EQ(delay, 1u); + scheduler.configure(now + 49, 8000, true, 1); + EXPECT_EQ(scheduler.nextAt(), now + 50); + } + scheduler.noteAttempt(16500); + EXPECT_EQ(scheduler.interval(), 16000u); + EXPECT_EQ(scheduler.nextAt(), 32500u); + + scheduler.configure(UINT32_MAX - 10u, 32, false, 0); + scheduler.noteDeferred(UINT32_MAX - 10u); + EXPECT_EQ(scheduler.nextAt(), 39u); + EXPECT_FALSE(scheduler.due(38)); + EXPECT_TRUE(scheduler.due(39)); +} + +TEST(AGCResetScheduler, LateServiceDoesNotReplayMissedResetSlots) { + AGCResetScheduler scheduler; + scheduler.configure(10, 8000, true, 0); + const uint32_t late = 7u * 24u * 60u * 60u * 1000u; + ASSERT_TRUE(scheduler.due(late)); + scheduler.noteAttempt(late); + EXPECT_EQ(scheduler.interval(), 8000u); + EXPECT_EQ(scheduler.nextAt(), late + 8000u); + EXPECT_FALSE(scheduler.due(late)); + scheduler.noteAttempt(late + 8000u); + EXPECT_EQ(scheduler.interval(), 16000u); +} + +TEST(AGCResetScheduler, DeadlinesAndDelaySurviveMillisRolloverIncludingZero) { + AGCResetScheduler scheduler; + scheduler.configure(0xfffffff0u, 32, true, 0); + EXPECT_EQ(scheduler.nextAt(), 16u); + uint32_t delay = 0; + ASSERT_TRUE(scheduler.nextDelay(0xfffffff0u, delay)); + EXPECT_EQ(delay, 32u); + EXPECT_FALSE(scheduler.due(15)); + EXPECT_TRUE(scheduler.due(16)); + scheduler.noteAttempt(16); + EXPECT_EQ(scheduler.nextAt(), 48u); + scheduler.configure(UINT32_MAX - 31u, 32, false, 0); + EXPECT_EQ(scheduler.nextAt(), 0u); + EXPECT_FALSE(scheduler.due(UINT32_MAX)); + EXPECT_TRUE(scheduler.due(0)); + ASSERT_TRUE(scheduler.nextDelay(UINT32_MAX, delay)); + EXPECT_EQ(delay, 1u); + scheduler.reset(); + EXPECT_FALSE(scheduler.due(0)); + EXPECT_FALSE(scheduler.nextDelay(0, delay)); + scheduler.configure(100, 32, false, 0); + EXPECT_EQ(scheduler.nextAt(), 132u); +} + +TEST(AGCResetScheduler, AdaptiveRepresentationDoesNotBleedStageOrStreakBits) { + for (uint32_t base : {1u, 2u, 3u, 31u, 32u, 32767u, 32768u, + 59999u, 60000u, 60001u, 1020000u}) { + AGCResetScheduler actual; + ReferenceScheduler expected; + actual.configure(UINT32_MAX - 123u, base, true, 42); + expected.configure(UINT32_MAX - 123u, base, true, 42); + for (unsigned attempt = 0; attempt < 80; ++attempt) { + const uint32_t now = actual.nextAt(); + actual.noteAttempt(now); + expected.attempted(now); + expectEquivalent(actual, expected, now); + // This implementation-only assertion checks the compact non-persisted + // word: no stage overflow into streak/unused bits, no base corruption. + uint32_t words[3]; + std::memcpy(words, &actual, sizeof(actual)); + EXPECT_EQ(words[2] & 0x7c000000u, 0u); + EXPECT_EQ(words[2] & 0xfffffu, base); + EXPECT_LE((words[2] >> 20) & 31u, 16u); + EXPECT_NE(words[2] & 0x80000000u, 0u); + } + } +} + +TEST(AGCResetScheduler, LargerExternalIntervalsRetainExactFixedCadence) { + for (uint32_t base : {1020001u, 0x100000u, 0x2000000u, 0x4000000u, + uint32_t(INT32_MAX)}) { + for (bool request_adaptive : {false, true}) { + AGCResetScheduler actual; + ReferenceScheduler expected; + actual.configure(UINT32_MAX - 44u, base, request_adaptive, 7); + expected.configure(UINT32_MAX - 44u, base, false, 7); + for (uint32_t now : {1u, 100u, UINT32_MAX - 1u}) { + actual.noteTransmit(now); + expected.transmit(now); + expectEquivalent(actual, expected, now); + actual.noteAttempt(now); + expected.attempted(now); + expectEquivalent(actual, expected, now); + actual.configure(now, base, request_adaptive, 7); + expectEquivalent(actual, expected, now); + } + } + } +} + +TEST(AGCResetScheduler, DeterministicDifferentialAcrossSupportedBoundaries) { + uint32_t random = 0x69ab1234; + const uint32_t boundaries[] = {1, 2, 3, 31, 32, 1000, 3999, 4000, 8000, + 28000, 32767, 32768, 59999, 60000, 60001, 65535, 65536, 1019999, 1020000}; + for (unsigned script = 0; script < 80; ++script) { + uint32_t base = script < sizeof(boundaries) / sizeof(boundaries[0]) + ? boundaries[script] : nextRandom(random) % 1020000 + 1; + bool adaptive = script % 2; + uint32_t recovery = UINT32_MAX; + uint32_t now = UINT32_MAX - 333; + AGCResetScheduler actual; + ReferenceScheduler expected; + actual.configure(now, base, adaptive, recovery); + expected.configure(now, base, adaptive, recovery); + for (unsigned operation = 0; operation < 200; ++operation) { + now += nextRandom(random) % 5000; + switch (nextRandom(random) % 7) { + case 0: + ++recovery; + actual.configure(now, base, adaptive, recovery); + expected.configure(now, base, adaptive, recovery); + break; + case 1: actual.noteTransmit(now); expected.transmit(now); break; + case 2: actual.noteDeferred(now); expected.deferred(now); break; + case 3: actual.noteAttempt(now); expected.attempted(now); break; + case 4: + now = actual.nextAt(); + actual.noteAttempt(now); expected.attempted(now); + break; + case 5: + adaptive = !adaptive; + actual.configure(now, base, adaptive, recovery); + expected.configure(now, base, adaptive, recovery); + break; + case 6: + actual.configure(now, base, adaptive, recovery); + expected.configure(now, base, adaptive, recovery); + break; + } + expectEquivalent(actual, expected, now); + } + } +} + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/test/test_packet_manager/test_rx_reserve_packet_manager.cpp b/test/test_packet_manager/test_rx_reserve_packet_manager.cpp index 0f293dd4a..6e11a404c 100644 --- a/test/test_packet_manager/test_rx_reserve_packet_manager.cpp +++ b/test/test_packet_manager/test_rx_reserve_packet_manager.cpp @@ -14,12 +14,18 @@ public: uint8_t pending_rx[MAX_TRANS_UNIT]; int pending_rx_len = 0; int send_starts = 0; + uint32_t airtime_ms = 1; bool receiving = false; bool in_recv_mode = true; int soft_recoveries = 0; int hard_recoveries = 0; int cad_set_calls = 0; int agc_resets = 0; + int agc_attempts = 0; + bool agc_admitted = true; + bool noise_floor_active = false; + mutable unsigned noise_floor_reads = 0; + uint32_t recovery_count = 0; bool cad_enabled = false; unsigned long last_irq = 0; bool recovery_result = true; @@ -37,7 +43,7 @@ public: pending_rx_len = 0; return len; } - uint32_t getEstAirtimeFor(int) override { return 1; } + uint32_t getEstAirtimeFor(int) override { return airtime_ms; } float packetScore(float, int) override { return 0; } bool startSendRaw(const uint8_t* bytes, int len) override { if (send_starts < 3) { @@ -56,6 +62,15 @@ public: cad_enabled = enable; } void resetAGC() override { agc_resets++; } + bool tryResetAGC() override { + agc_attempts++; + if (!agc_admitted) return false; + resetAGC(); + return true; + } + bool isCalibratingNoiseFloor() const override { return noise_floor_active; } + int getNoiseFloor() const override { noise_floor_reads++; return -120; } + uint32_t getRecoveryCount() const override { return recovery_count; } unsigned long getLastRadioInterruptMillis() const override { return last_irq; } bool recoverRadio(bool hard) override { if (hard) { @@ -121,12 +136,14 @@ public: bool bypass_rx_delay = false; bool configured_cad_enabled = false; int configured_agc_interval = 0; + bool adaptive_agc = false; float ota_speed = 1.0f; float getOtaSpeedFactor() const override { return ota_speed; } int getAGCResetInterval() const override { return configured_agc_interval; } + bool useAdaptiveAGC() const override { return adaptive_agc; } TestDispatcher(TestRadio& radio, TestClock& clock, RxReservePacketManager& mgr) : mesh::Dispatcher(radio, clock, mgr), manager(mgr) { } @@ -689,6 +706,292 @@ TEST(Dispatcher, AgcResetDeadlineSurvivesMillisRollover) { EXPECT_EQ(1, radio.agc_resets); } +static uint32_t nextAgcWake(TestDispatcher& dispatcher) { + uint32_t delay = UINT32_MAX; + EXPECT_TRUE(dispatcher.nextQueueWakeDelay(delay)); + return delay; +} + +static void dispatchNextAgc(TestDispatcher& dispatcher, TestClock& clock) { + clock.now = uint32_t(clock.now) + nextAgcWake(dispatcher) + 1; + dispatcher.loop(); +} + +TEST(Dispatcher, AdaptiveAgcDoublesAfterTwoAdmittedAttemptsAndCapsAtOneMinute) { + RxReservePacketManager manager(4, 1); + TestClock clock; + TestRadio radio; + TestDispatcher dispatcher(radio, clock, manager); + dispatcher.configured_agc_interval = 8000; + dispatcher.adaptive_agc = true; + dispatcher.begin(); + dispatcher.loop(); + EXPECT_EQ(8000U, nextAgcWake(dispatcher)); + const uint32_t expected[] = {8000, 16000, 16000, 32000, 32000, 60000, 60000, 60000}; + for (unsigned attempt = 0; attempt < sizeof(expected) / sizeof(expected[0]); ++attempt) { + SCOPED_TRACE(attempt); + dispatchNextAgc(dispatcher, clock); + EXPECT_EQ(int(attempt + 1), radio.agc_resets); + EXPECT_EQ(expected[attempt], nextAgcWake(dispatcher)); + } + EXPECT_EQ(radio.agc_resets, radio.agc_attempts); + EXPECT_EQ(0U, radio.noise_floor_reads); // No new RSSI/floor probes to justify backoff. + EXPECT_EQ(0, radio.soft_recoveries); + EXPECT_EQ(0, radio.hard_recoveries); +} + +TEST(Dispatcher, AdaptiveAgcKeepsZeroOffAndDoesNotShortenLongManualBase) { + RxReservePacketManager manager(4, 1); + TestClock clock; + TestRadio radio; + TestDispatcher dispatcher(radio, clock, manager); + dispatcher.adaptive_agc = true; + dispatcher.begin(); + dispatcher.loop(); + uint32_t delay = 77; + EXPECT_FALSE(dispatcher.nextQueueWakeDelay(delay)); + clock.now = 900000; + dispatcher.loop(); + EXPECT_EQ(0, radio.agc_attempts); + dispatcher.configured_agc_interval = 120000; + dispatcher.loop(); + for (unsigned attempt = 0; attempt < 4; ++attempt) { + EXPECT_EQ(120000U, nextAgcWake(dispatcher)); + dispatchNextAgc(dispatcher, clock); + } + EXPECT_EQ(4, radio.agc_resets); + EXPECT_EQ(120000U, nextAgcWake(dispatcher)); +} + +TEST(Dispatcher, AdaptiveAgcModeIntervalAndDisableChangesStartFreshFullIntervals) { + RxReservePacketManager manager(4, 1); + TestClock clock; + TestRadio radio; + TestDispatcher dispatcher(radio, clock, manager); + dispatcher.configured_agc_interval = 8000; + dispatcher.adaptive_agc = true; + dispatcher.begin(); + dispatcher.loop(); + dispatchNextAgc(dispatcher, clock); + dispatchNextAgc(dispatcher, clock); + ASSERT_EQ(16000U, nextAgcWake(dispatcher)); + ++clock.now; + dispatcher.adaptive_agc = false; + dispatcher.loop(); + uint32_t delay = 0; + EXPECT_FALSE(dispatcher.nextQueueWakeDelay(delay)); // Fixed mode keeps its queue-only query. + for (unsigned i = 0; i < 3; ++i) { + clock.now += 8001; + dispatcher.loop(); + EXPECT_EQ(int(3 + i), radio.agc_resets); // Power saving off stays fixed. + } + dispatcher.adaptive_agc = true; + ++clock.now; + dispatcher.loop(); + ASSERT_EQ(8000U, nextAgcWake(dispatcher)); + dispatchNextAgc(dispatcher, clock); + EXPECT_EQ(8000U, nextAgcWake(dispatcher)); // No inherited fixed-mode streak. + dispatcher.configured_agc_interval = 12000; + dispatcher.loop(); + EXPECT_EQ(12000U, nextAgcWake(dispatcher)); + dispatcher.configured_agc_interval = 0; + dispatcher.loop(); + EXPECT_FALSE(dispatcher.nextQueueWakeDelay(delay)); + const int attempts = radio.agc_attempts; + clock.now += 120000; + dispatcher.loop(); + EXPECT_EQ(attempts, radio.agc_attempts); + dispatcher.configured_agc_interval = 8000; + dispatcher.loop(); + EXPECT_EQ(8000U, nextAgcWake(dispatcher)); +} + +TEST(Dispatcher, AdaptiveAgcDeclinesAndNoiseFloorWindowsDoNotPromoteOrHotRetry) { + RxReservePacketManager manager(4, 1); + TestClock clock; + TestRadio radio; + TestDispatcher dispatcher(radio, clock, manager); + dispatcher.configured_agc_interval = 8000; + dispatcher.adaptive_agc = true; + dispatcher.begin(); + dispatcher.loop(); + radio.agc_admitted = false; + dispatchNextAgc(dispatcher, clock); + ASSERT_EQ(1, radio.agc_attempts); + EXPECT_EQ(0, radio.agc_resets); + EXPECT_EQ(50U, nextAgcWake(dispatcher)); + clock.now += 49; + dispatcher.loop(); + EXPECT_EQ(1, radio.agc_attempts); + EXPECT_EQ(1U, nextAgcWake(dispatcher)); + ++clock.now; + dispatcher.loop(); + EXPECT_EQ(2, radio.agc_attempts); + EXPECT_EQ(0, radio.agc_resets); + radio.agc_admitted = true; + clock.now += 50; + dispatcher.loop(); + ASSERT_EQ(1, radio.agc_resets); + EXPECT_EQ(8000U, nextAgcWake(dispatcher)); + radio.noise_floor_active = true; + dispatchNextAgc(dispatcher, clock); + EXPECT_EQ(3, radio.agc_attempts); // Dispatcher defers without touching the radio. + EXPECT_EQ(1, radio.agc_resets); + EXPECT_EQ(50U, nextAgcWake(dispatcher)); + radio.noise_floor_active = false; + clock.now += 50; + dispatcher.loop(); + EXPECT_EQ(2, radio.agc_resets); + EXPECT_EQ(16000U, nextAgcWake(dispatcher)); // Exactly two accepted attempts. +} + +TEST(Dispatcher, AdaptiveAgcRecoveryCounterChangesIncludingWrapRestoreBase) { + const uint32_t before[] = {10, UINT32_MAX, 10}; + const uint32_t after[] = {11, 0, 0}; + for (unsigned scenario = 0; scenario < 3; ++scenario) { + SCOPED_TRACE(scenario); + RxReservePacketManager manager(4, 1); + TestClock clock; + TestRadio radio; + radio.recovery_count = before[scenario]; + TestDispatcher dispatcher(radio, clock, manager); + dispatcher.configured_agc_interval = 8000; + dispatcher.adaptive_agc = true; + dispatcher.begin(); + dispatcher.loop(); + dispatchNextAgc(dispatcher, clock); + dispatchNextAgc(dispatcher, clock); + ASSERT_EQ(16000U, nextAgcWake(dispatcher)); + clock.now += 100; + radio.recovery_count = after[scenario]; + dispatcher.loop(); + EXPECT_EQ(2, radio.agc_resets); + EXPECT_EQ(8000U, nextAgcWake(dispatcher)); + dispatchNextAgc(dispatcher, clock); + EXPECT_EQ(3, radio.agc_resets); + EXPECT_EQ(8000U, nextAgcWake(dispatcher)); // Recovery cleared the old streak. + } +} + +TEST(Dispatcher, FrequentTransmitsPostponeFixedButNotAdaptiveAgc) { + for (bool adaptive : {false, true}) { + SCOPED_TRACE(adaptive); + RxReservePacketManager manager(4, 1); + TestClock clock; + clock.now = 1000; + TestRadio radio; + TestDispatcher dispatcher(radio, clock, manager); + dispatcher.configured_agc_interval = 8000; + dispatcher.adaptive_agc = adaptive; + dispatcher.begin(); + dispatcher.loop(); + for (uint32_t send_at : {2000U, 4000U, 8000U}) { + clock.now = send_at; + auto* packet = dispatcher.obtainNewPacket(); + ASSERT_NE(packet, nullptr); + packet->header = ROUTE_TYPE_DIRECT | (PAYLOAD_TYPE_RAW_CUSTOM << PH_TYPE_SHIFT); + packet->payload_len = 1; + packet->payload[0] = 0x42; + ASSERT_TRUE(dispatcher.sendPacket(packet, 0)); + dispatcher.loop(); + ++clock.now; + radio.send_complete = true; + dispatcher.loop(); + radio.send_complete = false; + } + ASSERT_EQ(3, radio.send_starts); + ASSERT_EQ(3, dispatcher.completed_packets); + clock.now = 9001; + dispatcher.loop(); + EXPECT_EQ(adaptive ? 1 : 0, radio.agc_resets); + } +} + +TEST(Dispatcher, AdaptiveAgcWaitsForOnAirTransmitButKeepsTheOverdueDeadline) { + RxReservePacketManager manager(4, 1); + TestClock clock; + clock.now = 1000; + TestRadio radio; + radio.airtime_ms = 200; // Keep this simulated send inside its real Dispatcher timeout. + TestDispatcher dispatcher(radio, clock, manager); + dispatcher.configured_agc_interval = 8000; + dispatcher.adaptive_agc = true; + dispatcher.begin(); + dispatcher.loop(); + clock.now = 8990; + auto* packet = dispatcher.obtainNewPacket(); + ASSERT_NE(packet, nullptr); + packet->header = ROUTE_TYPE_DIRECT | (PAYLOAD_TYPE_RAW_CUSTOM << PH_TYPE_SHIFT); + packet->payload_len = 1; + packet->payload[0] = 0x42; + ASSERT_TRUE(dispatcher.sendPacket(packet, 0)); + dispatcher.loop(); + ASSERT_EQ(1, radio.send_starts); + clock.now = 9001; + dispatcher.loop(); + EXPECT_EQ(0, radio.agc_attempts); + EXPECT_EQ(0U, nextAgcWake(dispatcher)); // Normal fast TX lifecycle remains due. + clock.now = 9100; + radio.send_complete = true; + dispatcher.loop(); + EXPECT_EQ(1, dispatcher.completed_packets); + EXPECT_EQ(1, radio.agc_resets); + EXPECT_EQ(8000U, nextAgcWake(dispatcher)); +} + +TEST(Dispatcher, AdaptiveAgcWakeLimitSharesTheEarliestQueuedDeadline) { + RxReservePacketManager manager(4, 1); + TestClock clock; + clock.now = 1000; + TestRadio radio; + TestDispatcher dispatcher(radio, clock, manager); + dispatcher.configured_agc_interval = 8000; + dispatcher.adaptive_agc = true; + dispatcher.begin(); + dispatcher.loop(); + EXPECT_EQ(8000U, nextAgcWake(dispatcher)); // Idle device must still wake for AGC. + auto* packet = dispatcher.obtainNewPacket(); + ASSERT_NE(packet, nullptr); + packet->header = ROUTE_TYPE_DIRECT | (PAYLOAD_TYPE_RAW_CUSTOM << PH_TYPE_SHIFT); + packet->payload_len = 1; + packet->payload[0] = 0x42; + manager.queueInbound(packet, 2000); + EXPECT_EQ(1000U, nextAgcWake(dispatcher)); + clock.now = 2001; + dispatcher.loop(); + EXPECT_EQ(1, dispatcher.received_packets); + EXPECT_EQ(6999U, nextAgcWake(dispatcher)); +} + +TEST(Dispatcher, AdaptiveAgcMillisRolloverAndSuccessfulRxDoNotMoveMaintenance) { + RxReservePacketManager manager(4, 1); + TestClock clock; + clock.now = UINT32_MAX - 4000U; + TestRadio radio; + TestDispatcher dispatcher(radio, clock, manager); + dispatcher.configured_agc_interval = 8000; + dispatcher.adaptive_agc = true; + dispatcher.begin(); + dispatcher.loop(); + ASSERT_EQ(8000U, nextAgcWake(dispatcher)); + clock.now = 3998; + const uint8_t raw[] = { + ROUTE_TYPE_DIRECT | (PAYLOAD_TYPE_RAW_CUSTOM << PH_TYPE_SHIFT), 0, 0x42 + }; + radio.queueRx(raw, sizeof(raw)); + dispatcher.loop(); + EXPECT_EQ(1, dispatcher.received_packets); + EXPECT_EQ(0, radio.agc_resets); + EXPECT_EQ(1U, nextAgcWake(dispatcher)); // A good packet is not an AGC-health proof. + clock.now = 3999; + dispatcher.loop(); + EXPECT_EQ(1, radio.agc_resets); + EXPECT_EQ(8000U, nextAgcWake(dispatcher)); + dispatchNextAgc(dispatcher, clock); + EXPECT_EQ(2, radio.agc_resets); + EXPECT_EQ(16000U, nextAgcWake(dispatcher)); +} + TEST(StaticPoolPacketManager, ReportsEarliestQueueTimesWithoutDequeuing) { StaticPoolPacketManager manager(8); mesh::Packet* later = manager.allocNew(); @@ -1329,6 +1632,62 @@ TEST(RxReservePacketManager, DispatcherKeepsOtaQueuedAcrossSlowQuietWindow) { EXPECT_EQ(manager.getFreeCount(), 8); } +TEST(Dispatcher, SameLoopRecoveryPreventsSleepBeforeAdaptiveAgcRestoresBase) { + class RecoveringRadio : public TestRadio { + public: + bool recoverRadio(bool hard) override { + const bool recovered = TestRadio::recoverRadio(hard); + ++recovery_count; + if (recovered) in_recv_mode = true; + return recovered; + } + } radio; + RxReservePacketManager manager(4, 1); + TestClock clock; + TestDispatcher dispatcher(radio, clock, manager); + dispatcher.configured_agc_interval = 8000; + dispatcher.adaptive_agc = true; + dispatcher.begin(); + dispatcher.loop(); + for (unsigned attempt = 0; attempt < 6; ++attempt) { + dispatchNextAgc(dispatcher, clock); + } + ASSERT_EQ(6, radio.agc_resets); + ASSERT_EQ(60000U, nextAgcWake(dispatcher)); + + // This recovery runs after the loop's initial scheduler configuration. + // An RXPS driver can defer its requested floor calibration until next loop, + // so the application may immediately ask whether it can take a long sleep. + radio.in_recv_mode = false; + dispatcher.loop(); + clock.now += 8001; + dispatcher.loop(); + ASSERT_EQ(1, radio.soft_recoveries); + ASSERT_EQ(1U, radio.recovery_count); + EXPECT_EQ(6, radio.agc_resets); + EXPECT_EQ(0U, nextAgcWake(dispatcher)); + + dispatcher.loop(); + EXPECT_EQ(8000U, nextAgcWake(dispatcher)); + clock.now += 7999; + dispatcher.loop(); + EXPECT_EQ(6, radio.agc_resets); + EXPECT_EQ(1U, nextAgcWake(dispatcher)); + ++clock.now; + dispatcher.loop(); + EXPECT_EQ(7, radio.agc_resets); + EXPECT_EQ(8000U, nextAgcWake(dispatcher)); + + // A disabled maintenance interval must not turn unrelated recoveries into + // an always-due wake request while its scheduler is intentionally reset. + dispatcher.configured_agc_interval = 0; + dispatcher.loop(); + ++radio.recovery_count; + uint32_t delay = 123; + EXPECT_FALSE(dispatcher.nextQueueWakeDelay(delay)); + EXPECT_EQ(123U, delay); +} + int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); diff --git a/test/test_radio_receive_contract.py b/test/test_radio_receive_contract.py index 9fe019fa3..bdc5e131a 100644 --- a/test/test_radio_receive_contract.py +++ b/test/test_radio_receive_contract.py @@ -92,6 +92,7 @@ struct RadioLibWrapper { int arm_result = 0, chip_mode = 1; float rssi = -100; unsigned arms = 0, stops = 0, soft = 0, hard = 0, reads = 0, mode_reads = 0; + uint32_t n_wd_soft = 0, n_wd_hard = 0; unsigned calibration_arms = 0, gain_changes = 0, agc_resets = 0; bool inject_mode_irq = false; NoiseFloorEstimator _floor_estimator; @@ -142,10 +143,20 @@ struct RadioLibWrapper { void requestNoiseFloorRefresh(); void requestPeriodicNoiseFloorRefresh(); void recalibrateNoiseFloor(); + bool resetAGCIfIdle(); + bool tryResetAGC(); void resetAGC(); + @RECOVERY_GETTER@ }; @METHODS@ +struct LegacyRadio { + unsigned resets = 0; + virtual void resetAGC() { ++resets; } + @LEGACY_TRY_RESET@ + @LEGACY_RECOVERY_GETTER@ +}; + // Exercise both public callers and the shared policy itself. Continuous and // fallback Dispatcher triggers intentionally retain their unconditional legacy // request; only passive polling and the helper use the two-second age gate. @@ -318,8 +329,122 @@ static void periodicRefreshContracts() { std::printf("PASS: routine noise-floor cooldown (%u cases)\n", cases); } +static void agcAdmissionContracts() { + unsigned cases = 0; + for (unsigned mode : {0U, 1U, 2U}) for (unsigned owned : {0U, 1U, 2U, 3U, 4U}) { + if (mode == 1 && owned == 1) continue; // known RXPS sleep has an explicit wake path + RadioLibWrapper w; selectMode(w, mode); + w._rx_ps_armed = mode == 1; + w._rx_boosted_gain_valid = w._cur_rx_boosted_gain = true; + w._nf_last_calib = now_ms; + w._nf_calib_deadline = now_ms + 800; + w._nf_sample_from = now_ms + NF_CALIB_SETTLE_MS; + assert(w._floor_estimator.add(-30, now_ms)); + assert(w._secondary_floor_estimator.add(-30, now_ms)); + if (owned == 0) w._cw_active = true; + if (owned == 1) w.busy = true; // unknown/continuous BUSY must defer + if (owned == 2) w.events.record(); + if (owned == 3) w.packet = true; + if (owned == 4) w.state = STATE_TX_WAIT; + const auto state = w.state, armed = uint8_t(w._rx_ps_armed); + const auto deadline = w._nf_calib_deadline, sample_from = w._nf_sample_from; + unsigned admitted = 0; + for (unsigned retry = 0; retry < 3; ++retry) { + if (w.tryResetAGC()) ++admitted; + // Legacy AGC deliberately retains its historical ability to reset while + // BUSY. The adaptive try API defers outside known RXPS sleep. + if (owned != 1) w.resetAGC(); + assert(admitted == 0 && w.agc_resets == 0 && w.gain_changes == 0); + assert(w.state == state && w._rx_ps_armed == bool(armed)); + assert(w._nf_last_calib == now_ms && w._nf_refresh_requested); + assert(w._nf_calib_deadline == deadline && w._nf_sample_from == sample_from); + assert(w._floor_estimator.count() == 1 && w._secondary_floor_estimator.count() == 1); + assert(w._noise_floor_valid && w._noise_floor_secondary_valid); + assert(w._noise_floor_centi_dbm == -10500 && w._noise_floor_secondary_centi_dbm == -10600); + if (owned == 2) assert(w.hasPendingRadioInterrupt()); // never consume another owner's IRQ + } + w._cw_active = w.busy = w.packet = false; + w.claimRadioInterrupt(); w.state = STATE_RX; + assert(w.tryResetAGC()); ++admitted; + assert(admitted == 1 && w.agc_resets == 1 && w.gain_changes == 1); + assert(w.state == STATE_IDLE && w._nf_refresh_requested && w._nf_last_calib == 0); + assert(w._floor_estimator.count() == 0 && w._secondary_floor_estimator.count() == 0); + ++cases; + } + { + RadioLibWrapper w; selectMode(w, 1); + w._rx_ps_armed = true; w.busy = true; + bool admitted = false; + // A valid 1 ms listen / 49 ms sleep cycle can remain BUSY at every + // phase-25 poll. Known RXPS must use the legacy explicit wake sequence. + for (unsigned retry = 0; retry < 10000 && !admitted; ++retry) { + now_ms = 25 + retry * 50; + admitted = w.tryResetAGC(); + } + assert(admitted && w.agc_resets == 1 && w.state == STATE_IDLE); + assert(w._nf_refresh_requested && w._noise_floor_valid); + assert(w.reads == 0 && w.radio.scans == 0); + ++cases; + } + for (unsigned mode : {0U, 1U, 2U}) { + RadioLibWrapper w; selectMode(w, mode); + w.busy = true; w._nf_refresh_requested = false; w._nf_last_calib = now_ms; + assert(!w.tryResetAGC() && w.agc_resets == 0 && !w._nf_refresh_requested); + w.resetAGC(); + assert(w.agc_resets == 1 && w.state == STATE_IDLE); + assert(w._nf_refresh_requested && w._nf_last_calib == 0); + ++cases; + } + // Admission reports that the sequence ran, not that the hardware is healthy. + // Both public APIs preserve independent published floors/validity and the + // active window's bound while invalidating samples from the old AGC path. + for (unsigned mode : {0U, 1U, 2U}) for (bool primary : {false, true}) + for (bool secondary : {false, true}) for (bool active_window : {false, true}) + for (bool legacy : {false, true}) { + RadioLibWrapper w; selectMode(w, mode); + w._rx_ps_armed = mode == 1 && !active_window; + w._rx_boosted_gain_valid = w._cur_rx_boosted_gain = true; + w._noise_floor_valid = primary; w._noise_floor_secondary_valid = secondary; + w._nf_calib_active = active_window; w._nf_last_calib = now_ms; + w._nf_calib_deadline = now_ms + 800; + w.n_wd_soft = 2; w.n_wd_hard = 3; + assert(w.getRecoveryCount() == 5); + assert(w._floor_estimator.add(-30, now_ms)); + assert(w._secondary_floor_estimator.add(-30, now_ms)); + ++now_ms; + if (legacy) w.resetAGC(); + else assert(w.tryResetAGC()); + assert(w.agc_resets == 1 && w.gain_changes == 1 && w.arms == 0); + assert(w.state == STATE_IDLE && w._nf_refresh_requested && w._nf_last_calib == 0); + assert(w._noise_floor_valid == primary && w._noise_floor_secondary_valid == secondary); + assert(w._noise_floor == -105 && w._noise_floor_centi_dbm == -10500); + assert(w._noise_floor_secondary_centi_dbm == -10600); + assert(w._floor_estimator.count() == 0 && w._secondary_floor_estimator.count() == 0); + assert(w._nf_sample_from == now_ms + NF_CALIB_SETTLE_MS); + assert(w._nf_calib_active == active_window); + assert(w._nf_calib_deadline == (active_window ? now_ms + NF_CALIB_TIMEOUT_MS : 0)); + assert(w.getRecoveryCount() == 5); // AGC attempts do not inflate watchdog recovery counters + ++cases; + } + { + RadioLibWrapper w; + assert(w.getRecoveryCount() == 0); + w.n_wd_soft = 1; assert(w.getRecoveryCount() == 1); + w.n_wd_hard = 2; assert(w.getRecoveryCount() == 3); + ++cases; + } + { + LegacyRadio radio; + assert(radio.tryResetAGC() && radio.resets == 1); + assert(radio.getRecoveryCount() == 0); + ++cases; + } + std::printf("PASS: AGC admission (%u cases)\n", cases); +} + int main() { periodicRefreshContracts(); + agcAdmissionContracts(); // A completed packet, current frame, or TX owns the radio; CAD cannot erase it. for (int owned : {1, 2, 3}) { RadioLibWrapper w; @@ -776,10 +901,11 @@ int main() { result = subprocess.run([str(binary)], capture_output=True, text=True) self.assertEqual(result.returncode, 0, result.stderr) - def run_production_transitions(self, source=None, expect_failure=False): + def run_production_transitions(self, source=None, expect_failure=False, phase_failure=False): if source is None: source = (ROOT / 'src/helpers/radiolib/RadioLibWrappers.cpp').read_text() header = (ROOT / 'src/helpers/radiolib/RadioLibWrappers.h').read_text() + dispatcher = (ROOT / 'src/Dispatcher.h').read_text() rxps = (ROOT / 'src/helpers/radiolib/RXPowerSaving.h').read_text() names = [('int16_t','performChannelScanWithTimeout'), ('bool','isPacketPendingOrReceiving'), ('bool','isChannelActive'), ('bool','isReceivingPassive'), @@ -788,7 +914,8 @@ int main() { ('void','loop'), ('void','triggerNoiseFloorCalibrate'), ('void','requestRestartRecv'), ('void','noiseFloorCalibCheck'), ('void','endNoiseFloorCalib'), ('void','requestNoiseFloorRefresh'), ('void','requestPeriodicNoiseFloorRefresh'), - ('void','recalibrateNoiseFloor'), ('void','resetAGC')] + ('void','recalibrateNoiseFloor'), ('bool','resetAGCIfIdle'), + ('bool','tryResetAGC'), ('void','resetAGC')] methods = method(rxps, 'inline bool rxPowerSavingUsesContinuousFallback(') + '\n' methods += '\n'.join(method(source, f'{kind} RadioLibWrapper::{name}(') for kind,name in names) constants = '\n'.join(re.findall(r'^#define NF_\w+\s+[^\n]+', source, re.MULTILINE)) @@ -797,7 +924,10 @@ int main() { settle_start = header.index('#if defined(USE_SX1262) || defined(USE_SX1268) || defined(USE_LLCC68)') settle = header[settle_start:header.index('#endif', settle_start) + len('#endif')] harness = (HARNESS.replace('@METHODS@', methods).replace('@NF_CONSTANTS@', constants) - .replace('@SETTLE_CONSTANT@', settle)) + .replace('@SETTLE_CONSTANT@', settle) + .replace('@RECOVERY_GETTER@', method(header, 'uint32_t getRecoveryCount() const').replace('override', '')) + .replace('@LEGACY_TRY_RESET@', method(dispatcher, 'virtual bool tryResetAGC(')) + .replace('@LEGACY_RECOVERY_GETTER@', method(dispatcher, 'virtual uint32_t getRecoveryCount('))) with tempfile.TemporaryDirectory(prefix='meshcore-radio-transitions-') as tmp: cpp = Path(tmp) / 'test.cpp' binary = Path(tmp) / 'test' @@ -814,15 +944,28 @@ int main() { result = subprocess.run([str(binary)], capture_output=True, text=True, timeout=20) if expect_failure: self.assertNotEqual(result.returncode, 0, 'unthrottled negative control escaped the regression') - self.assertIn('periodicRefreshContracts', result.stderr) - self.assertIn('w._nf_refresh_requested == expected', result.stderr) + if phase_failure: + self.assertIn('agcAdmissionContracts', result.stderr) + self.assertIn('admitted && w.agc_resets == 1', result.stderr) + else: + self.assertIn('periodicRefreshContracts', result.stderr) + self.assertIn('w._nf_refresh_requested == expected', result.stderr) else: self.assertEqual(result.returncode, 0, result.stdout + result.stderr) self.assertIn('PASS: routine noise-floor cooldown (262 cases)', result.stdout) + self.assertIn('PASS: AGC admission (68 cases)', result.stdout) def test_production_transitions(self): self.run_production_transitions() + def test_busy_rxps_sleep_phase_lock_negative_control(self): + source = (ROOT / 'src/helpers/radiolib/RadioLibWrappers.cpp').read_text() + body = method(source, 'bool RadioLibWrapper::tryResetAGC(') + self.assertEqual(body.count('_rx_ps_armed || '), 1) + unguarded = body.replace('_rx_ps_armed || ', '') + self.run_production_transitions(source.replace(body, unguarded), + expect_failure=True, phase_failure=True) + def test_unthrottled_periodic_callers_and_helper_negative_controls(self): source = (ROOT / 'src/helpers/radiolib/RadioLibWrappers.cpp').read_text() for caller in ('triggerNoiseFloorCalibrate', 'isReceivingPassive', 'requestPeriodicNoiseFloorRefresh'): diff --git a/test/test_sensor_tracker_sleep.py b/test/test_sensor_tracker_sleep.py index cb716adac..2b3bb1073 100644 --- a/test/test_sensor_tracker_sleep.py +++ b/test/test_sensor_tracker_sleep.py @@ -198,8 +198,9 @@ struct Liveness {unsigned begins=0;uint32_t at=0;void begin(uint32_t now){++begi class Dispatcher { public: bool radio_available=true,dispatcher_started=true,radio_nonrx_timer_armed=true; - bool agc_reset_armed=true,prev_isrecv_mode=false,nonrx_soft_recovery_attempted=true; - uint32_t radio_nonrx_start=0,next_floor_calib_time=0,armed_agc_reset_interval=5; + bool prev_isrecv_mode=false,nonrx_soft_recovery_attempted=true; + struct { unsigned resets=0; void reset(){++resets;} } agc_reset; + uint32_t radio_nonrx_start=0,next_floor_calib_time=0; uint32_t rx_watchdog_window_start=0; Ms ms;Ms* _ms=&ms;DispatcherRadio radio;DispatcherRadio* _radio=&radio;Liveness radio_liveness; void setRadioAvailable(bool available); @@ -220,7 +221,7 @@ int main(){ assert(!d.radio_available&&!d.radio_nonrx_timer_armed&&d.radio.begins==0); d.setRadioAvailable(true);assert(d.radio_available&&d.radio.begins==1&&d.prev_isrecv_mode); assert(d.radio_nonrx_start==12345&&d.next_floor_calib_time==12345); - assert(!d.agc_reset_armed&&d.armed_agc_reset_interval==0); + assert(d.agc_reset.resets==1); #ifdef RADIO_LIVENESS_SOFT_ONLY assert(d.rx_watchdog_window_start==12345); #else diff --git a/variants/rak3x72/platformio.ini b/variants/rak3x72/platformio.ini index 792f5c80e..ae47ba55a 100644 --- a/variants/rak3x72/platformio.ini +++ b/variants/rak3x72/platformio.ini @@ -70,6 +70,8 @@ build_flags = ${rak3x72.build_flags} -D ED25519_COMPACT_SCALAR=1 ; same ref10 arithmetic with fixed loops instead of unrolled code -Oz -flto + -fno-reorder-blocks + -fno-reorder-functions -fno-inline-small-functions -fno-tree-dominator-opts ; preserve the 32 KiB filesystem with the stability guards -fipa-pta diff --git a/variants/wio-e5-mini/platformio.ini b/variants/wio-e5-mini/platformio.ini index 5005c1b9a..e2a9203f4 100644 --- a/variants/wio-e5-mini/platformio.ini +++ b/variants/wio-e5-mini/platformio.ini @@ -83,6 +83,8 @@ build_flags = ${lora_e5_mini.build_flags} -D ED25519_COMPACT_SCALAR=1 ; same ref10 arithmetic with fixed loops instead of unrolled code -Oz -flto + -fno-reorder-blocks + -fno-reorder-functions -fno-inline-small-functions -fno-tree-dominator-opts ; save 160 release bytes while preserving the 32 KiB filesystem -fno-caller-saves ; avoid spill-code growth and retain the 32 KiB filesystem