From 63823f526beb53615809db68b95274580be68ca8 Mon Sep 17 00:00:00 2001 From: TeTeHacko Date: Fri, 4 Dec 2026 00:09:19 +0100 Subject: [PATCH] Repeater, room server, sensor: `set radio.rxps off` takes effect at once, and reception restarts after the noise-floor calibration MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Changelog-cs: Repeater, room server, sensor: `set radio.rxps off` platí hned a příjem se po kalibraci šumu znovu nastartuje Changelog-topic: rxps-stall-46 --- docs/power.md | 17 +- examples/simple_repeater/main.cpp | 3 +- src/Dispatcher.h | 2 + src/helpers/NodeMaintenance.cpp | 18 +- src/helpers/NodeMaintenance.h | 6 +- src/helpers/radiolib/CustomSX1262.h | 5 + src/helpers/radiolib/CustomSX1262Wrapper.h | 3 + src/helpers/radiolib/RadioLibWrappers.cpp | 65 +++++- src/helpers/radiolib/RadioLibWrappers.h | 4 +- test/mocks/RadioLib.h | 46 ++++ test/test_rxps/test_rxps.cpp | 238 +++++++++++++++++++++ 11 files changed, 382 insertions(+), 25 deletions(-) create mode 100644 test/mocks/RadioLib.h create mode 100644 test/test_rxps/test_rxps.cpp diff --git a/docs/power.md b/docs/power.md index d2ef055de..84a3a79a9 100644 --- a/docs/power.md +++ b/docs/power.md @@ -140,9 +140,20 @@ two hours of switching it on it stopped transmitting altogether: `sent` frozen, queue full (32), no `tx_start_fail`/`tx_timeout`, RX still counting -- so no adverts and no replies to an admin login, for 6+ hours. `radiostat` showed `irq=0x0014` (preamble + header valid, no RX done). `set radio.rxps off` did -NOT bring TX back; a reboot did. The mechanism is not proven, and the radio -silence watchdog cannot see it (it watches RX only). Do not enable rxps on a -node that has to answer. +NOT bring TX back; a reboot did. + +Three state-machine bugs in the RXPS wrapper were subsequently fixed (#46): +`set radio.rxps off` no longer waits on a latched `isReceiving()` / `irq=0x0014` +and tears down duty cycling immediately; non-`RX_DONE` DIO1 events (`TIMEOUT` / +`HEADER_ERR`) clear latched IRQ flags and reset `CustomSX1262` receive state +before re-arming (preventing a concurrent noise-floor calibration window from +leaving the chip in `STBY_RC`); and `stopReceiveDutyCycle()` / `kickRx()` clear +both the IRQ latch and the stateful receiver latch (while keeping IRQ flags +intact across `readData()` on valid `RX_DONE` so `CRC_ERR` is still detected). +The TX stall watchdog log also records `err_flags`, `tx_budget_ms` and +`next_tx_ms` in case the 6-hour stall recurs. Until a soak test on the live mesh +confirms stability (prefer `balanced` over `max` for SNR margin), keep rxps off +on nodes that must answer. ## MCU sleep diff --git a/examples/simple_repeater/main.cpp b/examples/simple_repeater/main.cpp index d1b2a796d..39e845da2 100644 --- a/examples/simple_repeater/main.cpp +++ b/examples/simple_repeater/main.cpp @@ -1130,7 +1130,8 @@ void loop() { #endif the_mesh.loop(); - maint.loop(the_mesh.txQueued(), the_mesh.txDue()); // CUSTOM (TeTeHacko): deferred `dfu`, deaf-receiver and TX stall watchdogs + maint.loop(the_mesh.txQueued(), the_mesh.txDue(), the_mesh.getErrFlags(), + the_mesh.getRemainingTxBudget(), the_mesh.getNextTxDelayMs()); // CUSTOM (TeTeHacko): deferred `dfu`, deaf-receiver and TX stall watchdogs sensors.loop(); #ifdef DISPLAY_CLASS ui_task.loop(); diff --git a/src/Dispatcher.h b/src/Dispatcher.h index 25625ec1e..dbc5a7957 100644 --- a/src/Dispatcher.h +++ b/src/Dispatcher.h @@ -196,6 +196,8 @@ public: unsigned long getTotalAirTime() const { return total_air_time; } unsigned long getReceiveAirTime() const {return rx_air_time; } unsigned long getRemainingTxBudget() const { return tx_budget_ms; } + uint16_t getErrFlags() const { return _err_flags; } + long getNextTxDelayMs() const { return (long)(next_tx_time - _ms->getMillis()); } uint32_t getNumSentFlood() const { return n_sent_flood; } uint32_t getNumSentDirect() const { return n_sent_direct; } uint32_t getNumRecvFlood() const { return n_recv_flood; } diff --git a/src/helpers/NodeMaintenance.cpp b/src/helpers/NodeMaintenance.cpp index e902fd9c0..1d08a4b8c 100644 --- a/src/helpers/NodeMaintenance.cpp +++ b/src/helpers/NodeMaintenance.cpp @@ -107,12 +107,13 @@ void NodeMaintenance::begin(FILESYSTEM* fs, NodePrefs* prefs, CommonCLICallbacks (unsigned) (1u << _silence.backoff())); } -void NodeMaintenance::loop(int tx_queued, int tx_due) { +void NodeMaintenance::loop(int tx_queued, int tx_due, uint16_t err_flags, + unsigned long tx_budget_ms, long next_tx_ms) { dfuTick(); #ifdef NODE_PWR_GUARD pwrTick(); #endif - txStallTick(tx_queued, tx_due); + txStallTick(tx_queued, tx_due, err_flags, tx_budget_ms, next_tx_ms); #ifdef FW_OTA _fw.loop(); #endif @@ -148,7 +149,8 @@ void NodeMaintenance::loop(int tx_queued, int tx_due) { // 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) { +void NodeMaintenance::txStallTick(int tx_queued, int tx_due, uint16_t err_flags, + unsigned long tx_budget_ms, long next_tx_ms) { _tx_queued = tx_queued; _tx_due = tx_due; uint32_t now = millis(); @@ -158,13 +160,15 @@ void NodeMaintenance::txStallTick(int tx_queued, int tx_due) { } 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)); + Serial.printf("tx stall: %d queued (%d due), err=0x%02x budget=%lu next=%ldms, nothing sent for %lu min, re-arming radio\n", + tx_queued, tx_due, (unsigned) err_flags, tx_budget_ms, next_tx_ms, + (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)); + Serial.printf("tx stall: %d queued (%d due), err=0x%02x budget=%lu next=%ldms, still nothing sent after %lu min, rebooting\n", + tx_queued, tx_due, (unsigned) err_flags, tx_budget_ms, next_tx_ms, + (unsigned long) (_txstall.quietMs(now) / 60000)); _silence_reboots++; silenceSave(_silence.backoff()); delay(100); // let the line out diff --git a/src/helpers/NodeMaintenance.h b/src/helpers/NodeMaintenance.h index 7a00d089b..54828e5fb 100644 --- a/src/helpers/NodeMaintenance.h +++ b/src/helpers/NodeMaintenance.h @@ -60,7 +60,8 @@ public: void begin(FILESYSTEM* fs, NodePrefs* prefs, CommonCLICallbacks* callbacks); // tx_queued < 0: the role does not report its queue, no TX stall watchdog. - void loop(int tx_queued = -1, int tx_due = -1); + void loop(int tx_queued = -1, int tx_due = -1, uint16_t err_flags = 0, + unsigned long tx_budget_ms = 0, long next_tx_ms = 0); // sender_timestamp == 0 means the local console (the same test CommonCLI uses // for `erase`); `dfu` refuses anything else. @@ -84,7 +85,8 @@ private: void silenceSave(uint8_t backoff); bool dfuCommand(uint32_t sender_timestamp, const char* command, char* reply); bool silenceCommand(const char* command, char* reply); - void txStallTick(int tx_queued, int tx_due); + void txStallTick(int tx_queued, int tx_due, uint16_t err_flags, + unsigned long tx_budget_ms, long next_tx_ms); bool txStallCommand(const char* command, char* reply); void dfuTick(); #ifdef NODE_PWR_GUARD diff --git a/src/helpers/radiolib/CustomSX1262.h b/src/helpers/radiolib/CustomSX1262.h index 70b0c59f2..8d059ed1a 100644 --- a/src/helpers/radiolib/CustomSX1262.h +++ b/src/helpers/radiolib/CustomSX1262.h @@ -222,6 +222,11 @@ class CustomSX1262 : public SX1262 { MESH_DEBUG_PRINTLN("Set _maxPayloadMillis=%u", _maxPayloadMillis); } + void resetReceivingState() { + _activityAt = 0; + _headerSeen = false; + } + bool getRxBoostedGainMode() { uint8_t rxGain = 0; readRegister(RADIOLIB_SX126X_REG_RX_GAIN, &rxGain, 1); diff --git a/src/helpers/radiolib/CustomSX1262Wrapper.h b/src/helpers/radiolib/CustomSX1262Wrapper.h index fd37821ee..fafe3bc6e 100644 --- a/src/helpers/radiolib/CustomSX1262Wrapper.h +++ b/src/helpers/radiolib/CustomSX1262Wrapper.h @@ -49,6 +49,9 @@ public: #endif return ((CustomSX1262 *)_radio)->isReceiving(); } + void resetReceivingState() override { + ((CustomSX1262 *)_radio)->resetReceivingState(); + } #ifdef WITH_RX_POWERSAVING bool isChipBusy() override { return ((CustomSX1262 *)_radio)->isChipBusy(); } #endif diff --git a/src/helpers/radiolib/RadioLibWrappers.cpp b/src/helpers/radiolib/RadioLibWrappers.cpp index 1420e91cd..16c32ef1c 100644 --- a/src/helpers/radiolib/RadioLibWrappers.cpp +++ b/src/helpers/radiolib/RadioLibWrappers.cpp @@ -86,6 +86,7 @@ void RadioLibWrapper::idle() { if (_rx_ps_armed) stopReceiveDutyCycle(); #endif _radio->standby(); + resetReceivingState(); state = STATE_IDLE; // need another startReceive() } @@ -163,10 +164,13 @@ void RadioLibWrapper::loop() { #endif #ifdef WITH_RX_POWERSAVING - if (_rx_ps_restart_pending && (state & ~STATE_INT_READY) != STATE_TX_WAIT && - !isPacketPendingOrReceiving()) { - _rx_ps_restart_pending = false; - requestRestartRecv(); + if (_rx_ps_restart_pending && (state & ~STATE_INT_READY) != STATE_TX_WAIT) { + if (!_rx_ps_enabled) { + disableRxPowerSavingNow(); + } else if (!isPacketPendingOrReceiving()) { + _rx_ps_restart_pending = false; + requestRestartRecv(); + } } noiseFloorCalibCheck(); @@ -335,14 +339,31 @@ int16_t RadioLibWrapper::startReceiveMode() { return fallback_err; } -void RadioLibWrapper::stopReceiveDutyCycle() { +void RadioLibWrapper::stopReceiveDutyCycle(bool clear_irq) { int16_t err = stopDutyCycleHardware(); + if (clear_irq) _radio->clearIrqFlags(0xFFFFFFFF); + resetReceivingState(); _rx_ps_armed = false; _rx_ps_eff_rx_us = 0; _rx_ps_eff_sleep_us = 0; if (err != RADIOLIB_ERR_NONE) _rx_ps_last_error = err; } +void RadioLibWrapper::disableRxPowerSavingNow() { + _rx_ps_restart_pending = false; + if (_rx_ps_armed) { + stopReceiveDutyCycle(true); + } else { + _radio->clearIrqFlags(0xFFFFFFFF); + resetReceivingState(); + } + noInterrupts(); + if ((state & ~STATE_INT_READY) != STATE_TX_WAIT) { + state = STATE_IDLE; + } + interrupts(); +} + bool RadioLibWrapper::isPacketReady() { if (!_rx_ps_armed) return true; return _radio->checkIrq(RADIOLIB_IRQ_RX_DONE) != 0; @@ -358,7 +379,11 @@ bool RadioLibWrapper::setRxPowerSaving(bool enabled, uint32_t rx_us, uint32_t sl if (enabled && (!isValidRxPowerSavingPeriod(rx_us) || !isValidRxPowerSavingPeriod(sleep_us))) { _rx_ps_enabled = false; _rx_ps_last_error = RX_POWERSAVING_ERR_TIMING; - requestRestartRecv(); + if ((state & ~STATE_INT_READY) != STATE_TX_WAIT) { + disableRxPowerSavingNow(); + } else { + _rx_ps_restart_pending = true; + } return false; } if (enabled && !supportsRxPowerSaving()) return false; @@ -369,9 +394,15 @@ bool RadioLibWrapper::setRxPowerSaving(bool enabled, uint32_t rx_us, uint32_t sl _rx_ps_last_error = RADIOLIB_ERR_NONE; _rx_ps_arm_retry.reset(); // new config, a fresh chance for the hardware _rx_ps_restart_pending = true; - if ((state & ~STATE_INT_READY) != STATE_TX_WAIT && !isPacketPendingOrReceiving()) { - _rx_ps_restart_pending = false; - requestRestartRecv(); + if ((state & ~STATE_INT_READY) != STATE_TX_WAIT) { + if (!enabled) { + // Explicit disable must not wait on a potentially stuck isReceiving() + // latch (e.g. irq=0x0014 without RX_DONE): tear down duty cycling now. + disableRxPowerSavingNow(); + } else if (!isPacketPendingOrReceiving()) { + _rx_ps_restart_pending = false; + requestRestartRecv(); + } } return true; } @@ -396,15 +427,27 @@ int RadioLibWrapper::recvRaw(uint8_t* bytes, int sz) { int len = 0; if (state & STATE_INT_READY) { #ifdef WITH_RX_POWERSAVING - // While duty cycling DIO1 also carries timeouts; only a real RX_DONE has data. + // While duty cycling DIO1 also carries timeouts and header/CRC errors; only + // a real RX_DONE has data. On any other DIO1 event the chip has already + // left SetRxDutyCycle into STBY_RC with stale IRQ flags still latched: tear + // down the duty cycle and clear them before re-arming, otherwise a + // concurrent noise-floor calib check sees the stale latch and skips re-arm. if (isPacketReady()) { - if (_rx_ps_armed) stopReceiveDutyCycle(); + // Leave IRQ flags intact for readData() so it can still detect CRC_ERR. + if (_rx_ps_armed) stopReceiveDutyCycle(false); len = _radio->getPacketLength(); if (len > 0) { _last_snr = _radio->getSNR(); _last_rssi = _radio->getRSSI(); _last_metrics_valid = true; + } else { + _radio->clearIrqFlags(0xFFFFFFFF); } + } else if (_rx_ps_armed) { + stopReceiveDutyCycle(true); + } else { + _radio->clearIrqFlags(0xFFFFFFFF); + resetReceivingState(); } #else len = _radio->getPacketLength(); diff --git a/src/helpers/radiolib/RadioLibWrappers.h b/src/helpers/radiolib/RadioLibWrappers.h index 11f100315..22992593b 100644 --- a/src/helpers/radiolib/RadioLibWrappers.h +++ b/src/helpers/radiolib/RadioLibWrappers.h @@ -72,7 +72,8 @@ protected: void noiseFloorCalibCheck(); void endNoiseFloorCalib(unsigned long now); int16_t startReceiveMode(); - void stopReceiveDutyCycle(); + void stopReceiveDutyCycle(bool clear_irq = true); + void disableRxPowerSavingNow(); // eff_rx_us/eff_sleep_us report the periods the driver really programmed. virtual int16_t armDutyCycle(RadioLibIrqFlags_t irq_flags, RadioLibIrqFlags_t irq_mask, uint32_t* eff_rx_us, uint32_t* eff_sleep_us) { @@ -89,6 +90,7 @@ protected: #endif float packetScoreInt(float snr, int sf, int packet_len); virtual bool isReceivingPacket() =0; + virtual void resetReceivingState() {} virtual bool lastRxHadCRC() { return true; } virtual void doResetAGC(); diff --git a/test/mocks/RadioLib.h b/test/mocks/RadioLib.h new file mode 100644 index 000000000..1523cd50c --- /dev/null +++ b/test/mocks/RadioLib.h @@ -0,0 +1,46 @@ +#pragma once + +#include +#include + +using RadioLibIrqFlags_t = uint32_t; + +#define RADIOLIB_ERR_NONE 0 +#define RADIOLIB_ERR_UNSUPPORTED -2 +#define RADIOLIB_ERR_CRC_MISMATCH -7 +#define RADIOLIB_ERR_LORA_HEADER_DAMAGED -16 +#define RADIOLIB_CHANNEL_FREE 0 + +#define RADIOLIB_IRQ_RX_DONE 1 +#define RADIOLIB_IRQ_PREAMBLE_DETECTED 2 +#define RADIOLIB_IRQ_HEADER_VALID 4 +#define RADIOLIB_IRQ_HEADER_ERR 5 +#define RADIOLIB_IRQ_CRC_ERR 6 +#define RADIOLIB_IRQ_TIMEOUT 9 + +#define RADIOLIB_IRQ_RX_DEFAULT_FLAGS ((1UL << RADIOLIB_IRQ_RX_DONE) | (1UL << RADIOLIB_IRQ_CRC_ERR) | (1UL << RADIOLIB_IRQ_HEADER_ERR) | (1UL << RADIOLIB_IRQ_HEADER_VALID)) +#define RADIOLIB_IRQ_RX_DEFAULT_MASK (1UL << RADIOLIB_IRQ_RX_DONE) + +class PhysicalLayer { +public: + virtual ~PhysicalLayer() = default; + virtual void setPacketReceivedAction(void (*func)(void)) { (void)func; } + virtual int16_t setPreambleLength(size_t len) { (void)len; return RADIOLIB_ERR_NONE; } + virtual int32_t random(int32_t max) { (void)max; return 1; } + virtual uint8_t randomByte() { return 0; } + virtual int16_t setOutputPower(int8_t power) { (void)power; return RADIOLIB_ERR_NONE; } + virtual int16_t standby() { return RADIOLIB_ERR_NONE; } + virtual int16_t sleep() { return RADIOLIB_ERR_NONE; } + virtual int16_t clearIrqFlags(RadioLibIrqFlags_t irq) { (void)irq; return RADIOLIB_ERR_NONE; } + virtual RadioLibIrqFlags_t getIrqFlags() { return 0; } + virtual bool checkIrq(uint8_t irq) { (void)irq; return false; } + virtual int16_t startReceive() { return RADIOLIB_ERR_NONE; } + virtual size_t getPacketLength(bool update = true) { (void)update; return 0; } + virtual int16_t readData(uint8_t* data, size_t len) { (void)data; (void)len; return RADIOLIB_ERR_NONE; } + virtual float getSNR() { return 0.0f; } + virtual float getRSSI() { return -100.0f; } + virtual uint32_t getTimeOnAir(size_t len) { (void)len; return 100000; } + virtual int16_t startTransmit(uint8_t* data, size_t len) { (void)data; (void)len; return RADIOLIB_ERR_NONE; } + virtual int16_t finishTransmit() { return RADIOLIB_ERR_NONE; } + virtual int16_t scanChannel() { return RADIOLIB_CHANNEL_FREE; } +}; diff --git a/test/test_rxps/test_rxps.cpp b/test/test_rxps/test_rxps.cpp new file mode 100644 index 000000000..5f2b99869 --- /dev/null +++ b/test/test_rxps/test_rxps.cpp @@ -0,0 +1,238 @@ +#include +#include +#include +#include + +// Minimal Arduino/LoRa shims needed to compile RadioLibWrappers.cpp on host. +#define WITH_RX_POWERSAVING 1 +#define LORA_SF 8 +#ifndef noInterrupts +#define noInterrupts() ((void)0) +#endif +#ifndef interrupts +#define interrupts() ((void)0) +#endif +using std::min; +using std::max; +inline long random(long lo, long hi) { return lo + (hi > lo ? 0 : 0); } + +#include "helpers/radiolib/RXPowerSaving.cpp" +#include "helpers/radiolib/RadioLibWrappers.cpp" + +namespace { + +class MockBoard : public mesh::MainBoard { +public: + uint8_t getStartupReason() const override { return 0; } + uint16_t getBattMilliVolts() override { return 3800; } + const char* getManufacturerName() const override { return "mock"; } + void reboot() override {} +}; + +class MockRadio : public PhysicalLayer { +public: + void (*isr_fn)(void) = nullptr; + RadioLibIrqFlags_t irq_flags = 0; + size_t next_pkt_len = 0; + int16_t read_data_err = RADIOLIB_ERR_NONE; + bool read_data_saw_irq_intact = false; + int clear_irq_calls = 0; + int standby_calls = 0; + int start_receive_calls = 0; + int read_data_calls = 0; + + void setPacketReceivedAction(void (*func)(void)) override { isr_fn = func; } + void fireDio1() { if (isr_fn) isr_fn(); } + + int16_t standby() override { + standby_calls++; + return RADIOLIB_ERR_NONE; + } + int16_t clearIrqFlags(RadioLibIrqFlags_t irq) override { + clear_irq_calls++; + irq_flags &= ~irq; + return RADIOLIB_ERR_NONE; + } + RadioLibIrqFlags_t getIrqFlags() override { return irq_flags; } + bool checkIrq(uint8_t irq) override { return (irq_flags & (1UL << irq)) != 0; } + int16_t startReceive() override { + start_receive_calls++; + irq_flags = 0; + return RADIOLIB_ERR_NONE; + } + size_t getPacketLength(bool) override { return next_pkt_len; } + int16_t readData(uint8_t* data, size_t len) override { + read_data_calls++; + read_data_saw_irq_intact = (irq_flags != 0); + if (len > 0) memset(data, 0xAA, len); + irq_flags = 0; + return read_data_err; + } +}; + +class TestRxpsWrapper : public RadioLibWrapper { +public: + bool receiving_latch = false; + int reset_receiving_calls = 0; + int arm_duty_cycle_calls = 0; + int stop_duty_cycle_hw_calls = 0; + int start_cont_rx_calls = 0; + + TestRxpsWrapper(MockRadio& r, MockBoard& b) : RadioLibWrapper(r, b) {} + + bool supportsRxPowerSaving() const override { return true; } + void setParams(float, float, uint8_t, uint8_t) override {} + float getCurrentRSSI() override { return -110.0f; } + bool isReceivingPacket() override { return receiving_latch; } + void resetReceivingState() override { + reset_receiving_calls++; + receiving_latch = false; + } + + int16_t armDutyCycle(RadioLibIrqFlags_t, RadioLibIrqFlags_t, + uint32_t* eff_rx_us, uint32_t* eff_sleep_us) override { + arm_duty_cycle_calls++; + *eff_rx_us = _rx_ps_rx_us; + *eff_sleep_us = _rx_ps_sleep_us; + return RADIOLIB_ERR_NONE; + } + int16_t stopDutyCycleHardware() override { + stop_duty_cycle_hw_calls++; + return _radio->standby(); + } + int16_t startContinuousReceive() override { + start_cont_rx_calls++; + return _radio->startReceive(); + } +}; + +struct RxpsFixture : public ::testing::Test { + MockRadio radio; + MockBoard board; + TestRxpsWrapper wrap{radio, board}; + + void SetUp() override { + g_mock_millis = 1000; + wrap.begin(); + ASSERT_TRUE(wrap.setRxPowerSaving(true, 20000, 60000)); + uint8_t buf[16]; + EXPECT_EQ(wrap.recvRaw(buf, sizeof(buf)), 0); + ASSERT_TRUE(wrap.getRxPowerSavingStatus().armed); + } +}; + +TEST_F(RxpsFixture, DisableRxpsClearsStuckHeaderLatchImmediately) { + // Simulate mast-three stuck state: irq=0x0014 (preamble + header valid, no RX_DONE) + // holding isReceivingPacket() == true. + radio.irq_flags = (1UL << RADIOLIB_IRQ_PREAMBLE_DETECTED) | (1UL << RADIOLIB_IRQ_HEADER_VALID); + wrap.receiving_latch = true; + + EXPECT_TRUE(wrap.setRxPowerSaving(false, 20000, 60000)); + + EXPECT_FALSE(wrap.getRxPowerSavingStatus().armed); + EXPECT_FALSE(wrap.receiving_latch); + EXPECT_EQ(radio.irq_flags, 0u); + EXPECT_GT(wrap.stop_duty_cycle_hw_calls, 0); + EXPECT_GT(wrap.reset_receiving_calls, 0); + + // Next recvRaw() must re-arm continuous RX, not duty cycle. + int prev_cont = wrap.start_cont_rx_calls; + uint8_t buf[16]; + EXPECT_EQ(wrap.recvRaw(buf, sizeof(buf)), 0); + EXPECT_EQ(wrap.start_cont_rx_calls, prev_cont + 1); + EXPECT_FALSE(wrap.getRxPowerSavingStatus().armed); +} + +TEST_F(RxpsFixture, DisableRxpsDeferredDuringTxThenClearsStuckLatch) { + uint8_t tx[4] = {1, 2, 3, 4}; + ASSERT_TRUE(wrap.startSendRaw(tx, sizeof(tx))); + + // Disable requested mid-TX must not clobber the active transmit. + EXPECT_TRUE(wrap.setRxPowerSaving(false, 20000, 60000)); + radio.fireDio1(); + ASSERT_TRUE(wrap.isSendComplete()); + wrap.onSendFinished(); + + // Even if a stale header latch appears before loop(), disable still completes. + radio.irq_flags = (1UL << RADIOLIB_IRQ_PREAMBLE_DETECTED) | (1UL << RADIOLIB_IRQ_HEADER_VALID); + wrap.receiving_latch = true; + wrap.loop(); + + EXPECT_FALSE(wrap.receiving_latch); + EXPECT_EQ(radio.irq_flags, 0u); + uint8_t buf[16]; + EXPECT_EQ(wrap.recvRaw(buf, sizeof(buf)), 0); + EXPECT_FALSE(wrap.getRxPowerSavingStatus().armed); + EXPECT_GT(wrap.start_cont_rx_calls, 0); +} + +TEST_F(RxpsFixture, TimeoutIrqDuringNoiseFloorCalibReArmsRxInsteadOfStayingInStandby) { + // Start a noise-floor calibration window (after NF_CALIB_INTERVAL_MS). + g_mock_millis += 65000; + wrap.loop(); + ASSERT_TRUE(wrap.isRxPowerSavingCalibrationActive()); + ASSERT_TRUE(wrap.getRxPowerSavingStatus().armed); + + // Before recvRaw() switches to continuous RX, DIO1 fires with TIMEOUT + stale + // PREAMBLE/HEADER flags (no RX_DONE). Without the fix, startReceiveMode() + // saw _nf_calib_active && _rx_ps_armed && isPacketPendingOrReceiving() and + // returned ERR_NONE without re-arming RX, leaving the chip in STBY_RC. + radio.irq_flags = (1UL << RADIOLIB_IRQ_TIMEOUT) | + (1UL << RADIOLIB_IRQ_PREAMBLE_DETECTED) | + (1UL << RADIOLIB_IRQ_HEADER_VALID); + wrap.receiving_latch = true; + radio.fireDio1(); + + int prev_cont = wrap.start_cont_rx_calls; + uint8_t buf[16]; + EXPECT_EQ(wrap.recvRaw(buf, sizeof(buf)), 0); + + EXPECT_FALSE(wrap.receiving_latch); + EXPECT_EQ(radio.irq_flags, 0u); + EXPECT_FALSE(wrap.getRxPowerSavingStatus().armed); + EXPECT_EQ(wrap.start_cont_rx_calls, prev_cont + 1); + EXPECT_TRUE(wrap.isInRecvMode()); +} + +TEST_F(RxpsFixture, ValidRxDonePreservesIrqForReadDataCrcCheck) { + radio.irq_flags = (1UL << RADIOLIB_IRQ_RX_DONE) | (1UL << RADIOLIB_IRQ_CRC_ERR); + radio.next_pkt_len = 8; + radio.read_data_err = RADIOLIB_ERR_CRC_MISMATCH; + radio.fireDio1(); + + uint8_t buf[16]; + EXPECT_EQ(wrap.recvRaw(buf, sizeof(buf)), 0); + EXPECT_EQ(radio.read_data_calls, 1); + EXPECT_TRUE(radio.read_data_saw_irq_intact); + EXPECT_EQ(wrap.getPacketsRecvErrors(), 1u); +} + +TEST_F(RxpsFixture, ValidRxDoneZeroLenStillClearsIrq) { + radio.irq_flags = (1UL << RADIOLIB_IRQ_RX_DONE); + radio.next_pkt_len = 0; + radio.fireDio1(); + + uint8_t buf[16]; + EXPECT_EQ(wrap.recvRaw(buf, sizeof(buf)), 0); + EXPECT_EQ(radio.read_data_calls, 0); + EXPECT_EQ(radio.irq_flags, 0u); +} + +TEST_F(RxpsFixture, KickRxClearsIrqAndResetsReceivingState) { + radio.irq_flags = (1UL << RADIOLIB_IRQ_PREAMBLE_DETECTED) | (1UL << RADIOLIB_IRQ_HEADER_VALID); + wrap.receiving_latch = true; + + wrap.kickRx(); + + EXPECT_FALSE(wrap.getRxPowerSavingStatus().armed); + EXPECT_FALSE(wrap.receiving_latch); + EXPECT_EQ(radio.irq_flags, 0u); + EXPECT_GT(wrap.reset_receiving_calls, 0); +} + +} // namespace + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +}