Speed up SX1262 profile switching and verify radio lab behavior

Keep TCXO warm during owned dual-profile retunes, batch modulation setup, and enable guarded fast RX with buffered 8 MHz SPI on XIAO S3 WIO and Indicator LoRa. Preserve lifecycle invalidation, packet guards, rollback, and existing scheduling budgets.

Add reliable sequence-scoped USB lab transport, native regression coverage, bounded channel and preamble diagnostics, and byte-exact measurement records including failed experiments and qualification limits.
This commit is contained in:
mikecarper committed 2026-09-14 01:22:09 -07:00
1 parent 25eab1a581
commit bd30388436
90 files changed
+146200 -20

No files matched your search

+64
View File
@@ -0,0 +1,64 @@
"""HIL IRQ capture is bounded, observational and frozen before USB retrieval."""
from pathlib import Path
import unittest
import test_sx1262_batched_modulation as compiler
class ChannelTraceTests(unittest.TestCase):
compile_run = compiler.BatchedModulationTests.compile_run
def test_held_occupancy_survives_receive_restart(self):
source = (Path(__file__).resolve().parents[1] / "tools/hil/profile_switch_channels.h").read_text()
self.assertIn("visitAge=now-channelSweep.visitStartedUs", source)
self.assertIn("channelSweep.heldDwell.add(visitAge)", source)
self.assertIn("channelTrace.add(ChannelTrace::Hop,visitAge", source)
self.assertEqual(source.count("channelSweep.visitStartedUs=driver.receiveStartedUs();"), 2)
def test_selected_sf_reaches_initial_hops_tx_and_cache_check(self):
source = (Path(__file__).resolve().parents[1] / "tools/hil/profile_switch_channels.h").read_text()
self.assertIn("p.sf=sf", source)
for expected in ("sweepParams(0,preamble,sf)", "sweepParams(1,preamble,sf)",
"setLoRaModulationParams(125,sf,5)", "channelSweep.sf=sf;",
"chip.spreadingFactor!=channelSweep.sf"):
self.assertIn(expected, source)
self.assertEqual(source.count("sweepParams(next,channelSweep.preamble,channelSweep.sf)"), 2)
def test_passive_irq_decode_bounds_and_freeze(self):
source = (Path(__file__).resolve().parents[1] / "tools/hil/ProfileChannelTrace.h").read_text().replace("#pragma once", "")
harness = r'''
#include <cassert>
#include <cstdint>
#include <cstddef>
uint32_t clockUs=1000;
uint32_t micros() { return clockUs; }
@SOURCE@
int main() {
auto& t=channelTrace;
t.arm(5,0,3,40);assert(t.size==0);
t.enabled=true;t.arm(6,1,3,50);
assert(t.size==1 && t.events[0].a==3 && t.events[0].b==50);
uint8_t out[4]={0x12,0,0,0},in[4]={0,0,0,4};
clockUs+=20;t.observe(out,4,in);
assert(t.size==2 && t.events[1].irq==4 && t.events[1].us==20);
t.observe(out,4,in);assert(t.size==2); // unchanged observations deduplicate
uint8_t clear[3]={2,0,4};t.observe(clear,3,in);
assert(t.events[2].kind==ChannelTrace::Clear && t.irq==4);
in[3]=0;t.observe(out,4,in);assert(t.size==4 && t.irq==0);
t.active=false;t.observe(out,4,in);t.add(ChannelTrace::Hop);assert(t.size==4);
t.arm(7,2,0,0);
for(unsigned i=0;i<ChannelTrace::Capacity+10;++i) t.add(ChannelTrace::Hop,i);
assert(t.size==ChannelTrace::Capacity && t.overflow==11);
t.arm(8,0,0,0);assert(t.size==1 && !t.overflow && t.sequence==8);
t.active=false;
uint8_t rf[5]={0x86,0x38,0xe0,0,0};t.observe(rf,5,in);
assert(t.rfWord==0x38e00000);
uint8_t tx[4]={0x83,0,0,0};t.observe(tx,4,in);
assert(t.txCommandUs==clockUs && t.txWord==t.rfWord && t.size==1);
assert(out[0]==0x12 && clear[0]==2 && in[3]==0);
}
'''
self.compile_run(harness.replace("@SOURCE@", source))
if __name__ == "__main__":
unittest.main()
+153
View File
@@ -0,0 +1,153 @@
"""Check HIL-only optimization boundaries; not full radio lifecycle qualification."""
from pathlib import Path
import unittest
from test_radio_receive_contract import method
import test_sx1262_batched_modulation as batched_tests
ROOT = Path(__file__).resolve().parents[1]
class ProfileSwitchExperimentTests(unittest.TestCase):
compile_run = batched_tests.BatchedModulationTests.compile_run
def test_rx_omissions_are_scoped_and_commands_preserved(self):
source = (ROOT / "tools/hil/profile_switch_experiments.h").read_text()
source = source[source.index("class ExperimentalSX1262") :]
harness = r'''
#include <cassert>
#include <cstdint>
#include <cstddef>
#include <string>
#define RADIOLIB_ERR_NONE 0
#define RADIOLIB_ERR_WRONG_MODEM -4
#define RADIOLIB_SX126X_STANDBY_XOSC 1
#define RADIOLIB_SX126X_STANDBY_RC 0
#define RADIOLIB_SX126X_PACKET_TYPE_LORA 1
#define RADIOLIB_SX126X_RX_TIMEOUT_INF 0xffffff
#define RADIOLIB_RADIO_MODE_NONE 0
#define RADIOLIB_IRQ_RX_DEFAULT_FLAGS 1
#define RADIOLIB_IRQ_RX_DEFAULT_MASK 2
#define RADIOLIB_IRQ_PREAMBLE_DETECTED 3
#define RADIOLIB_ASSERT(rc) do { if ((rc)!=0) return (rc); } while(0)
struct Module { enum { MODE_RX=1 }; void setRfSwitchState(int m) { assert(m==MODE_RX); } };
struct SX1262 {
bool standbyXOSC=true;
size_t preambleLengthLoRa=16;
uint8_t crcTypeLoRa=1, implicitLen=255, headerType=0, invertIQEnabled=0;
uint32_t rxTimeout=0; int stagedMode=3;
std::string calls; char failAt=0; int modem=1; Module mod;
virtual ~SX1262()=default;
int call(char c) { calls+=c;return failAt==c ? -10:0; }
virtual int16_t standby() { return standby(1,true); }
int16_t standby(int mode,bool wake) { assert(mode==0 || mode==1);return call(wake?'S':'s'); }
virtual int16_t startReceive() { return call('X'); }
virtual int16_t setPreambleLength(size_t p) { preambleLengthLoRa=p;return call('P'); }
int getIrqMapped(int x) { return x; }
int setDioIrqParams(int flags,int mask) { assert(flags==9 && mask==2);return call('I'); }
int setBufferBaseAddress() { return call('B'); }
int clearIrqStatus() { return call('C'); }
int getPacketType() { call('Q');return modem; }
int setPacketParams(size_t p,int,int,int,int) { assert(p==preambleLengthLoRa);return call('K'); }
Module* getMod() { return &mod; }
int setRx(uint32_t t) { assert(t==0xffffff);return call('R'); }
};
struct CustomSX1262: SX1262 { int16_t startReceive() override { return call('F'); } };
@CLASS@
int main() {
// Outside an owned RX-to-RX window every mask uses the ordinary path.
for(unsigned mask=0;mask<256;++mask) {
ExperimentalSX1262 r;r.experiment=mask;
assert(r.startReceive()==0 && r.calls=="F");r.calls.clear();
r.beginHop(false);r.standby();r.calls.clear();
assert(r.startReceive()==0 && r.calls=="F");r.endHop();r.calls.clear();
r.beginHop(true); // no successful standby yet
assert(r.startReceive()==0 && r.calls=="F");r.endHop();r.calls.clear();
r.beginHop(true);r.standby();r.rxPrimed=false;r.calls.clear();
assert(r.startReceive()==0 && r.calls=="F");
}
// Exhaust every omission combination, after a valid normal RX setup.
for(unsigned mask=1;mask<256;++mask) {
ExperimentalSX1262 r;r.experiment=mask;r.rxPrimed=true;r.beginHop(true);
assert(r.standby()==0);r.calls.clear();
assert(r.setPreambleLength(91)==0);
assert(r.preambleLengthLoRa==91);
const bool deferred=mask & 32;
assert(r.calls==(deferred ? "":"P"));r.calls.clear();
assert(r.startReceive()==0);
std::string want;
if(!(mask&1)) want+=(mask&64)?'s':'S';
if(!(mask&2)) want+='I';
if(!(mask&4)) want+='B';
want+='C'; // clearing stale IRQs must never be optimized out
if(!(mask&16)) want+='Q';
if(!(mask&8) || deferred) want+='K';
want+='R'; // always issue RX and retain the underlying BUSY waits
assert(r.calls==want && r.stagedMode==0);
r.endHop();r.calls.clear();assert(r.startReceive()==0 && r.calls=="F");
}
// A command failure short-circuits; wrong modem never reaches SetRx.
for(char fail: std::string("SIBCKR")) {
ExperimentalSX1262 r;r.experiment=128;r.rxPrimed=true;r.beginHop(true);
r.haveStandby=true;r.failAt=fail;
assert(r.startReceive()==-10 && r.calls.back()==fail);
if(fail=='R') assert(!r.rxPrimed);
}
ExperimentalSX1262 r;r.experiment=128;r.rxPrimed=true;r.beginHop(true);r.haveStandby=true;r.modem=0;
assert(r.startReceive()==-4 && r.calls=="SIBCQ");
}
'''
# These cases deliberately select the old HIL omission masks, not
# the production state machine (tested separately).
harness = harness.replace("ExperimentalSX1262 r;", "ExperimentalSX1262 r;r.productionPath=false;")
self.compile_run(harness.replace("@CLASS@", source))
def test_bulk_hal_preserves_full_duplex_buffer(self):
source = (ROOT / "tools/hil/profile_switch.cpp").read_text()
operation = method(source, "void spiTransfer(").replace(" override", "")
harness = r'''
#include <cassert>
#include <cstdint>
#include <cstddef>
struct Spi {
unsigned bulk=0;
void transferBytes(uint8_t* out,uint8_t* in,size_t n) {
++bulk;for(size_t i=0;i<n;++i) in[i]=out[i]^0xa5;
}
};
struct ArduinoHal {
unsigned fallback=0;Spi device;Spi* spi=&device;
void spiTransfer(uint8_t* out,size_t n,uint8_t* in) {
++fallback;for(size_t i=0;i<n;++i) in[i]=out[i]^0xa5;
}
};
struct ESP32BufferedRadioHal: ArduinoHal {
void spiTransfer(uint8_t* out,size_t n,uint8_t* in) {
if(n) spi->transferBytes(out,in,n);
}
};
using BenchHalBase=ESP32BufferedRadioHal;
struct {
unsigned calls=0;
void observe(const uint8_t* out,size_t n,const uint8_t* in) {
++calls;
for(size_t i=0;i<n;++i) assert(in[i]==(out[i]^0xa5));
}
} channelTrace;
struct Hal: BenchHalBase { bool bulkTransfer=false; @OP@ };
int main() {
for(size_t n=1;n<=260;++n) for(int bulk=0;bulk<2;++bulk) {
Hal h;h.bulkTransfer=bulk;uint8_t in[262]={},out[260];
for(size_t i=0;i<n;++i) out[i]=uint8_t(i);
h.spiTransfer(out,n,in+1);
assert(!in[0] && !in[n+1]);
for(size_t i=0;i<n;++i) assert(in[i+1]==(out[i]^0xa5));
assert(h.fallback==unsigned(!bulk) && h.device.bulk==unsigned(bulk));
}
assert(channelTrace.calls==520);
}
'''
self.compile_run(harness.replace("@OP@", operation))
if __name__ == "__main__":
unittest.main()
+46
View File
@@ -0,0 +1,46 @@
"""Check firmware-side USB results are immutable, bounded and sequence-scoped."""
from pathlib import Path
import unittest
import test_sx1262_batched_modulation as compiler
ROOT = Path(__file__).resolve().parents[1]
class UsbResultCacheTests(unittest.TestCase):
compile_run = compiler.BatchedModulationTests.compile_run
def test_cache_replay_never_executes_an_operation(self):
source = (ROOT / "tools/hil/ProfileSwitchUsb.h").read_text().replace("#pragma once", "")
harness = r'''
#include <cassert>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <string>
struct {
std::string output;unsigned flushes=0;
void print(const char* text) { output+=text; }
void println(const char* text) { output+=text;output+='\n'; }
void flush() { ++flushes; }
} Serial;
@SOURCE@
int main() {
recordBenchResult(lastTxResult,42,"{\"sent\":%u,\"rc\":0}\n",42u);
const auto expected=Serial.output;assert(lastTxResult.sequence==42);
Serial.output.clear();replayBenchResult("sent",42);assert(Serial.output==expected);
Serial.output.clear();replayBenchResult("sent",43);
assert(Serial.output.find("unavailable")!=std::string::npos);
Serial.output.clear();replayBenchResult("listening",42);
assert(Serial.output.find("unavailable")!=std::string::npos);
Serial.output.clear();recordBenchResult(lastTxResult,43,"%03000d",1);
assert(lastTxResult.sequence==0 && Serial.output.find("overflow")!=std::string::npos);
Serial.output.clear();replayBenchResult("sent",42);
assert(Serial.output.find("unavailable")!=std::string::npos);
assert(Serial.flushes==2);
}
'''
self.compile_run(harness.replace("@SOURCE@", source))
if __name__ == "__main__":
unittest.main()
+111 -3
View File
@@ -9,6 +9,7 @@ from test_radio_receive_contract import method
ROOT = Path(__file__).resolve().parents[1]
HARNESS = r'''
#include <cassert>
#include <initializer_list>
#include <RadioProfiles.h>
#include <helpers/radiolib/RXPowerSaving.h>
#define RADIOLIB_ERR_NONE 0
@@ -22,13 +23,15 @@ static uint64_t elapsed_us;
static uint8_t state;
uint32_t micros() { return (uint32_t)elapsed_us; }
uint32_t millis() { return (uint32_t)(elapsed_us / 1000); }
struct Chip { int standby() { return 0; } };
struct Chip { bool standbyXOSC=false; int standby() { return 0; } };
using CustomSX1262 = Chip;
struct RadioLibWrapper {
Chip chip; Chip* _radio = &chip;
mesh::RadioProfiles _profiles;
bool _params_valid=true, packet=false, busy=false, fail=false;
bool _rx_ps_enabled=true, _rx_ps_armed=true, _rx_ps_continuous_fallback=false;
bool _profile_saved_rxps=false, _profile_rxps_suspended=false;
bool _profile_standby_held=false, _saved_standby_xosc=false;
bool _nf_calib_active=false, _noise_floor_valid=true, _profile_refresh_required=false;
uint32_t _rx_ps_rx_us=50000, _rx_ps_sleep_us=50000;
uint8_t _active_profile=0, _cur_sf=7, _cur_cr=5;
@@ -36,7 +39,7 @@ struct RadioLibWrapper {
uint32_t _profile_scan_generation[2]={};
uint16_t _physical_preamble=32;
float _cur_freq=909.5, _cur_bw=62.5;
unsigned applies=0;
unsigned applies=0, failRxStarts=0;
RadioLibWrapper() {
state=STATE_RX; elapsed_us=100000;
auto& p=_profiles.primary;
@@ -44,10 +47,17 @@ struct RadioLibWrapper {
_profile_visit_us=micros();
}
bool isChipBusy() { return busy; }
bool isInRecvMode() const { return (state & ~STATE_INT_READY) == STATE_RX; }
void beginProfileRetune(bool) {}
void endProfileRetune(bool) {}
bool isReceivingPacket() { return packet; }
bool isPacketPendingOrReceiving() { return packet || (state & STATE_INT_READY); }
bool supportsRxPowerSaving() { return true; }
void startRecv() { state=STATE_RX; _profile_visit_us=micros(); _rx_ps_armed=_rx_ps_enabled; }
void startRecv() {
if (failRxStarts) { --failRxStarts; state=STATE_IDLE; return; }
if (_profile_rxps_suspended) assert(chip.standbyXOSC && !_rx_ps_enabled);
state=STATE_RX; _profile_visit_us=micros(); _rx_ps_armed=_rx_ps_enabled;
}
void stopReceiveDutyCycle() { _rx_ps_armed=false; }
bool applyParams(float f,float,uint8_t,uint8_t) { ++applies; elapsed_us+=1200; return !fail || f==909.5f; }
void cacheParams(float f,float b,uint8_t s,uint8_t c) { _cur_freq=f;_cur_bw=b;_cur_sf=s;_cur_cr=c; }
@@ -57,6 +67,7 @@ struct RadioLibWrapper {
uint16_t profilePreamble(uint8_t n) const { return _profiles.preamble(n,32); }
uint8_t beginReconfigure();
void endReconfigure(bool);
void setProfileStandbyWarm(bool);
void serviceProfileScan();
mesh::RadioParamApplyResult tuneProfile(uint8_t);
mesh::RadioParamApplyResult prepareTransmitProfile(uint8_t);
@@ -72,9 +83,26 @@ struct RadioLibWrapper {
@METHODS@
int main() {
using Result=mesh::RadioParamApplyResult;
{
// Applying the tuple is not success if RX resume failed. Roll back the
// profile and caches, and request recovery if rollback RX also fails.
for (unsigned failures: {1u,2u}) {
RadioLibWrapper w; w.enable(); w.failRxStarts=failures;
const auto switches=w._profiles.switches;
const auto generation=w._profile_generation;
assert(w.tuneProfile(1)==Result::FAILED);
assert(w._active_profile==0 && w._cur_freq==909.5f && w._cur_bw==62.5f);
assert(w._profile_generation==generation && w._profiles.switches==switches);
assert(w._profiles.switch_failures==1);
assert(w.isInRecvMode()==(failures==1));
assert(w._profile_refresh_required==(failures==2));
}
}
{
RadioLibWrapper w; w.enable();
assert(w._profile_rxps_suspended && !w._rx_ps_enabled && !w._rx_ps_armed);
assert(w.chip.standbyXOSC && w._profile_standby_held && !w._saved_standby_xosc);
w.setProfileStandbyWarm(true); // repeated requests must not overwrite the saved RC policy
elapsed_us+=w._profiles.listenUs(0)-1;w.serviceProfileScan();assert(w._active_profile==0);
elapsed_us++;w.serviceProfileScan();assert(w._active_profile==1);
elapsed_us+=w._profiles.listenUs(1)-1;w.serviceProfileScan();assert(w._active_profile==1);
@@ -85,9 +113,11 @@ int main() {
assert(w.prepareTransmitProfile(0)==Result::BUSY);
w._profiles.setSecondary({},false);w.serviceProfileScan();
assert(w._active_profile==1 && w._profile_generation==generation);
assert(w.chip.standbyXOSC); // cannot change oscillator policy during a packet
w.packet=false;w.serviceProfileScan();
assert(w._active_profile==0 && w._rx_ps_enabled && !w._profile_rxps_suspended);
assert(w._rx_ps_armed);
assert(!w.chip.standbyXOSC && !w._profile_standby_held);
w.serviceProfileScan(); assert(!w._profile_refresh_required);
}
{
@@ -104,6 +134,7 @@ int main() {
RadioLibWrapper w;w.enable();w.fail=true;
elapsed_us+=100000;w.serviceProfileScan();
assert(w._profiles.switch_failures==1 && w._active_profile==0);
assert(w.chip.standbyXOSC && w._profile_standby_held);
const auto applies=w.applies;
for (int i=0;i<10;++i) w.serviceProfileScan();
assert(w.applies==applies); // failed target is not hammered every loop
@@ -130,6 +161,28 @@ int main() {
assert(w._profiles.primary==temp && w._physical_preamble==64);
assert(w._profile_generation==w._profiles.generation[0]);
}
{
RadioLibWrapper w; w.chip.standbyXOSC=true; w._rx_ps_enabled=false; w._rx_ps_armed=false;
w.enable(); assert(w._saved_standby_xosc);
w._profiles.setSecondary({},false); w.serviceProfileScan();
assert(w.chip.standbyXOSC && !w._profile_standby_held && !w._rx_ps_enabled);
w.setProfileStandbyWarm(false); assert(w.chip.standbyXOSC);
}
for (int reason=0;reason<4;++reason) {
RadioLibWrapper w;
if (reason==0) w.busy=true;
if (reason==1) w.packet=true;
if (reason==2) state=STATE_RX|STATE_INT_READY;
if (reason==3) state=STATE_TX_WAIT;
w.enable();
assert(!w._profile_standby_held && !w.chip.standbyXOSC && w._rx_ps_enabled);
w.busy=w.packet=false; state=STATE_RX; w.serviceProfileScan();
assert(w.chip.standbyXOSC && w._profile_rxps_suspended);
w._profiles.setSecondary({},false); w.busy=true; w.serviceProfileScan();
assert(w.chip.standbyXOSC && w._profile_rxps_suspended);
w.busy=false; w.serviceProfileScan();
assert(!w.chip.standbyXOSC && !w._profile_rxps_suspended && w._rx_ps_enabled);
}
}
'''
@@ -140,6 +193,10 @@ class ProfileScanTest(unittest.TestCase):
('void','serviceProfileScan')]+[('mesh::RadioParamApplyResult',name) for name in
['tuneProfile','prepareTransmitProfile','trySetParams','trySetPrimaryParams']]
methods='\n'.join(method(source,f'{kind} RadioLibWrapper::{name}(') for kind,name in names)
wrapper=(ROOT/'src/helpers/radiolib/CustomSX1262Wrapper.h').read_text()
methods+='\n'+method(wrapper,'void setProfileStandbyWarm(').replace(
'void setProfileStandbyWarm(bool enabled) override',
'void RadioLibWrapper::setProfileStandbyWarm(bool enabled)')
with tempfile.TemporaryDirectory() as folder:
cpp=Path(folder)/'test.cpp'; exe=Path(folder)/'test.exe'
(Path(folder)/'Arduino.h').write_text('#pragma once\n#include <cstdint>\n#include <cmath>\n')
@@ -150,4 +207,55 @@ class ProfileScanTest(unittest.TestCase):
result=subprocess.run([str(exe)],capture_output=True,text=True)
self.assertEqual(result.returncode,0,result.stderr)
def test_warm_oscillator_is_not_used_before_tcxo_reinitialization(self):
source=(ROOT/'src/helpers/radiolib/CustomSX1262.h').read_text()
begin=method(source,'int16_t begin(')
harness=r'''
#include <cassert>
#include <cstdint>
#define RADIOLIB_SX126X_SYNC_WORD_PRIVATE 0x12
#define RADIOLIB_ERR_NONE 0
struct SX1262 {
bool standbyXOSC=false;
int16_t beginResult=0, calibrationResult=0;
unsigned calibrations=0;
int16_t begin(float,float,uint8_t,uint8_t,uint8_t,int8_t,uint16_t,float,bool) {
assert(!standbyXOSC); // every init command must use RC until TCXO is configured
return beginResult;
}
};
struct CustomSX1262: SX1262 {
bool _coldStandby=false;
bool _tcxoWakePending=true;
struct { bool invalidated=false; void invalidate() { invalidated=true; } } _profileSwitch;
int16_t applyMeshCoreTcxoDelay() {
assert(!standbyXOSC); ++calibrations; return calibrationResult;
}
@BEGIN@
};
int main() {
for (bool warm: {false,true}) {
for (int failure=0; failure<3; ++failure) {
CustomSX1262 radio; radio.standbyXOSC=warm;
radio.beginResult=failure==1 ? -1 : 0;
radio.calibrationResult=failure==2 ? -2 : 0;
assert(radio.begin()==-failure);
assert(radio._profileSwitch.invalidated);
assert(radio._coldStandby);
assert(!radio._tcxoWakePending);
assert(radio.standbyXOSC==warm);
assert(radio.calibrations==(failure==1 ? 0u : 1u));
}
}
}
'''
with tempfile.TemporaryDirectory() as folder:
cpp=Path(folder)/'test.cpp'; exe=Path(folder)/'test.exe'
cpp.write_text('#include <initializer_list>\n'+harness.replace('@BEGIN@',begin))
result=subprocess.run([os.environ.get('CXX','g++'),'-std=c++17','-Wall','-Wextra',
str(cpp),'-o',str(exe)],capture_output=True,text=True)
self.assertEqual(result.returncode,0,result.stderr)
result=subprocess.run([str(exe)],capture_output=True,text=True)
self.assertEqual(result.returncode,0,result.stderr)
if __name__=='__main__': unittest.main()
+166
View File
@@ -0,0 +1,166 @@
"""Execute production batched modulation validation/cache and wrapper paths."""
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 BatchedModulationTests(unittest.TestCase):
def compile_run(self, source):
with tempfile.TemporaryDirectory() as folder:
cpp, exe = Path(folder) / "test.cpp", Path(folder) / "test.exe"
cpp.write_text(source)
built = subprocess.run([os.environ.get("CXX", "g++"), "-std=c++17",
"-Wall", "-Wextra", str(cpp), "-o", str(exe)],
capture_output=True, text=True)
self.assertEqual(built.returncode, 0, built.stderr)
ran = subprocess.run([str(exe)], capture_output=True, text=True)
self.assertEqual(ran.returncode, 0, ran.stderr)
def test_tuple_validation_ldro_and_failure_cache_rollback(self):
production = method((ROOT / "src/helpers/radiolib/CustomSX1262.h").read_text(),
"int16_t setLoRaModulationParams(")
harness = r'''
#include <cassert>
#include <cmath>
#include <cstdint>
#include <cstddef>
#include <initializer_list>
using std::isfinite;
#define RADIOLIB_ERR_NONE 0
#define RADIOLIB_ERR_INVALID_SPREADING_FACTOR -1
#define RADIOLIB_ERR_INVALID_CODING_RATE -2
#define RADIOLIB_ERR_INVALID_BANDWIDTH -3
#define RADIOLIB_ERR_WRONG_MODEM -4
#define RADIOLIB_SX126X_PACKET_TYPE_LORA 1
#define RADIOLIB_SX126X_LORA_BW_7_8 0x00
#define RADIOLIB_SX126X_LORA_BW_10_4 0x08
#define RADIOLIB_SX126X_LORA_BW_15_6 0x01
#define RADIOLIB_SX126X_LORA_BW_20_8 0x09
#define RADIOLIB_SX126X_LORA_BW_31_25 0x02
#define RADIOLIB_SX126X_LORA_BW_41_7 0x0a
#define RADIOLIB_SX126X_LORA_BW_62_5 0x03
#define RADIOLIB_SX126X_LORA_BW_125_0 0x04
#define RADIOLIB_SX126X_LORA_BW_250_0 0x05
#define RADIOLIB_SX126X_LORA_BW_500_0 0x06
struct Radio {
uint8_t spreadingFactor=9, bandwidth=4, codingRate=3, ldrOptimize=0;
float bandwidthKhz=125;
bool ldroAuto=true;
unsigned queries=0, writes=0;
uint8_t packetType=1, payload[4]={};
int16_t result=0;
uint8_t getPacketType() { ++queries; return packetType; }
int16_t setModulationParams(uint8_t sf,uint8_t bw,uint8_t cr,uint8_t ldro) {
// RadioLib 187ef247 reads these caches, not just the command arguments,
// when deciding LDRO. Assert they are synchronized before that call.
assert(spreadingFactor==sf && bandwidth==bw && codingRate==cr);
if (ldroAuto) ldrOptimize=((1U<<spreadingFactor)/bandwidthKhz)>=16.0f;
else ldrOptimize=ldro;
payload[0]=sf;payload[1]=bw;payload[2]=cr;payload[3]=ldrOptimize;
++writes; return result;
}
@PRODUCTION@
};
bool sameCache(const Radio& a,const Radio& b) {
return a.spreadingFactor==b.spreadingFactor && a.bandwidth==b.bandwidth
&& a.bandwidthKhz==b.bandwidthKhz && a.codingRate==b.codingRate
&& a.ldrOptimize==b.ldrOptimize && a.ldroAuto==b.ldroAuto;
}
int main() {
const float bandwidths[]={7.8f,10.4f,15.6f,20.8f,31.25f,41.7f,62.5f,125,250,500};
const uint8_t codes[]={0,8,1,9,2,10,3,4,5,6};
for (unsigned i=0;i<10;++i) for(uint8_t sf=5;sf<=12;++sf)
for(uint8_t cr=4;cr<=8;++cr) for(int mode=0;mode<3;++mode) {
Radio r;r.ldroAuto=mode==0;r.ldrOptimize=mode==2;
assert(r.setLoRaModulationParams(bandwidths[i],sf,cr)==0);
assert(r.queries==1 && r.writes==1);
assert(r.spreadingFactor==sf && r.bandwidth==codes[i]);
assert(r.bandwidthKhz==bandwidths[i] && r.codingRate==cr-4);
const uint8_t ldro=mode==0 ? ((1U<<sf)/bandwidths[i]>=16.0f) : mode==2;
assert(r.ldrOptimize==ldro && r.payload[0]==sf && r.payload[1]==codes[i]
&& r.payload[2]==cr-4 && r.payload[3]==ldro);
}
// Invalid values cannot issue SPI, mutate caches, or enter float->int UB.
for(float bw: {NAN,INFINITY,-INFINITY,-1.0f,0.0f,50.0f,62.6f,1000.0f}) {
Radio r,old=r;assert(r.setLoRaModulationParams(bw,7,5)==-3);
assert(!r.queries && !r.writes && sameCache(r,old));
}
for(uint8_t sf: {0,4,13,255}) {
Radio r,old=r;assert(r.setLoRaModulationParams(500,sf,5)==-1);
assert(!r.queries && !r.writes && sameCache(r,old));
}
for(uint8_t cr: {0,3,9,255}) {
Radio r,old=r;assert(r.setLoRaModulationParams(500,7,cr)==-2);
assert(!r.queries && !r.writes && sameCache(r,old));
}
for(uint8_t packet: {0,2,255}) {
Radio r;r.packetType=packet;Radio old=r;
assert(r.setLoRaModulationParams(500,7,5)==-4);
assert(r.queries==1 && !r.writes && sameCache(r,old));
}
for (int mode=0;mode<3;++mode) for(int error: {-10,-705,-707}) {
Radio r;r.ldroAuto=mode==0;r.ldrOptimize=mode==2;Radio old=r;r.result=error;
assert(r.setLoRaModulationParams(7.8f,12,8)==error);
assert(r.queries==1 && r.writes==1 && sameCache(r,old));
// A following restoration/retry must still work.
r.result=0;assert(r.setLoRaModulationParams(125,9,7)==0);
assert(sameCache(r,old));
}
}
'''
self.compile_run(harness.replace("@PRODUCTION@", production))
def test_wrapper_batches_once_and_preserves_failure_short_circuit(self):
source = (ROOT / "src/helpers/radiolib/CustomSX1262Wrapper.h").read_text()
production = method(source, "bool applyParams(").replace(" override", "")
harness = r'''
#include <cassert>
#include <cstdint>
#define RADIOLIB_ERR_NONE 0
struct CustomSX1262 {
unsigned freq=0,mod=0,limits=0;int failure=0;
bool profileSwitchFailed() const { return failure==4; }
int setFrequency(float f) { assert(f==910.5f);++freq;return failure==1?-1:0; }
int setLoRaModulationParams(float bw,uint8_t sf,uint8_t cr) {
assert(bw==500 && sf==8 && cr==5);++mod;return failure==2?-1:0;
}
void setPreambleMillis(uint32_t v) { assert(v==123);++limits; }
void setMaxPayloadMillis(uint32_t v) { assert(v==456);++limits; }
};
struct PacketMillis { uint32_t preambleMillis,payloadMillis; };
struct Wrapper {
CustomSX1262 chip;CustomSX1262* _radio=&chip;unsigned preamble=0,calcs=0;
bool updatePreamble(uint8_t sf,float bw) {
assert(sf==8 && bw==500);++preamble;return chip.failure!=3;
}
uint16_t preambleLengthForParams(uint8_t,float) { return 88; }
PacketMillis calcMaxPacketMillis(uint8_t,float,uint8_t,uint16_t p) {
assert(p==88);++calcs;return {123,456};
}
@PRODUCTION@
};
int main() {
Wrapper stopped;stopped.chip.failure=4;
assert(!stopped.applyParams(910.5f,500,8,5));
assert(!stopped.chip.freq && !stopped.chip.mod && !stopped.preamble);
for(int failure=0;failure<=3;++failure) {
Wrapper w;w.chip.failure=failure;
assert(w.applyParams(910.5f,500,8,5)==(failure==0));
assert(w.chip.freq==1);
assert(w.chip.mod==(failure==1?0u:1u));
assert(w.preamble==((failure==1 || failure==2)?0u:1u));
assert(w.calcs==(failure?0u:1u) && w.chip.limits==(failure?0u:2u));
}
}
'''
self.compile_run(harness.replace("@PRODUCTION@", production))
if __name__ == "__main__":
unittest.main()
+159
View File
@@ -0,0 +1,159 @@
"""Exercise actual production fast-RX methods and invalidation state."""
from pathlib import Path
import unittest
import test_sx1262_batched_modulation as compiler
from test_radio_receive_contract import method
ROOT = Path(__file__).resolve().parents[1]
class FastProfileSwitchTests(unittest.TestCase):
compile_run = compiler.BatchedModulationTests.compile_run
def test_owned_rx_window_commands_errors_and_lifecycle_invalidation(self):
src = (ROOT / "src/helpers/radiolib/CustomSX1262.h").read_text()
state = (ROOT / "src/helpers/radiolib/SX1262ProfileSwitchState.h").read_text().replace("#pragma once", "")
signatures = ["void setProfileSwitchOptimization(", "void beginProfileSwitch(",
"void endProfileSwitch(", "bool profileSwitchFailed(", "int16_t restoreTcxoAfterSleep(",
"int16_t standby()", "int16_t standby(uint8_t", "int16_t sleep()",
"int16_t sleep(bool", "int16_t reset(bool", "int16_t stageMode(",
"int16_t setPreambleLength(", "int16_t startReceive()",
"int16_t startReceiveDutyCycle("]
methods = "\n".join(method(src, signature).replace(" override", "") for signature in signatures)
harness = r'''
#include <cassert>
#include <cstdint>
#include <cstddef>
#include <string>
@STATE@
#define RADIOLIB_ERR_NONE 0
#define RADIOLIB_SX126X_STANDBY_XOSC 1
#define RADIOLIB_SX126X_STANDBY_RC 0
#define RADIOLIB_SX126X_XOSC_START_ERR 32
#define RADIOLIB_ERR_SPI_CMD_FAILED -200
#define RADIOLIB_SX126X_RX_TIMEOUT_INF 0xffffff
#define RADIOLIB_SX126X_PACKET_TYPE_LORA 1
#define RADIOLIB_RADIO_MODE_NONE 0
#define RADIOLIB_IRQ_RX_DEFAULT_FLAGS 1
#define RADIOLIB_IRQ_RX_DEFAULT_MASK 2
#define RADIOLIB_IRQ_PREAMBLE_DETECTED 3
using RadioModeType_t=int;
using RadioLibIrqFlags_t=uint32_t;
struct RadioModeConfig_t {};
struct Module {
enum { MODE_RX=1 };std::string* trace;
void setRfSwitchState(int mode) { assert(mode==MODE_RX);*trace+='W'; }
};
struct SX1262 {
std::string trace;char fail=0;int modem=1;bool standbyXOSC=true;
size_t preambleLengthLoRa=32;
uint8_t crcTypeLoRa=1,implicitLen=255,headerType=0,invertIQEnabled=0;
uint32_t rxTimeout=0;int stagedMode=3;
float tcxoVoltage=1.8f;uint32_t tcxoDelay=1600;unsigned errors=32;
Module module{&trace};Module* mod=&module;
virtual ~SX1262()=default;
int16_t call(char c) { trace+=c;return fail==c ? -100:0; }
Module* getMod() { return mod; }
virtual int16_t standby() { return call('S'); }
virtual int16_t standby(uint8_t) { return call('U'); }
int16_t standby(uint8_t mode,bool wake) { assert(mode==1);return call(wake?'S':'s'); }
virtual int16_t sleep() { return call('L'); }
int16_t sleep(bool) { return call('l'); }
int16_t reset(bool) { return call('Z'); }
unsigned getDeviceErrors() { call('E');return errors; }
int16_t setTCXO(float voltage,uint32_t delay) {
assert(voltage==tcxoVoltage && delay==1600);return call('V');
}
virtual int16_t stageMode(RadioModeType_t mode,RadioModeConfig_t*) { return call(mode==1?'G':'T'); }
virtual int16_t setPreambleLength(size_t n) { preambleLengthLoRa=n;return call('M'); }
int16_t startReceive(uint32_t timeout,uint32_t flags,uint32_t mask,size_t len) {
assert(timeout==0xffffff && flags==9 && mask==2 && len==0);
int16_t rc=stageMode(1,nullptr);if(rc==0) rc=standby();if(rc==0) rc=call('F');return rc;
}
int16_t startReceiveDutyCycle(uint32_t,uint32_t,uint32_t,uint32_t) { return call('D'); }
uint8_t getPacketType() { call('Q');return modem; }
int16_t clearIrqStatus() { return call('C'); }
int16_t setPacketParams(size_t p,int crc,int len,int header,int iq) {
assert(p==preambleLengthLoRa && crc==1 && len==255 && header==0 && iq==0);return call('P');
}
int16_t setRx(uint32_t timeout) { assert(timeout==0xffffff);return call('R'); }
};
struct Radio: SX1262 {
SX1262ProfileSwitchState _profileSwitch{true};bool _rx_ps_rf_rx_disabled=false;uint32_t _profileFastResumes=0;
bool _coldStandby=true;
bool _tcxoWakePending=false;
@METHODS@
};
void prime(Radio& r) {
const bool cold=r._coldStandby;
const bool wake=r._tcxoWakePending;
r.trace.clear();assert(r.startReceive()==0);assert(r.trace==(wake ? "GUEVFQ":cold ? "GUFQ":"GSFQ"));
assert(!r._coldStandby);
assert(r._profileSwitch.rxValid);r.trace.clear();
}
void fast(Radio& r) {
r.beginProfileSwitch(true);assert(r.standby()==0);assert(r.trace=="s");r.trace.clear();
assert(r.setPreambleLength(120)==0 && r.trace.empty());
assert(r.startReceive()==0 && r.trace=="CPWR");
assert(r.stagedMode==0 && r._profileSwitch.rxValid);
r.endProfileSwitch(true);assert(!r._profileSwitch.open);r.trace.clear();
}
int main() {
Radio r;prime(r);fast(r);fast(r);
// Deferring before standby changes no hardware and retains the RX context.
r.beginProfileSwitch(true);r.endProfileSwitch(true);fast(r);
// No shortcut is legal before a successful owned standby.
r.beginProfileSwitch(true);assert(r.setPreambleLength(88)==0 && r.trace=="M");
r.endProfileSwitch(true);r.trace.clear();
// Ordinary standby, mode staging (TX/CAD), sleep, reset and RXPS revoke RX.
for(int event=0;event<7;++event) {
Radio x;prime(x);
switch(event) {
case 0:x.standby();break;
case 1:x.standby(uint8_t(0));break;
case 2:x.stageMode(2,nullptr);break;
case 3:x.sleep();break;
case 4:x.sleep(false);break;
case 5:x.reset();break;
case 6:x.startReceiveDutyCycle(1000,1000);break;
}
assert(!x._profileSwitch.rxValid);x.trace.clear();x.beginProfileSwitch(true);
const bool cold=x._coldStandby;
const bool wake=x._tcxoWakePending;
assert(x.standby()==0 && x.trace==(wake ? "UEV":cold ? "U":"S"));x.endProfileSwitch(true);prime(x);fast(x);
}
for(int gate=0;gate<3;++gate) {
Radio x;prime(x);
if(gate==0) x.setProfileSwitchOptimization(false);
if(gate==1) x.standbyXOSC=false;
x.beginProfileSwitch(gate!=2);x.trace.clear();
assert(x.standby()==0 && x.trace=="S");x.endProfileSwitch(true);
}
for(char fail:std::string("sCPR")) {
Radio x;prime(x);x.beginProfileSwitch(true);x.fail=fail;
if(fail=='s') assert(x.standby()==-100);
else { assert(x.standby()==0);assert(x.startReceive()==-100); }
assert(x.profileSwitchFailed() && !x._profileSwitch.rxValid);
assert(x.trace.back()==fail);x.endProfileSwitch(false);x.fail=0;prime(x);fast(x);
}
Radio x;prime(x);x.beginProfileSwitch(true);x.standby();
// A modulation/frequency/packet apply failure must revoke the capability
// before the wrapper rolls back with normal setup.
x.endProfileSwitch(false);assert(!x._profileSwitch.rxValid);prime(x);fast(x);
Radio sleeper;prime(sleeper);assert(sleeper.sleep()==0 && sleeper.trace=="Ul");
prime(sleeper);sleeper.fail='U';assert(sleeper.sleep(true)==-100 && sleeper.trace=="U");
assert(!sleeper._profileSwitch.rxValid && sleeper._coldStandby);
Radio fault;prime(fault);fault.sleep();fault.trace.clear();fault.errors=4;
assert(fault.standby()==-200 && fault.trace=="UE" && fault._tcxoWakePending);
fault.errors=32;fault.trace.clear();assert(fault.standby()==0 && fault.trace=="UEV");
assert(!fault._tcxoWakePending);
Radio wrong;wrong.modem=0;assert(wrong.startReceive()==0 && !wrong._profileSwitch.rxValid);
Radio off;off.setProfileSwitchOptimization(false);assert(off.startReceive()==0);
assert(off.trace=="GUF" && !off._profileSwitch.rxValid);
}
'''
self.compile_run(harness.replace("@STATE@", state).replace("@METHODS@", methods))
if __name__ == "__main__":
unittest.main()