Merge PowerSaving-v17 and harden noise calibration and RX recovery

Port the measured RXPS model without changing Cascade wire preambles or automatically enabling experimental levels. Use a spaced weighted median with bounded calibration windows, preserve packet ownership across CAD, and check actual SX126x receive mode before recovery.

Preserve Cascade sleep and radio fixes, integrate the new sensor and board profiles, and correct BSEC script inheritance and the MKE UART pin conflict. Native regressions, production-method/SPI harnesses, and ESP32, nRF52, and STM32 builds pass. Hardware comparison and fault-injection validation are recorded privately.
This commit is contained in:
mikecarper committed 2026-09-10 13:19:22 -07:00
commit a60a6a1f60
34 files changed
+1800 -495

No files matched your search

+4 -1
View File
@@ -13,6 +13,8 @@ require integration or target testing; see "Local testing without hardware" in
pio test -e native # all suites except KISS modem
pio test -e native_kiss_modem # KISS modem suite
pio test -e native -f test_webconfig_keys # a single suite
python3 test/test_radio_receive_contract.py # real CAD/re-arm/calibration/mode-watchdog methods
python3 test/test_sx126x_receive_mode.py # pinned RadioLib SPI transport/status-byte regression
python3 test/test_firmware_ram.py # every firmware hook, ELF heaps, reservations, RAM report binding
python3 test/test_indicator_display_profile.py # Indicator RAM/scale contract
python3 test/test_indicator_render_profile.py # four-mode Indicator canvas matrix/fallback contract
@@ -136,7 +138,8 @@ does not reflect the GoogleTest count -- run the built binary directly
| `test_packet_manager` | `src/Packet.cpp`, `src/Dispatcher.cpp`, `src/helpers/StaticPoolPacketManager.cpp` | truncated-packet rejection, unavailable-radio behavior, scoped RX-delay replacement, queue/CAD scheduling, and staged radio/TX recovery |
| `test_persistent_store_format` | `src/helpers/PersistentStoreFormat.h` | contact-page headers and CRCs, dirty-page state, stable slot allocation, and bounded resumable legacy migration across power loss |
| `test_power_management` | `src/helpers/PowerManagementUtils.h` | median filtering of a brownout outlier and valid-reading requirements for the boot lock |
| `test_rx_power_saving` | `src/helpers/radiolib/RXPowerSaving.h` | level-derived timing, tuple-selected 32/64/128-symbol wire preambles, equivalent SF7/BW500, SF6/BW250, and SF5/BW125 profiles, SF5/BW250 and SF6/BW500 level-8/64 timing, SF5/BW500 level-8/128 timing, SF5/BW62.5 with a 16-symbol timing assumption, automatic retuning, and SX1262 TCXO timing thresholds |
| `test_rx_power_saving` | `src/helpers/radiolib/RXPowerSaving.h` | guarded timer/capture bounds across SF5-SF12, bandwidths, TCXO delays and wire preambles; experimental profiles; retuning and strict CLI parsing |
| `test_noise_floor_estimator` | `src/helpers/radiolib/NoiseFloorEstimator.h` | spaced median, weighting, outliers, persistent rises, timeout/reset semantics and clock rollover |
| `test_region_names` | `src/helpers/RegionNameUtils.h` | canonical public-region markers while preserving distinct private and differently named regions |
| `test_datagram_payload_limits` | `src/helpers/DatagramPayloadLimits.h` | encrypted datagram plaintext ceilings, including the anonymous region-reply prefix and worst-case cipher padding |
| `test_serial_packet_log` | `src/helpers/SerialPacketLog.h` | bounded USB packet logging and dropped-line reporting |
@@ -0,0 +1,114 @@
#include <gtest/gtest.h>
#include <helpers/radiolib/NoiseFloorEstimator.h>
static void fill(NoiseFloorEstimator& estimator, float dbm, uint32_t start = 0) {
for (unsigned i = 0; i < 64; ++i) ASSERT_TRUE(estimator.add(dbm, start + i * 50));
}
TEST(NoiseFloorEstimator, RequiresACompleteSpacedBlock) {
NoiseFloorEstimator n;
int32_t floor = -11000;
for (uint32_t t = 0; t < 1000; ++t) n.add(-100, t);
EXPECT_EQ(20, n.count());
EXPECT_FALSE(n.publish(floor, true));
EXPECT_EQ(-11000, floor);
for (uint32_t t = 1000; t <= 3150; ++t) n.add(-100, t);
EXPECT_TRUE(n.complete());
EXPECT_TRUE(n.publish(floor, true));
EXPECT_EQ(-10250, floor);
EXPECT_GT(NoiseFloorEstimator::WINDOW_TIMEOUT_MS, 3150U);
}
TEST(NoiseFloorEstimator, MedianRejectsMinorityOutliersAndKeepsFractionalDbm) {
NoiseFloorEstimator n;
int32_t floor = 0;
for (unsigned i = 0; i < 64; ++i) {
ASSERT_TRUE(n.add(i < 15 ? -30 : i > 48 ? -127 : -103.25f, i * 50));
}
EXPECT_TRUE(n.publish(floor, false));
EXPECT_EQ(-10325, floor);
}
TEST(NoiseFloorEstimator, HandlesEvenMedianAndClampsAtMinus120) {
NoiseFloorEstimator n;
int32_t floor = 0;
for (unsigned i = 0; i < 64; ++i) n.add(i < 32 ? -105.5f : -104.5f, i * 50);
ASSERT_TRUE(n.publish(floor, false));
EXPECT_EQ(-10500, floor);
n.reset(); fill(n, -127);
ASSERT_TRUE(n.publish(floor, false));
EXPECT_EQ(-12000, floor);
}
TEST(NoiseFloorEstimator, PersistentRiseEscapesTheOldAdmissionGate) {
NoiseFloorEstimator n;
int32_t floor = -12000;
for (unsigned block = 1; block <= 3; ++block) {
n.reset(); fill(n, -100);
EXPECT_EQ(block == 3, n.publish(floor, true));
EXPECT_EQ(block == 3 ? -10500 : -12000, floor);
}
n.reset(); fill(n, -100);
ASSERT_TRUE(n.publish(floor, true));
EXPECT_EQ(-10125, floor);
}
TEST(NoiseFloorEstimator, QuieterBlockBreaksTheConsecutiveRiseHold) {
NoiseFloorEstimator n;
int32_t floor = -10000;
fill(n, -70); EXPECT_FALSE(n.publish(floor, true));
n.reset(); fill(n, -110); EXPECT_TRUE(n.publish(floor, true));
EXPECT_EQ(-10750, floor);
n.reset(); fill(n, -70); EXPECT_FALSE(n.publish(floor, true));
EXPECT_EQ(1, n.heldBlocks());
}
TEST(NoiseFloorEstimator, PartialTimeoutDoesNotCountAsACompleteHeldBlock) {
NoiseFloorEstimator n;
int32_t floor = -12000;
fill(n, -100); EXPECT_FALSE(n.publish(floor, true));
n.reset(); n.add(-40, 10000);
EXPECT_FALSE(n.publish(floor, true));
n.reset(); fill(n, -100); EXPECT_FALSE(n.publish(floor, true));
EXPECT_EQ(-12000, floor);
n.reset(); fill(n, -100); EXPECT_TRUE(n.publish(floor, true));
}
TEST(NoiseFloorEstimator, GainResetDiscardsSamplesAndRiseHistory) {
NoiseFloorEstimator n;
int32_t floor = -12000;
fill(n, -100); EXPECT_FALSE(n.publish(floor, true));
n.reset(true);
EXPECT_EQ(0, n.count());
EXPECT_EQ(0, n.heldBlocks());
EXPECT_EQ(-12000, floor);
fill(n, -80); EXPECT_TRUE(n.publish(floor, false));
EXPECT_EQ(-8000, floor);
}
TEST(NoiseFloorEstimator, SpacingSurvivesMillisRolloverAndRejectsInvalidReads) {
NoiseFloorEstimator n;
EXPECT_FALSE(n.add(NAN, 0));
EXPECT_FALSE(n.add(INFINITY, 0));
EXPECT_FALSE(n.add(0, 0));
EXPECT_FALSE(n.add(-201, 0));
EXPECT_TRUE(n.add(-105, 0xFFFFFFF0U));
EXPECT_FALSE(n.add(-105, 0x20));
EXPECT_TRUE(n.add(-105, 0x22));
}
TEST(NoiseFloorEstimator, MajorityContaminationIsAnExplicitLimit) {
NoiseFloorEstimator n;
int32_t floor = -10500;
for (unsigned block = 0; block < 3; ++block) {
n.reset();
for (unsigned i = 0; i < 64; ++i) n.add(i < 48 ? -60 : -105, i * 50);
EXPECT_EQ(block == 2, n.publish(floor, true));
}
EXPECT_EQ(-7125, floor); // a median cannot distinguish sustained energy from noise
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
+244
View File
@@ -0,0 +1,244 @@
#!/usr/bin/env python3
"""Execute production CAD, receive re-arm, calibration and mode-watchdog methods."""
from pathlib import Path
import os
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
def method(text, signature):
start = text.index(signature)
end = text.index('{', start) + 1
depth = 1
while depth:
depth += (text[end] == '{') - (text[end] == '}')
end += 1
return text[start:end]
HARNESS = r'''
#include <cassert>
#include <cstdint>
#include <initializer_list>
#include <helpers/radiolib/NoiseFloorEstimator.h>
#define STATE_IDLE 0
#define STATE_RX 1
#define STATE_TX_WAIT 3
#define STATE_INT_READY 16
#define RADIOLIB_ERR_NONE 0
#define RADIOLIB_CHANNEL_FREE -15
#define RADIOLIB_ERR_UNKNOWN -16
#define RADIOLIB_ERR_RX_TIMEOUT -6
#define MAX_TRANS_UNIT 255
#define MESH_DEBUG_PRINTLN(...) ((void)0)
#define NF_CALIB_INTERVAL_MS 2000UL
#define NF_CALIB_TIMEOUT_MS NoiseFloorEstimator::WINDOW_TIMEOUT_MS
#define NF_CONTINUOUS_TIMEOUT_MS NoiseFloorEstimator::WINDOW_TIMEOUT_MS
#define NF_CALIB_SETTLE_MS 20UL
static volatile uint8_t state = STATE_RX;
static uint32_t now_ms = 0;
uint32_t millis() { return now_ms; }
void noInterrupts() {}
void interrupts() {}
void yield() { ++now_ms; }
struct Board {
unsigned n_cad_busy = 0, services = 0;
void serviceWatchdog() { ++services; }
};
struct Radio {
int scan_result = RADIOLIB_CHANNEL_FREE, start_result = 0;
unsigned scans = 0;
int startChannelScan() { ++scans; return start_result; }
int getChannelScanResult() {
if (scan_result != RADIOLIB_ERR_UNKNOWN) state |= STATE_INT_READY;
return scan_result;
}
};
struct RadioLibWrapper {
Board board; Board* _board = &board;
Radio radio; Radio* _radio = &radio;
bool _rx_ps_enabled = false, _rx_ps_armed = false, _rx_ps_continuous_fallback = false;
bool _nf_calib_active = false, _nf_refresh_requested = true, _noise_floor_valid = true;
bool _cad_enabled = true, packet = false, busy = false, inject_arm_irq = false;
bool _rx_boosted_gain_valid = false, _cur_rx_boosted_gain = false;
bool _wd_last_busy = false;
uint8_t _startrx_fails = 0, _rx_mode_failures = 0;
uint32_t _rx_mode_checked_at = 0, _rx_ps_rx_us = 50000, _rx_ps_sleep_us = 50000;
unsigned long _nf_last_calib = 0, _nf_calib_deadline = 0, _nf_sample_from = 0;
unsigned long _wd_last_transition = 0, _wd_stuck_thresh = 0, _wd_observe_ms = 0;
int16_t _threshold = 0, _noise_floor = -105;
int32_t _noise_floor_centi_dbm = -10500;
int arm_result = 0, chip_mode = 1;
float rssi = -100;
unsigned arms = 0, stops = 0, soft = 0, hard = 0, reads = 0;
NoiseFloorEstimator _floor_estimator;
RadioLibWrapper() { state = STATE_RX; now_ms = 100; }
bool isChipBusy() { return busy; }
bool isReceivingPacket() { return packet; }
float getCurrentRSSI() { ++reads; return rssi; }
int8_t readReceiveMode() { return chip_mode; }
bool recoverRadio(bool use_hard) { use_hard ? ++hard : ++soft; return true; }
void rxPsWatchdogCheck() {}
unsigned long getEstAirtimeFor(int) { return 10; }
void stopReceiveDutyCycle() { ++stops; _rx_ps_armed = false; }
void doResetAGC() {}
bool applyRxBoostedGainMode(bool) { return true; }
int startReceiveMode() {
++arms;
if (!arm_result) _rx_ps_armed = _rx_ps_enabled && !_nf_calib_active;
if (inject_arm_irq) state |= STATE_INT_READY;
return arm_result;
}
int16_t performChannelScan() { return performChannelScanWithTimeout(2500); }
int16_t performChannelScanWithTimeout(unsigned long);
bool isPacketPendingOrReceiving();
bool isChannelActive();
void startRecv();
void checkReceiveMode(uint32_t);
void loop();
void requestRestartRecv();
void noiseFloorCalibCheck(unsigned long);
void endNoiseFloorCalib(unsigned long);
void requestNoiseFloorRefresh();
void recalibrateNoiseFloor();
void resetAGC();
};
@METHODS@
int main() {
// A completed packet, current frame, or TX owns the radio; CAD cannot erase it.
for (int owned : {1, 2, 3}) {
RadioLibWrapper w;
if (owned == 1) state |= STATE_INT_READY;
if (owned == 2) w.packet = true;
if (owned == 3) state = STATE_TX_WAIT;
assert(w.isChannelActive());
assert(w.radio.scans == 0 && w.arms == 0);
}
for (int result : {RADIOLIB_CHANNEL_FREE, 1, -5, RADIOLIB_ERR_UNKNOWN}) {
for (bool ps : {false, true}) {
RadioLibWrapper w;
w._rx_ps_enabled = w._rx_ps_armed = ps;
w.radio.scan_result = result;
const bool active = w.isChannelActive();
assert(active == (result != RADIOLIB_CHANNEL_FREE));
assert(w.stops == unsigned(ps));
assert(w.arms == 1 && state == STATE_RX);
assert(w._rx_ps_armed == ps);
if (result == RADIOLIB_ERR_UNKNOWN) {
assert(now_ms == 2600 && w.board.services == 2);
}
}
}
{
RadioLibWrapper w;
w.radio.start_result = -5;
assert(w.isChannelActive());
assert(w.arms == 1 && state == STATE_RX);
}
{
RadioLibWrapper w;
w.arm_result = -5;
assert(w.isChannelActive()); // a free CAD with failed RX restoration is not success
assert(state == STATE_IDLE);
}
{
RadioLibWrapper w;
w.inject_arm_irq = true;
assert(w.isChannelActive());
assert(state == (STATE_RX | STATE_INT_READY)); // preserves the new packet
}
// A quiet ten-second window completes in ~3.2 s and powersaving resumes.
for (bool ps : {false, true}) {
RadioLibWrapper w;
w._rx_ps_enabled = w._rx_ps_armed = ps;
w._noise_floor_valid = false;
w._nf_last_calib = 0;
for (; now_ms < 4000; ++now_ms) {
w.loop();
if (state == STATE_IDLE) w.startRecv();
}
assert(!w._nf_refresh_requested && !w._nf_calib_active);
assert(w._noise_floor_valid && w._noise_floor_centi_dbm == -10000);
assert(w._rx_ps_armed == ps);
assert(w.reads == 64); // no unnecessary SPI RSSI reads between accepted samples
}
// Repeated scheduled requests must not reset a partial block.
{
RadioLibWrapper w;
for (; now_ms < 4100; ++now_ms) {
if (now_ms % 2000 == 0) w.requestNoiseFloorRefresh();
w.loop();
}
assert(w._noise_floor_centi_dbm == -10125);
}
// Busy continuous RX times out without changing the published floor.
{
RadioLibWrapper w;
w.packet = true;
for (; now_ms <= 10101; ++now_ms) w.loop();
assert(!w._nf_refresh_requested);
assert(w._noise_floor_centi_dbm == -10500);
assert(w.reads == 0);
}
{
RadioLibWrapper w;
w._floor_estimator.add(-30, 100);
w.resetAGC();
assert(w._noise_floor_valid && w._noise_floor_centi_dbm == -10500);
assert(w._floor_estimator.count() == 0);
}
// Unknown/SPI-busy/sleep and packet ownership cannot trigger false recovery.
for (int skip : {0,1,2,3,4}) {
RadioLibWrapper w;
w.chip_mode = 0;
if (skip == 0) w.chip_mode = -1;
if (skip == 1) w.busy = true;
if (skip == 2) w._rx_ps_armed = true;
if (skip == 3) w.packet = true;
if (skip == 4) state |= STATE_INT_READY;
for (uint32_t t : {10000U,20000U,30000U}) w.checkReceiveMode(t);
assert(w.soft == 0 && w.hard == 0);
}
{
RadioLibWrapper w;
w.chip_mode = 0;
w.checkReceiveMode(10000); assert(w.soft == 0);
w.checkReceiveMode(20000); assert(w.soft == 1);
w.checkReceiveMode(30000); assert(w.hard == 1);
w.chip_mode = 1; w.checkReceiveMode(40000);
w.chip_mode = 0; w.checkReceiveMode(50000);
assert(w.soft == 1 && w.hard == 1);
}
{
RadioLibWrapper w;
w._rx_mode_checked_at = 0xFFFFF000U;
w.checkReceiveMode(0x10); assert(w._rx_mode_checked_at == 0xFFFFF000U);
w.checkReceiveMode(0x2000); assert(w._rx_mode_checked_at == 0x2000);
}
}
'''
class RadioReceiveContractTest(unittest.TestCase):
def test_production_transitions(self):
source = (ROOT / 'src/helpers/radiolib/RadioLibWrappers.cpp').read_text()
names = [('int16_t','performChannelScanWithTimeout'), ('bool','isPacketPendingOrReceiving'),
('bool','isChannelActive'), ('void','startRecv'), ('void','checkReceiveMode'),
('void','loop'), ('void','requestRestartRecv'), ('void','noiseFloorCalibCheck'),
('void','endNoiseFloorCalib'), ('void','requestNoiseFloorRefresh'),
('void','recalibrateNoiseFloor'), ('void','resetAGC')]
methods = '\n'.join(method(source, f'{kind} RadioLibWrapper::{name}(') for kind,name in names)
with tempfile.TemporaryDirectory(prefix='meshcore-radio-transitions-') as tmp:
cpp = Path(tmp) / 'test.cpp'
binary = Path(tmp) / 'test'
cpp.write_text(HARNESS.replace('@METHODS@', methods))
result = subprocess.run([os.environ.get('CXX','c++'), '-std=c++17', '-O1',
'-Wall', '-Wextra', '-I', str(ROOT / 'src'), str(cpp), '-o', str(binary)],
capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stderr)
result = subprocess.run([str(binary)], capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stderr)
if __name__ == '__main__':
unittest.main()
+125 -285
View File
@@ -1,309 +1,149 @@
#include <gtest/gtest.h>
#include <cmath>
#include <helpers/radiolib/RXPowerSaving.h>
#include <helpers/CLICommandUtils.h>
TEST(RxPowerSaving, BalancedNormalProfileKeepsDerivedDutyCycle) {
uint32_t rx_us = 0;
uint32_t sleep_us = 0;
ASSERT_TRUE(calcRxPowerSavingLevel(5, 7, 62.5f, 16, &rx_us, &sleep_us));
EXPECT_EQ(20936U, rx_us);
EXPECT_EQ(13425U, sleep_us);
EXPECT_FALSE(rxPowerSavingUsesContinuousFallback(rx_us, sleep_us));
TEST(RxPowerSaving, WirePreamblesStayCompatibleRegardlessOfLocalPowerSaving) {
EXPECT_EQ(32U, rxPowerSavingPreambleForParams(7, 500));
EXPECT_EQ(32U, rxPowerSavingPreambleForParams(6, 250));
EXPECT_EQ(32U, rxPowerSavingPreambleForParams(5, 125));
EXPECT_EQ(64U, rxPowerSavingPreambleForParams(6, 500));
EXPECT_EQ(64U, rxPowerSavingPreambleForParams(5, 250));
EXPECT_EQ(128U, rxPowerSavingPreambleForParams(5, 500));
EXPECT_EQ(16U, rxPowerSavingPreambleForParams(9, 500));
}
TEST(RxPowerSaving, Sf5Bw500UsesPreamble128) {
uint32_t rx_us = 0;
uint32_t sleep_us = 0;
uint8_t effective_level = 0;
uint8_t effective_preamble = 0;
ASSERT_TRUE(recalcRxPowerSavingFromLevel(5, 5, 500.0f, 16,
&rx_us, &sleep_us,
&effective_level,
&effective_preamble));
EXPECT_EQ(5U, effective_level);
EXPECT_EQ(128U, effective_preamble);
EXPECT_FALSE(rxPowerSavingUsesContinuousFallback(rx_us, sleep_us));
TEST(RxPowerSaving, GuardedProfilesCoverActualWireHeaderAndPromisedCatch) {
for (float bw : {7.8f, 15.6f, 31.25f, 62.5f, 125.0f, 250.0f, 500.0f}) {
for (uint8_t sf = 5; sf <= 12; ++sf) {
for (uint32_t transition : {1000U, 2600U, 6000U}) {
for (uint8_t requested = 1; requested <= 8; ++requested) {
for (uint8_t assumption : {16, 32, 64, 128}) {
SCOPED_TRACE(::testing::Message() << "sf=" << int(sf) << " bw=" << bw
<< " level=" << int(requested) << " preamble=" << int(assumption)
<< " transition=" << transition);
uint32_t rx, sleep;
uint8_t level, preamble;
ASSERT_TRUE(calcRxPowerSavingLevelAtOrAbove(requested, sf, bw, assumption,
transition, &rx, &sleep, &level, &preamble));
if (rxPowerSavingUsesContinuousFallback(rx, sleep)) {
EXPECT_EQ(0, level);
EXPECT_EQ(0, preamble);
continue;
}
EXPECT_GE(level, requested);
EXPECT_LE(level, RX_POWERSAVING_MAX_LEVEL);
EXPECT_LE(preamble, rxPowerSavingPreambleForParams(sf, bw));
EXPECT_GE(sleep, transition + RX_POWERSAVING_MIN_SLEEP_MARGIN_US);
EXPECT_TRUE(canStartRxPowerSavingDutyCycle(rx, sleep, transition));
const double symbol = 1000.0 * (1U << sf) / bw;
EXPECT_GE(preamble - sleep / symbol,
rxPowerSavingLevelCatch(level, preamble));
const double actual_rx = (rx * 8U / 125U) * 15.625;
const double actual_sleep = ((sleep - transition) * 8U / 125U) * 15.625;
const double required = (rxPowerSavingPreambleForParams(sf, bw)
+ (sf <= 6 ? 6.25 : 4.25) + 8.0 + 1.0) * symbol;
EXPECT_GE(2 * actual_rx + actual_sleep + 0.01, required);
}
}
}
}
}
}
TEST(RxPowerSaving, ReturningToSlowerProfileRestoresSmallerPreambleTiming) {
uint32_t rx_us = 0;
uint32_t sleep_us = 0;
uint8_t effective_level = 0;
uint8_t effective_preamble = 0;
ASSERT_TRUE(recalcRxPowerSavingFromLevel(5, 5, 500.0f, 16,
&rx_us, &sleep_us,
&effective_level,
&effective_preamble));
ASSERT_EQ(128U, effective_preamble);
ASSERT_TRUE(recalcRxPowerSavingFromLevel(5, 9, 500.0f, 16,
&rx_us, &sleep_us,
&effective_level,
&effective_preamble));
EXPECT_EQ(10468U, rx_us);
EXPECT_EQ(6712U, sleep_us);
EXPECT_EQ(5U, effective_level);
EXPECT_EQ(16U, effective_preamble);
EXPECT_FALSE(rxPowerSavingUsesContinuousFallback(rx_us, sleep_us));
TEST(RxPowerSaving, AutomaticAdjustmentNeverSelectsExperimentalLevels) {
uint32_t rx, sleep;
uint8_t level, preamble;
// The previous 6 ms TCXO budget cannot fit a guarded P32 at this tuple.
ASSERT_TRUE(calcRxPowerSavingLevelAtOrAbove(1, 7, 500, 16, 6000,
&rx, &sleep, &level, &preamble));
EXPECT_TRUE(rxPowerSavingUsesContinuousFallback(rx, sleep));
ASSERT_TRUE(calcRxPowerSavingLevelAtOrAbove(1, 7, 500, 16, 2600,
&rx, &sleep, &level, &preamble));
EXPECT_FALSE(rxPowerSavingUsesContinuousFallback(rx, sleep));
EXPECT_LE(level, 8);
EXPECT_EQ(32, preamble);
}
TEST(RxPowerSaving, TcxoThresholdSeparatesFastestUsableProfiles) {
constexpr uint32_t sx1262_tcxo_transition_us = 6000;
uint32_t rx_us = 0;
uint32_t sleep_us = 0;
ASSERT_TRUE(calcRxPowerSavingLevel(6, 7, 500.0f, 32,
&rx_us, &sleep_us));
EXPECT_FALSE(canStartRxPowerSavingDutyCycle(
rx_us, sleep_us, sx1262_tcxo_transition_us));
ASSERT_TRUE(calcRxPowerSavingLevel(7, 7, 500.0f, 32,
&rx_us, &sleep_us));
EXPECT_TRUE(canStartRxPowerSavingDutyCycle(
rx_us, sleep_us, sx1262_tcxo_transition_us));
TEST(RxPowerSaving, FastTuplesRetainLongPreambleSupport) {
uint32_t rx, sleep;
uint8_t level, preamble;
for (uint8_t sf : {5, 6}) {
ASSERT_TRUE(calcRxPowerSavingLevelAtOrAbove(8, sf, 500, 16, 6000,
&rx, &sleep, &level, &preamble));
EXPECT_EQ(8, level);
EXPECT_EQ(sf == 5 ? 128 : 64, preamble);
EXPECT_FALSE(rxPowerSavingUsesContinuousFallback(rx, sleep));
}
}
TEST(RxPowerSaving, WirePreambleUses64OnlyWhen32CannotEnableRxps) {
EXPECT_EQ(32U, rxPowerSavingPreambleForParams(7, 500.0f));
EXPECT_EQ(32U, rxPowerSavingPreambleForParams(6, 250.0f));
EXPECT_EQ(32U, rxPowerSavingPreambleForParams(5, 125.0f));
EXPECT_EQ(32U, rxPowerSavingPreambleForParams(5, 62.5f));
EXPECT_EQ(64U, rxPowerSavingPreambleForParams(5, 250.0f));
EXPECT_EQ(64U, rxPowerSavingPreambleForParams(6, 500.0f));
EXPECT_EQ(128U, rxPowerSavingPreambleForParams(5, 500.0f));
EXPECT_EQ(16U, rxPowerSavingPreambleForParams(9, 500.0f));
TEST(RxPowerSaving, NamedProfilesAndExplicitExperimentalModes) {
EXPECT_EQ(3, RX_POWERSAVING_CONSERVATIVE_LEVEL);
EXPECT_EQ(6, RX_POWERSAVING_BALANCED_LEVEL);
EXPECT_EQ(8, RX_POWERSAVING_MAX_LEVEL);
uint32_t rx9, sleep9, rx10, sleep10;
ASSERT_TRUE(calcRxPowerSavingLevel(9, 8, 62.5f, 32, &rx9, &sleep9));
ASSERT_TRUE(calcRxPowerSavingLevel(10, 8, 62.5f, 32, &rx10, &sleep10));
EXPECT_LT(rx10, rx9);
EXPECT_GT(sleep10, sleep9);
EXPECT_FALSE(isRxPowerSavingUnguardedLevel(8));
EXPECT_TRUE(isRxPowerSavingUnguardedLevel(9));
}
TEST(RxPowerSaving, RequestedLevelIsRaisedOnlyToRequiredMinimum) {
constexpr uint32_t sx1262_tcxo_transition_us = 6000;
uint32_t rx_us = 0;
uint32_t sleep_us = 0;
uint8_t effective_level = 0;
uint8_t effective_preamble = 0;
ASSERT_TRUE(calcRxPowerSavingLevelAtOrAbove(
1, 7, 500.0f, 16, sx1262_tcxo_transition_us,
&rx_us, &sleep_us, &effective_level, &effective_preamble));
EXPECT_EQ(7U, effective_level);
EXPECT_EQ(32U, effective_preamble);
EXPECT_TRUE(canStartRxPowerSavingDutyCycle(
rx_us, sleep_us, sx1262_tcxo_transition_us));
ASSERT_TRUE(calcRxPowerSavingLevelAtOrAbove(
8, 7, 500.0f, 16, sx1262_tcxo_transition_us,
&rx_us, &sleep_us, &effective_level, &effective_preamble));
EXPECT_EQ(8U, effective_level);
EXPECT_EQ(32U, effective_preamble);
EXPECT_TRUE(canStartRxPowerSavingDutyCycle(
rx_us, sleep_us, sx1262_tcxo_transition_us));
TEST(RxPowerSaving, BothFamiliesShareGuardedGeometry) {
for (uint8_t level = 1; level <= 8; ++level) {
uint32_t sx_rx, sx_sleep, lr_rx, lr_sleep;
ASSERT_TRUE(calcRxPowerSavingLevel(level, 8, 62.5f, 32, &sx_rx, &sx_sleep, 6, 2600));
ASSERT_TRUE(calcRxPowerSavingLevel(level, 8, 62.5f, 32, &lr_rx, &lr_sleep, 8, 2600));
EXPECT_EQ(sx_rx, lr_rx);
EXPECT_EQ(sx_sleep, lr_sleep);
}
}
TEST(RxPowerSaving, Sf5Bw500UsesPreamble128AtEffectiveLevel8) {
constexpr uint32_t sx1262_tcxo_transition_us = 6000;
uint32_t rx_us = 0;
uint32_t sleep_us = 0;
uint8_t effective_level = 99;
uint8_t effective_preamble = 99;
ASSERT_TRUE(calcRxPowerSavingLevelAtOrAbove(
1, 5, 500.0f, 16, sx1262_tcxo_transition_us,
&rx_us, &sleep_us, &effective_level, &effective_preamble));
EXPECT_EQ(8U, effective_level);
EXPECT_EQ(128U, effective_preamble);
EXPECT_EQ(626U, rx_us);
EXPECT_EQ(6398U, sleep_us);
EXPECT_TRUE(canStartRxPowerSavingDutyCycle(
rx_us, sleep_us, sx1262_tcxo_transition_us));
EXPECT_FALSE(rxPowerSavingUsesContinuousFallback(rx_us, sleep_us));
TEST(RxPowerSaving, ExperimentalProfilesAvoidKnownBadSx126xTicks) {
for (uint32_t tick : {320U, 640U}) {
EXPECT_EQ(tick + 1, avoidBadRxPowerSavingTick(rxPowerSavingTickToUs(tick)) * 8U / 125U);
}
}
TEST(RxPowerSaving, Sf5Bw250NeedsLongerTransmittedPreambleOnTcxoRadio) {
constexpr uint32_t sx1262_tcxo_transition_us = 6000;
uint32_t rx_us = 0;
uint32_t sleep_us = 0;
uint8_t effective_level = 99;
uint8_t effective_preamble = 99;
// Even the maximum level only provides a 3.616 ms sleep window. RadioLib
// must reserve 6 ms for the SX1262 TCXO and sleep/wake transitions.
ASSERT_TRUE(calcRxPowerSavingLevel(10, 5, 250.0f, 32,
&rx_us, &sleep_us));
EXPECT_EQ(1024U, rx_us);
EXPECT_EQ(3616U, sleep_us);
EXPECT_FALSE(canStartRxPowerSavingDutyCycle(
rx_us, sleep_us, sx1262_tcxo_transition_us));
ASSERT_TRUE(calcRxPowerSavingLevelAtOrAbove(
8, 5, 250.0f, 32, sx1262_tcxo_transition_us,
&rx_us, &sleep_us, &effective_level, &effective_preamble));
EXPECT_EQ(8U, effective_level);
EXPECT_EQ(64U, effective_preamble);
EXPECT_EQ(1252U, rx_us);
EXPECT_EQ(6424U, sleep_us);
EXPECT_FALSE(rxPowerSavingUsesContinuousFallback(rx_us, sleep_us));
}
TEST(RxPowerSaving, Sf5Bw250UsesPreamble64AtEffectiveLevel8) {
constexpr uint32_t sx1262_tcxo_transition_us = 6000;
uint32_t rx_us = 0;
uint32_t sleep_us = 0;
uint8_t effective_level = 0;
uint8_t effective_preamble = 0;
ASSERT_TRUE(calcRxPowerSavingLevelAtOrAbove(
1, 5, 250.0f, 64, sx1262_tcxo_transition_us,
&rx_us, &sleep_us, &effective_level, &effective_preamble));
EXPECT_EQ(8U, effective_level);
EXPECT_EQ(64U, effective_preamble);
EXPECT_EQ(1252U, rx_us);
EXPECT_EQ(6424U, sleep_us);
EXPECT_TRUE(canStartRxPowerSavingDutyCycle(
rx_us, sleep_us, sx1262_tcxo_transition_us));
}
TEST(RxPowerSaving, Sf5Bw250SelectorUsesPreamble64Automatically) {
constexpr uint32_t sx1262_tcxo_transition_us = 6000;
uint32_t rx_us = 0;
uint32_t sleep_us = 0;
uint8_t effective_level = 0;
uint8_t effective_preamble = 0;
ASSERT_TRUE(calcRxPowerSavingLevelAtOrAbove(
1, 5, 250.0f, 16, sx1262_tcxo_transition_us,
&rx_us, &sleep_us, &effective_level, &effective_preamble));
EXPECT_EQ(8U, effective_level);
EXPECT_EQ(64U, effective_preamble);
EXPECT_EQ(1252U, rx_us);
EXPECT_EQ(6424U, sleep_us);
}
TEST(RxPowerSaving, Sf5Bw125KeepsPreamble32) {
constexpr uint32_t sx1262_tcxo_transition_us = 6000;
uint32_t rx_us = 0;
uint32_t sleep_us = 0;
uint8_t effective_level = 0;
uint8_t effective_preamble = 0;
ASSERT_TRUE(calcRxPowerSavingLevelAtOrAbove(
1, 5, 125.0f, 16, sx1262_tcxo_transition_us,
&rx_us, &sleep_us, &effective_level, &effective_preamble));
EXPECT_EQ(7U, effective_level);
EXPECT_EQ(32U, effective_preamble);
EXPECT_EQ(2731U, rx_us);
EXPECT_EQ(6101U, sleep_us);
EXPECT_TRUE(canStartRxPowerSavingDutyCycle(
rx_us, sleep_us, sx1262_tcxo_transition_us));
}
TEST(RxPowerSaving, EquivalentFastProfilesSupportExplicitPreamble32Level7) {
constexpr uint32_t sx1262_tcxo_transition_us = 6000;
uint32_t rx_us = 0;
uint32_t sleep_us = 0;
uint8_t effective_level = 0;
uint8_t effective_preamble = 0;
ASSERT_TRUE(calcRxPowerSavingLevelAtOrAbove(
7, 7, 500.0f, 32, sx1262_tcxo_transition_us,
&rx_us, &sleep_us, &effective_level, &effective_preamble));
EXPECT_EQ(7U, effective_level);
EXPECT_EQ(32U, effective_preamble);
EXPECT_EQ(2731U, rx_us);
EXPECT_EQ(6101U, sleep_us);
ASSERT_TRUE(calcRxPowerSavingLevelAtOrAbove(
7, 6, 250.0f, 32, sx1262_tcxo_transition_us,
&rx_us, &sleep_us, &effective_level, &effective_preamble));
EXPECT_EQ(7U, effective_level);
EXPECT_EQ(32U, effective_preamble);
ASSERT_TRUE(calcRxPowerSavingLevelAtOrAbove(
7, 5, 125.0f, 32, sx1262_tcxo_transition_us,
&rx_us, &sleep_us, &effective_level, &effective_preamble));
EXPECT_EQ(7U, effective_level);
EXPECT_EQ(32U, effective_preamble);
}
TEST(RxPowerSaving, Sf6Bw250KeepsPreamble32) {
constexpr uint32_t sx1262_tcxo_transition_us = 6000;
uint32_t rx_us = 0;
uint32_t sleep_us = 0;
uint8_t effective_level = 0;
uint8_t effective_preamble = 0;
ASSERT_TRUE(calcRxPowerSavingLevelAtOrAbove(
1, 6, 250.0f, 16, sx1262_tcxo_transition_us,
&rx_us, &sleep_us, &effective_level, &effective_preamble));
EXPECT_EQ(7U, effective_level);
EXPECT_EQ(32U, effective_preamble);
EXPECT_EQ(2731U, rx_us);
EXPECT_EQ(6101U, sleep_us);
}
TEST(RxPowerSaving, Sf6Bw500UsesPreamble64WhenRequired) {
constexpr uint32_t sx1262_tcxo_transition_us = 6000;
uint32_t rx_us = 0;
uint32_t sleep_us = 0;
uint8_t effective_level = 0;
uint8_t effective_preamble = 0;
ASSERT_TRUE(calcRxPowerSavingLevelAtOrAbove(
1, 6, 500.0f, 16, sx1262_tcxo_transition_us,
&rx_us, &sleep_us, &effective_level, &effective_preamble));
EXPECT_EQ(8U, effective_level);
EXPECT_EQ(64U, effective_preamble);
EXPECT_EQ(1252U, rx_us);
EXPECT_EQ(6424U, sleep_us);
}
TEST(RxPowerSaving, TimingAssumptionCannotExceedWirePreamble) {
constexpr uint32_t sx1262_tcxo_transition_us = 6000;
uint32_t rx_us = 0;
uint32_t sleep_us = 0;
uint8_t effective_level = 0;
uint8_t effective_preamble = 0;
ASSERT_TRUE(calcRxPowerSavingLevelAtOrAbove(
1, 7, 500.0f, 64, sx1262_tcxo_transition_us,
&rx_us, &sleep_us, &effective_level, &effective_preamble));
EXPECT_EQ(7U, effective_level);
EXPECT_EQ(32U, effective_preamble);
EXPECT_EQ(2731U, rx_us);
EXPECT_EQ(6101U, sleep_us);
}
TEST(RxPowerSaving, Sf5Bw62Point5UsesPreamble16AtEffectiveLevel10) {
constexpr uint32_t sx1262_tcxo_transition_us = 6000;
uint32_t rx_us = 0;
uint32_t sleep_us = 0;
uint8_t effective_level = 0;
uint8_t effective_preamble = 0;
ASSERT_TRUE(calcRxPowerSavingLevelAtOrAbove(
1, 5, 62.5f, 16, sx1262_tcxo_transition_us,
&rx_us, &sleep_us, &effective_level, &effective_preamble));
EXPECT_EQ(10U, effective_level);
EXPECT_EQ(16U, effective_preamble);
EXPECT_EQ(4096U, rx_us);
EXPECT_EQ(6272U, sleep_us);
TEST(RxPowerSaving, RetuningPreservesManualTimingsAndRestoresRequestedLevel) {
uint32_t rx = 12345, sleep = 67890;
EXPECT_FALSE(recalcRxPowerSavingFromLevel(0, 8, 62.5f, 16, &rx, &sleep));
EXPECT_EQ(12345U, rx);
EXPECT_EQ(67890U, sleep);
uint8_t level, preamble;
ASSERT_TRUE(recalcRxPowerSavingFromLevel(3, 5, 500, 16, &rx, &sleep, &level, &preamble));
ASSERT_TRUE(recalcRxPowerSavingFromLevel(3, 9, 62.5f, 16, &rx, &sleep, &level, &preamble));
EXPECT_EQ(3, level);
EXPECT_EQ(16, preamble);
}
TEST(RxPowerSaving, RejectsInvalidInputs) {
uint32_t rx_us = 123;
uint32_t sleep_us = 456;
uint32_t rx, sleep;
EXPECT_FALSE(calcRxPowerSavingLevel(0, 8, 62.5f, 16, &rx, &sleep));
EXPECT_FALSE(calcRxPowerSavingLevel(11, 8, 62.5f, 16, &rx, &sleep));
EXPECT_FALSE(calcRxPowerSavingLevel(5, 4, 62.5f, 16, &rx, &sleep));
EXPECT_FALSE(calcRxPowerSavingLevel(5, 8, 0, 16, &rx, &sleep));
EXPECT_FALSE(calcRxPowerSavingLevel(5, 8, NAN, 16, &rx, &sleep));
EXPECT_FALSE(calcRxPowerSavingLevel(5, 8, INFINITY, 16, &rx, &sleep));
EXPECT_FALSE(calcRxPowerSavingLevel(5, 8, 62.5f, 24, &rx, &sleep));
EXPECT_FALSE(calcRxPowerSavingLevel(5, 8, 62.5f, 16, nullptr, &sleep));
}
EXPECT_FALSE(calcRxPowerSavingLevel(0, 7, 500.0f, 32,
&rx_us, &sleep_us));
EXPECT_FALSE(calcRxPowerSavingLevel(5, 4, 500.0f, 32,
&rx_us, &sleep_us));
EXPECT_FALSE(calcRxPowerSavingLevel(5, 7, 0.0f, 32,
&rx_us, &sleep_us));
EXPECT_FALSE(calcRxPowerSavingLevel(5, 7, 500.0f, 24,
&rx_us, &sleep_us));
TEST(RxPowerSavingCLI, ParsesNewNamesAndRejectsTrailingJunk) {
mesh::cli::RxPowerSavingArguments args = {};
for (const char* name : {"max", "overdrive", "riskyWorkingMax"}) {
ASSERT_TRUE(mesh::cli::parseRxPowerSavingArgumentsStrict(name, args));
EXPECT_EQ(mesh::cli::rxPowerSavingNamedLevel(name), args.level);
EXPECT_EQ(16U, args.preamble);
}
ASSERT_TRUE(mesh::cli::parseRxPowerSavingArgumentsStrict("max preamble 32", args));
EXPECT_EQ(8U, args.level);
EXPECT_EQ(32U, args.preamble);
for (const char* text : {"maxx", "max extra", "max preamble 32 extra", "riskyworkingmax",
"level 4294967296", "overdrive preamble nope"}) {
EXPECT_FALSE(mesh::cli::parseRxPowerSavingArgumentsStrict(text, args)) << text;
}
}
int main(int argc, char** argv) {
+114
View File
@@ -0,0 +1,114 @@
#!/usr/bin/env python3
"""Exercise the pinned RadioLib SPI transport with a fake Semtech status response."""
from pathlib import Path
import os
import re
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
HARNESS = r'''
#include <cassert>
#include <cstring>
#include <initializer_list>
#include <RadioLib.h>
#include <helpers/radiolib/SX126xReceiveMode.h>
struct Hal : RadioLibHal {
Hal() : RadioLibHal(0,1,0,1,1,0) {}
bool busy = false;
uint8_t status = 0x54;
unsigned transfers = 0;
uint32_t time = 0;
void pinMode(uint32_t,uint32_t) override {}
void digitalWrite(uint32_t,uint32_t) override {}
uint32_t digitalRead(uint32_t) override { return busy; }
void attachInterrupt(uint32_t,void(*)(),uint32_t) override {}
void detachInterrupt(uint32_t) override {}
void delay(RadioLibTime_t ms) override { time += ms; }
void delayMicroseconds(RadioLibTime_t) override {}
RadioLibTime_t millis() override { return time; }
RadioLibTime_t micros() override { return time * 1000; }
long pulseIn(uint32_t,uint32_t,RadioLibTime_t) override { return 0; }
void spiBegin() override {}
void spiBeginTransaction() override {}
void spiTransfer(uint8_t* out, size_t size, uint8_t* in) override {
assert(size == 2 && out[0] == 0xC0);
memset(in, 0, size);
in[1] = status; // GetStatus has one response byte, no payload after it.
++transfers;
}
void spiEndTransaction() override {}
void spiEnd() override {}
};
struct Radio {
Module* mod;
Module* getMod() { return mod; }
@LEGACY@
};
int main() {
Hal hal;
Module module(&hal,1,2,3,4);
module.spiConfig.widths[RADIOLIB_MODULE_SPI_WIDTH_CMD] = Module::BITS_8;
module.spiConfig.widths[RADIOLIB_MODULE_SPI_WIDTH_STATUS] = Module::BITS_8;
module.spiConfig.statusPos = 1;
module.spiConfig.parseStatusCb = nullptr;
module.spiConfig.checkStatusCb = nullptr;
Radio radio{&module};
assert(radio.getStatus() == 0); // reproduces the PR's false non-RX observation
assert(sx126xReceiveMode(&radio) == 1);
assert(module.spiConfig.widths[RADIOLIB_MODULE_SPI_WIDTH_STATUS] == 8);
for (uint8_t mode : {0x24, 0x34, 0x44, 0x64}) {
hal.status = mode;
assert(sx126xReceiveMode(&radio) == 0);
}
for (uint8_t invalid : {0x00, 0xFF, 0x14, 0x74}) {
hal.status = invalid;
assert(sx126xReceiveMode(&radio) == -1);
assert(module.spiConfig.widths[RADIOLIB_MODULE_SPI_WIDTH_STATUS] == 8);
}
const unsigned before = hal.transfers;
hal.busy = true;
assert(sx126xReceiveMode(&radio) == -1);
assert(hal.transfers == before); // no SPI while the chip is asleep/busy
}
'''
class ReceiveModeTest(unittest.TestCase):
def test_real_spi_transport_and_legacy_status(self):
candidates = sorted((ROOT / '.pio/libdeps').glob('*/RadioLib/src/Module.cpp'))
pin = re.search(r'jgromes/RadioLib.git#([0-9a-f]{40})',
(ROOT / 'platformio.ini').read_text()).group(1)
lib = None
for candidate in candidates:
installed = subprocess.run(
['git', '-C', str(candidate.parent.parent), 'rev-parse', 'HEAD'],
capture_output=True, text=True)
if installed.returncode == 0 and installed.stdout.strip() == pin:
lib = candidate.parent
break
if lib is None:
self.skipTest('Build a firmware environment to install the pinned RadioLib dependency')
commands = (lib / 'modules/SX126x/SX126x_commands.cpp').read_text()
start = commands.index('uint8_t SX126x::getStatus()')
end = commands.index('\n}', start) + 2
legacy = commands[start:end].replace('SX126x::', '')
with tempfile.TemporaryDirectory(prefix='meshcore-status-') as tmp:
source = Path(tmp) / 'test.cpp'
binary = Path(tmp) / 'test'
source.write_text(HARNESS.replace('@LEGACY@', legacy))
command = [os.environ.get('CXX', 'c++'), '-std=c++17', '-O1',
'-DRADIOLIB_GODMODE=1', '-DRADIOLIB_STATIC_ONLY=1',
'-ffunction-sections', '-fdata-sections', '-Wl,--gc-sections',
'-I', str(lib), '-I', str(ROOT / 'src'), str(source),
str(lib / 'Module.cpp'), str(lib / 'Hal.cpp'), '-o', str(binary)]
result = subprocess.run(command, capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stderr)
result = subprocess.run([str(binary)], capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stderr)
if __name__ == '__main__':
unittest.main()