Preserve radio lab experiments and reuse unchanged SX1262 modulation
Skip redundant modulation writes during owned fast RX retunes when the last acknowledged SF/BW/CR/LDRO tuple matches. Invalidate that cache after ordinary setters, failed writes, and lifecycle changes. Include the remaining scan, preamble, settling, and memory-soak experiments, their collectors, validation notes, and original capture records. Preserve capture bytes across checkouts and keep private soak credentials local. Run lab collector and compiled contract tests in CI. Update the expectation, profile mapping, and result-buffer tests for the extended lab tools, and make the private WiFi override header optional for ordinary soak diagnostics. Validation: 145 host tests passed from the staged source snapshot. Clean heltec_v4_repeater and Xiao_S3_WIO_companion_radio_usb builds passed their RAM/flash gates. All 229 staged capture files retain their original bytes; all 75 local documentation links resolve in the clean snapshot.
This commit is contained in:
1 parent
55b4d8848d
commit
170c2c44b1
374 files changed
+412356
-100
No files matched your search
@@ -7,6 +7,28 @@ import test_sx1262_batched_modulation as compiler
|
||||
class ChannelTraceTests(unittest.TestCase):
|
||||
compile_run = compiler.BatchedModulationTests.compile_run
|
||||
|
||||
def test_settle_is_additional_and_cycles_exclude_held_visits(self):
|
||||
source = (Path(__file__).resolve().parents[1] / "tools/hil/ProfileChannelVisitClock.h").read_text().replace("#pragma once", "")
|
||||
self.compile_run(r'''
|
||||
#include <cassert>
|
||||
@SOURCE@
|
||||
int main() {
|
||||
ChannelVisitClock v;
|
||||
v.begin(100,200,false);assert(v.dwell(500,100)==400); // zero-delay legacy clock
|
||||
v.begin(100,1100,true);assert(v.dwell(3711,100)==2611);
|
||||
assert(v.dwell(3712,100)==2612); // settling did not consume the 5.1-symbol visit
|
||||
assert(v.dwell(4100,4000)==100); // packet restart has no channel-settle delay
|
||||
v.begin(0xfffffff0u,0xfffffffau,true);assert(v.dwell(10,0xfffffff0u)==16);
|
||||
ChannelCycleClock c;uint32_t elapsed=0;
|
||||
assert(!c.hop(0,100,false,elapsed));
|
||||
for(unsigned ch=1;ch<4;++ch) assert(!c.hop(ch,100+ch*3000,false,elapsed));
|
||||
assert(c.hop(0,12100,false,elapsed) && elapsed==12000);
|
||||
assert(!c.hop(2,15000,true,elapsed));
|
||||
assert(!c.hop(0,25000,false,elapsed)); // a held visit invalidates this full cycle
|
||||
assert(c.hop(0,37000,false,elapsed) && elapsed==12000);
|
||||
}
|
||||
'''.replace("@SOURCE@", source))
|
||||
|
||||
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)
|
||||
@@ -17,11 +39,13 @@ class ChannelTraceTests(unittest.TestCase):
|
||||
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"):
|
||||
for expected in ("sweepParams(0,preamble,sf,bwKhz)", "sweepParams(1,preamble,sf,bwKhz)",
|
||||
"setLoRaModulationParams(bwKhz,sf,5)", "channelSweep.sf=sf;",
|
||||
"channelSweep.bwKhz=bwKhz;", "p.bw=bwKhz",
|
||||
"chip.bandwidthKhz!=expectedParams.bw",
|
||||
"chip.spreadingFactor!=expectedParams.sf"):
|
||||
self.assertIn(expected, source)
|
||||
self.assertEqual(source.count("sweepParams(next,channelSweep.preamble,channelSweep.sf)"), 2)
|
||||
self.assertEqual(source.count("sweepParams(next,channelSweep.preamble,channelSweep.sf,channelSweep.bwKhz)"), 3)
|
||||
|
||||
def test_passive_irq_decode_bounds_and_freeze(self):
|
||||
source = (Path(__file__).resolve().parents[1] / "tools/hil/ProfileChannelTrace.h").read_text().replace("#pragma once", "")
|
||||
@@ -52,6 +76,10 @@ int main() {
|
||||
t.active=false;
|
||||
uint8_t rf[5]={0x86,0x38,0xe0,0,0};t.observe(rf,5,in);
|
||||
assert(t.rfWord==0x38e00000);
|
||||
assert(t.rfWrites==1 && t.modulationWrites==0);
|
||||
uint8_t modulation[5]={0x8b,6,4,1,0};t.observe(modulation,5,in);
|
||||
assert(t.modulationWrites==1 && t.size==1);
|
||||
assert(t.modulationWord==0x06040100);
|
||||
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);
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Fixed-sample HIL continuation never erases misses or resets the scanner."""
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
from test_radio_receive_contract import method
|
||||
import test_sx1262_batched_modulation as compiler
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
|
||||
class ContinueTests(unittest.TestCase):
|
||||
compile_run=compiler.BatchedModulationTests.compile_run
|
||||
|
||||
def test_completion_changes_only_expectation_counts_and_stop_policy(self):
|
||||
source=(ROOT/'tools/hil/profile_switch_channels.h').read_text()
|
||||
body=method(source,'void completeChannelExpectation(')
|
||||
self.compile_run(r'''
|
||||
#include <cassert>
|
||||
bool channelContinueOnMiss=false;
|
||||
struct {bool active=true,expecting=true;unsigned received=0,missed=0;} channelSweep;
|
||||
@METHOD@
|
||||
int main(){
|
||||
completeChannelExpectation(false);
|
||||
assert(!channelSweep.active&&!channelSweep.expecting&&channelSweep.missed==1);
|
||||
channelSweep={};channelContinueOnMiss=true;
|
||||
for(unsigned i=0;i<400;++i){
|
||||
channelSweep.expecting=true;completeChannelExpectation(i%4==0);
|
||||
assert(channelSweep.active&&!channelSweep.expecting);
|
||||
}
|
||||
assert(channelSweep.received==100&&channelSweep.missed==300);
|
||||
}
|
||||
'''.replace('@METHOD@',body))
|
||||
service=method(source,'void serviceChannelSweep(')
|
||||
self.assertIn('completeChannelExpectation(accepted)',service)
|
||||
self.assertIn('completeChannelExpectation(false)',service)
|
||||
self.assertIn('++channelSweep.failures;channelSweep.active=false',service)
|
||||
|
||||
def test_expectations_preserve_scanner_phase_and_use_mode_timeout(self):
|
||||
source=(ROOT/'tools/hil/profile_switch_channels.h').read_text()
|
||||
self.compile_run(r'''
|
||||
#include <cassert>
|
||||
#include <cstdint>
|
||||
bool channelPair=false;
|
||||
uint32_t nowMs=0xfffffff0u;
|
||||
uint32_t millis(){return nowMs;}
|
||||
uint32_t micros(){return 900;}
|
||||
struct {
|
||||
bool active=true,expecting=false;
|
||||
unsigned channels=2,current=1,expectedChannel=0;
|
||||
uint32_t sequence=0,deadline=0,visitStartedUs=100,received=7,missed=3;
|
||||
} channelSweep;
|
||||
struct {
|
||||
unsigned calls=0;
|
||||
void arm(unsigned,unsigned current,unsigned,uint32_t age){
|
||||
++calls;assert(current==1&&age==800);
|
||||
}
|
||||
} channelTrace;
|
||||
struct {unsigned errors=0;void println(const char*){++errors;}} Serial;
|
||||
int lastListenResult=0;
|
||||
unsigned recorded=0;
|
||||
void recordBenchResult(int&,unsigned sequence,const char*,...){recorded=sequence;}
|
||||
@METHOD@
|
||||
int main(){
|
||||
for(unsigned pair=0;pair<2;++pair){
|
||||
channelPair=pair;channelSweep.expecting=false;
|
||||
expectChannelPacket(0,42+pair);
|
||||
assert(channelSweep.expecting&&channelSweep.sequence==42+pair);
|
||||
assert(channelSweep.deadline==uint32_t(nowMs+(pair?1000:10000)));
|
||||
assert(recorded==42+pair&&channelTrace.calls==pair+1);
|
||||
assert(channelSweep.current==1&&channelSweep.visitStartedUs==100);
|
||||
assert(channelSweep.received==7&&channelSweep.missed==3);
|
||||
expectChannelPacket(1,99); // overlapping requests cannot restart a deadline
|
||||
assert(channelSweep.sequence==42+pair&&recorded==42+pair);
|
||||
}
|
||||
channelSweep.expecting=false;
|
||||
expectChannelPacket(2,99);
|
||||
assert(!channelSweep.expecting&&channelTrace.calls==2&&Serial.errors==3);
|
||||
}
|
||||
'''.replace('@METHOD@',method(source,'void expectChannelPacket(')))
|
||||
|
||||
if __name__=='__main__': unittest.main()
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Sub-float HIL detour changes the actual RF command, not the MHz float."""
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
from test_radio_receive_contract import method
|
||||
import test_sx1262_batched_modulation as compiler
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class FrequencyOffsetTests(unittest.TestCase):
|
||||
compile_run = compiler.BatchedModulationTests.compile_run
|
||||
|
||||
def test_integer_word_offset_and_scoped_restore(self):
|
||||
source = (ROOT / 'tools/hil/ProfileFrequencyOffset.h').read_text().replace('#pragma once', '')
|
||||
self.compile_run(r'''
|
||||
#include <cassert>
|
||||
#include <cstring>
|
||||
@SOURCE@
|
||||
void earlyReturn() { HilFrequencyOffsetScope offset(10); }
|
||||
int main() {
|
||||
uint8_t original[5]={0x86,0x38,0xd8,0xff,0xfc}, shifted[5]={};
|
||||
uint8_t saved[5];memcpy(saved,original,5);
|
||||
assert(hilFrequencyCommand(original,5,shifted)==original);
|
||||
{
|
||||
HilFrequencyOffsetScope offset(10);
|
||||
assert(hilFrequencyCommand(original,5,shifted)==shifted);
|
||||
const uint8_t expected[5]={0x86,0x38,0xd9,0,6};
|
||||
assert(memcmp(shifted,expected,5)==0 && memcmp(original,saved,5)==0);
|
||||
assert(hilFrequencyCommand(original,4,shifted)==original);
|
||||
assert(hilFrequencyCommand(nullptr,5,shifted)==nullptr);
|
||||
uint8_t other[5]={0x8b,10,4,2,0};
|
||||
assert(hilFrequencyCommand(other,5,shifted)==other);
|
||||
uint8_t overflow[5]={0x86,0xff,0xff,0xff,0xfc};
|
||||
assert(hilFrequencyCommand(overflow,5,shifted)==overflow);
|
||||
{ HilFrequencyOffsetScope zero(0);assert(hilFrequencyCommand(original,5,shifted)==original); }
|
||||
assert(hilFrequencyOffsetSteps==10);
|
||||
}
|
||||
assert(hilFrequencyOffsetSteps==0);
|
||||
earlyReturn();assert(hilFrequencyOffsetSteps==0);
|
||||
assert(hilFrequencyCommand(original,5,shifted)==original);
|
||||
const float mhz=909.5f;
|
||||
assert(float(mhz+0.00001f)==mhz); // float API cannot encode requested 10 Hz
|
||||
assert(10.0*32000000.0/33554432.0==9.5367431640625);
|
||||
{ HilFrequencyOffsetScope offset(105);
|
||||
hilFrequencyCommand(original,5,shifted);
|
||||
const uint8_t expected[5]={0x86,0x38,0xd9,0,101};
|
||||
assert(memcmp(shifted,expected,5)==0 && memcmp(original,saved,5)==0);
|
||||
}
|
||||
assert(105.0*32000000.0/33554432.0==100.13580322265625);
|
||||
}
|
||||
'''.replace('@SOURCE@', source))
|
||||
|
||||
def test_wire_and_observer_use_shifted_bytes(self):
|
||||
source = (ROOT / 'tools/hil/profile_switch.cpp').read_text()
|
||||
transfer = method(source, 'void spiTransfer(')
|
||||
self.assertIn('hilFrequencyCommand(out,len,shifted)', transfer)
|
||||
self.assertIn('ESP32BufferedRadioHal::spiTransfer(const_cast<uint8_t*>(wire)', transfer)
|
||||
self.assertIn('ArduinoHal::spiTransfer(const_cast<uint8_t*>(wire)', transfer)
|
||||
self.assertIn('channelTrace.observe(wire,len,in)', transfer)
|
||||
apply = method(source, 'bool applyParams(')
|
||||
self.assertIn('HilFrequencyOffsetScope offset(firstPassDetour && hopPasses==2 && cr==6 ? firstPassOffsetSteps : 0)', apply)
|
||||
|
||||
def test_capability_reply_avoids_exact_usb_packet_boundary(self):
|
||||
import json
|
||||
import re
|
||||
source = (ROOT / 'tools/hil/profile_switch.cpp').read_text()
|
||||
branch = source.split('!strcmp(line,"detourinfo")', 1)[1].split('} else', 1)[0]
|
||||
literal = re.search(r'Serial\.printf\(("(?:\\.|[^"\\])*")', branch).group(1)
|
||||
template = json.loads(literal)
|
||||
for hz, steps in ((10,10),(100,105)):
|
||||
reply = template % (hz/1000,steps,steps*32000000/33554432)
|
||||
self.assertNotEqual(len(reply.encode('ascii'))%64, 0)
|
||||
self.assertTrue(reply.endswith('\n'))
|
||||
self.assertEqual(json.loads(reply)['rf_offset_steps'], steps)
|
||||
self.assertEqual(json.loads(reply)['offset_hz'],steps*32000000/33554432)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Check the actual HIL frequency override's scope, order and error propagation."""
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
from test_radio_receive_contract import method
|
||||
import test_sx1262_batched_modulation as compiler
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class FrequencyRepeatTests(unittest.TestCase):
|
||||
compile_run=compiler.BatchedModulationTests.compile_run
|
||||
|
||||
def test_only_owned_rx_hops_repeat_and_failures_short_circuit(self):
|
||||
source=method((ROOT/'tools/hil/profile_switch_experiments.h').read_text(),
|
||||
'int16_t setFrequency(')
|
||||
harness=r'''
|
||||
#include <cassert>
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
#define RADIOLIB_ERR_NONE 0
|
||||
struct SX1262 {
|
||||
std::vector<bool> calibrationSkipped; int failAt=0;
|
||||
virtual int16_t setFrequency(float f) { return setFrequency(f,false); }
|
||||
int16_t setFrequency(float f,bool skip) {
|
||||
assert(f==909.5f); calibrationSkipped.push_back(skip);
|
||||
return int(calibrationSkipped.size())==failAt ? -3:0;
|
||||
}
|
||||
};
|
||||
struct Radio : SX1262 {
|
||||
bool repeatFrequency=false, inHop=false, resumeRx=false;
|
||||
@METHOD@
|
||||
};
|
||||
int main() {
|
||||
for(bool enabled : {false,true}) for(bool hop : {false,true}) for(bool rx : {false,true}) {
|
||||
Radio r;r.repeatFrequency=enabled;r.inHop=hop;r.resumeRx=rx;
|
||||
assert(r.setFrequency(909.5f)==0);
|
||||
assert(r.calibrationSkipped.size()==(enabled&&hop&&rx?2u:1u));
|
||||
assert(!r.calibrationSkipped.front());
|
||||
if(r.calibrationSkipped.size()==2) assert(r.calibrationSkipped.back());
|
||||
}
|
||||
for(int fail : {1,2}) {
|
||||
Radio r;r.repeatFrequency=r.inHop=r.resumeRx=true;r.failAt=fail;
|
||||
assert(r.setFrequency(909.5f)==-3);
|
||||
assert(int(r.calibrationSkipped.size())==fail);
|
||||
}
|
||||
}
|
||||
'''
|
||||
self.compile_run(harness.replace('@METHOD@',source))
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,71 @@
|
||||
"""HIL V4 front-end selection and restoration around every direct TX path."""
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
from test_radio_receive_contract import method
|
||||
import test_sx1262_batched_modulation as compiler
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class HeltecHilTests(unittest.TestCase):
|
||||
compile_run = compiler.BatchedModulationTests.compile_run
|
||||
|
||||
def test_gc_bypass_kct_tx_and_restore_even_on_error(self):
|
||||
source = (ROOT / "tools/hil/ProfileHeltecV4.h").read_text().replace(
|
||||
'#include "LoRaFEMControl.h"', '').replace('#pragma once', '')
|
||||
tx = method((ROOT / "tools/hil/profile_switch.cpp").read_text(), 'int16_t benchTransmit(')
|
||||
harness = r'''
|
||||
#include <cassert>
|
||||
#include <cstdint>
|
||||
#include <cstddef>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
enum { GC1109_PA, KCT8103L_PA };
|
||||
struct LoRaFEMControl {
|
||||
int type=GC1109_PA; std::string calls;
|
||||
void init() { calls+='I'; }
|
||||
void setRxModeEnable() { calls+='R'; }
|
||||
void setTxModeEnable() { calls+='T'; }
|
||||
int getFEMType() const { return type; }
|
||||
};
|
||||
@SOURCE@
|
||||
ProfileHeltecV4 v4FrontEnd;
|
||||
struct {
|
||||
int16_t rc=0;
|
||||
int16_t transmit(uint8_t*,size_t n) {
|
||||
assert(n==16);
|
||||
assert(v4FrontEnd.fem.calls.back()==(v4FrontEnd.fem.type==GC1109_PA?'R':'T'));
|
||||
v4FrontEnd.fem.calls+='X'; return rc;
|
||||
}
|
||||
} chip;
|
||||
#define HIL_HELTEC_V4
|
||||
@TX@
|
||||
int main() {
|
||||
uint8_t data[16]={};
|
||||
for(int fem : {GC1109_PA,KCT8103L_PA}) {
|
||||
v4FrontEnd.fem.type=fem; v4FrontEnd.fem.calls.clear();
|
||||
v4FrontEnd.begin(); assert(v4FrontEnd.fem.calls=="IR");
|
||||
assert(!strcmp(v4FrontEnd.type(),fem==GC1109_PA?"GC1109":"KCT8103L"));
|
||||
assert(!strcmp(v4FrontEnd.txMode(),fem==GC1109_PA?"bypass":"amplified"));
|
||||
for(int error : {0,-3}) {
|
||||
chip.rc=error; v4FrontEnd.fem.calls.clear();
|
||||
assert(benchTransmit(data,16)==error);
|
||||
assert(v4FrontEnd.fem.calls==(fem==GC1109_PA?"RXR":"TXR"));
|
||||
}
|
||||
}
|
||||
}
|
||||
'''
|
||||
self.compile_run(harness.replace('@SOURCE@',source).replace('@TX@',tx))
|
||||
|
||||
def test_all_direct_probe_transmits_use_frontend_adapter(self):
|
||||
for name in ('profile_switch_channels.h','profile_switch_packets.h','profile_preamble_diagnostic.h'):
|
||||
source=(ROOT/'tools/hil'/name).read_text()
|
||||
self.assertNotIn('chip.transmit(',source)
|
||||
self.assertIn('benchTransmit(',source)
|
||||
source=(ROOT/'tools/hil/profile_switch.cpp').read_text()
|
||||
setup=method(source,'void setup()')
|
||||
self.assertLess(setup.index('v4FrontEnd.begin()'),setup.index('chip.std_init('))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Mixed HIL channels preserve fractional BW and normal uniform defaults."""
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
from test_radio_receive_contract import method
|
||||
import test_sx1262_batched_modulation as compiler
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class MixedTests(unittest.TestCase):
|
||||
compile_run=compiler.BatchedModulationTests.compile_run
|
||||
|
||||
def test_profile_mapping_and_equal_symbols(self):
|
||||
source=(ROOT/'tools/hil/profile_switch_channels.h').read_text()
|
||||
header=(ROOT/'tools/hil/ProfileMixedChannels.h').read_text().replace('#pragma once','')
|
||||
pair_header=(ROOT/'tools/hil/ProfilePairPlan.h').read_text().replace('#pragma once','')
|
||||
self.compile_run(r'''
|
||||
#include <cassert>
|
||||
@HEADER@
|
||||
@PAIR_HEADER@
|
||||
namespace mesh { struct RadioProfileParams { float freq,bw; unsigned sf,cr,preamble; }; }
|
||||
bool channelMixed=false,channelPair=false;
|
||||
float sweepFrequency(unsigned channel){return 909.5f+channel;}
|
||||
@METHOD@
|
||||
int main(){
|
||||
for(unsigned ch=0;ch<4;++ch){
|
||||
auto uniform=sweepParams(ch,32,6,125);
|
||||
assert(uniform.sf==6&&uniform.bw==125);
|
||||
channelMixed=true;auto p=sweepParams(ch,32,10,125);channelMixed=false;
|
||||
assert(p.sf==9+ch&&p.bw==62.5f*(1u<<ch)&&p.cr==5&&p.preamble==32);
|
||||
assert((1u<<p.sf)*1000/p.bw==8192);
|
||||
}
|
||||
channelPair=true;
|
||||
auto slow=sweepParams(0,32,10,125), fast=sweepParams(1,32,10,125);
|
||||
assert(slow.sf==7&&slow.bw==62.5f&&slow.freq==909.5f);
|
||||
assert(fast.sf==8&&fast.bw==500&&fast.freq==910.5f);
|
||||
assert(slow.cr==5&&fast.cr==5&&slow.preamble==32&&fast.preamble==32);
|
||||
}
|
||||
'''.replace('@HEADER@',header).replace('@PAIR_HEADER@',pair_header)
|
||||
.replace('@METHOD@',method(source,'mesh::RadioProfileParams sweepParams(')))
|
||||
|
||||
|
||||
if __name__=='__main__': unittest.main()
|
||||
@@ -0,0 +1,70 @@
|
||||
"""Reference transmitter: cache replay never retransmits and failures stay failures."""
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
from test_radio_receive_contract import method
|
||||
import test_sx1262_batched_modulation as compiler
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class NrfReferenceTxTests(unittest.TestCase):
|
||||
compile_run=compiler.BatchedModulationTests.compile_run
|
||||
|
||||
def test_duplicate_result_replay_and_failed_setup_do_not_transmit(self):
|
||||
source=method((ROOT/'tools/hil/profile_switch_nrf52_tx.cpp').read_text(),'void referenceTransmit(')
|
||||
harness=r'''
|
||||
#include <cassert>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <cstddef>
|
||||
#define RADIOLIB_ERR_NONE 0
|
||||
#define RADIOLIB_ERR_CHIP_NOT_FOUND -2
|
||||
unsigned ticks=0;uint32_t micros(){ return ++ticks; }
|
||||
int SPI;
|
||||
unsigned channelStepKhz=250;
|
||||
float expectedFrequency=910.25f;
|
||||
float expectedBw=125;
|
||||
unsigned expectedSf=10;
|
||||
struct Result { unsigned sequence=0; } lastTxResult;
|
||||
unsigned replayed=0;
|
||||
void emitBenchResult(const Result&) { ++replayed; }
|
||||
template<class... T> void recordBenchResult(Result& r,unsigned seq,const char*,T...) { r.sequence=seq; }
|
||||
struct {
|
||||
bool init=true; unsigned sent=0; int txResult=0;
|
||||
bool std_init(int*) { return init; }
|
||||
int setFrequency(float f) { assert(f==expectedFrequency);return 0; }
|
||||
int setLoRaModulationParams(float bw,unsigned sf,unsigned cr) { assert(bw==expectedBw&&sf==expectedSf&&cr==5);return 0; }
|
||||
int setPreambleLength(unsigned p) { assert(p==32);return 0; }
|
||||
int setOutputPower(int p) { assert(p==-9);return 0; }
|
||||
int transmit(uint8_t* p,unsigned len) { assert(len==16&&!memcmp(p,"CHS1",4)&&p[8]==3);++sent;return txResult; }
|
||||
} chip;
|
||||
@METHOD@
|
||||
int main() {
|
||||
referenceTransmit(3,42,16,32,10,125);assert(chip.sent==1&&lastTxResult.sequence==42);
|
||||
referenceTransmit(3,42,16,32,10,125);assert(chip.sent==1&&replayed==1);
|
||||
chip.init=false;referenceTransmit(3,43,16,32,10,125);assert(chip.sent==1&&lastTxResult.sequence==43);
|
||||
chip.init=true;chip.txResult=-3;referenceTransmit(3,44,16,32,10,125);assert(chip.sent==2);
|
||||
referenceTransmit(3,44,16,32,10,125);assert(chip.sent==2&&replayed==2);
|
||||
channelStepKhz=1000;expectedFrequency=912.5f;chip.txResult=0;
|
||||
referenceTransmit(3,45,16,32,10,125);assert(chip.sent==3);
|
||||
channelStepKhz=250;referenceTransmit(3,45,16,32,10,125);assert(chip.sent==3&&replayed==3);
|
||||
expectedFrequency=910.25f;
|
||||
for(unsigned i=0;i<4;++i) {
|
||||
expectedSf=9+i;expectedBw=62.5f*(1u<<i);
|
||||
referenceTransmit(3,46+i,16,32,expectedSf,expectedBw);assert(chip.sent==4+i);
|
||||
}
|
||||
}
|
||||
'''
|
||||
self.compile_run(harness.replace('@METHOD@',source))
|
||||
|
||||
def test_scope_and_host_command_bounds(self):
|
||||
source=(ROOT/'tools/hil/profile_switch_nrf52_tx.cpp').read_text()
|
||||
self.assertNotIn('transmit',method(source,'void setup()'))
|
||||
loop=method(source,'void loop()')
|
||||
for guard in ('channel<4','len==16','preamble==32','sf>=5','sf<=10','bw==125','bw==250'):
|
||||
self.assertIn(guard,loop)
|
||||
self.assertIn('static bool overflow=false',loop)
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Full HIL retune repeat is real, bounded, and never overrides RX guards."""
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
from test_radio_receive_contract import method
|
||||
import test_sx1262_batched_modulation as compiler
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class RetuneRepeatTests(unittest.TestCase):
|
||||
compile_run=compiler.BatchedModulationTests.compile_run
|
||||
|
||||
def test_second_pass_refresh_and_fail_closed(self):
|
||||
body=method((ROOT/'tools/hil/profile_switch.cpp').read_text(),'mesh::RadioParamApplyResult hop(')
|
||||
self.compile_run(r'''
|
||||
#include <cassert>
|
||||
#include <cstdint>
|
||||
namespace mesh {
|
||||
enum class RadioParamApplyResult {APPLIED,BUSY,FAILED};
|
||||
struct RadioProfileParams { float freq=910.5f;uint8_t cr=5; };
|
||||
}
|
||||
using Result=mesh::RadioParamApplyResult;
|
||||
struct { uint32_t rfWord=0,modulationWord=0; } channelTrace;
|
||||
uint32_t micros(){static uint32_t t=0;return ++t;}
|
||||
struct { unsigned begins=0,ends=0;bool busyLine=false;bool isChipBusy(){return busyLine;}void beginHop(bool rx){assert(rx);++begins;}void endHop(){++ends;} } chip;
|
||||
struct Bench {
|
||||
unsigned hopPasses=1,calls=0;
|
||||
uint32_t firstPassOffsetSteps=10;
|
||||
bool firstPassDetour=false,corruptFirst=false,corruptFinal=false;
|
||||
uint32_t detourChecks=0,detourErrors=0,detourFirstRf=0,detourFinalRf=0,detourFirstMod=0,detourFinalMod=0;
|
||||
struct Profiles {
|
||||
mesh::RadioProfileParams primary;
|
||||
struct Secondary { mesh::RadioProfileParams params; } secondary;
|
||||
const mesh::RadioProfileParams& params(uint8_t target){return target?secondary.params:primary;}
|
||||
void setPrimary(const mesh::RadioProfileParams& p,bool){primary=p;}
|
||||
void setSecondary(const Secondary& p,bool){secondary=p;}
|
||||
} _profiles;
|
||||
uint32_t lastFirstPassUs=0,lastSecondPassUs=0,secondPassBlocked=0;
|
||||
bool _profile_refresh_required=false;
|
||||
Result first=Result::APPLIED,second=Result::APPLIED;
|
||||
bool isInRecvMode(){return true;}
|
||||
Result tuneProfile(uint8_t target){
|
||||
assert(target<=1);++calls;if(calls==2)assert(_profile_refresh_required);
|
||||
const auto& p=_profiles.params(target);
|
||||
assert(p.freq==910.5f);
|
||||
assert(p.cr==(firstPassDetour&&calls==1?6:5));
|
||||
Result r=calls==1?first:second;
|
||||
if(r==Result::APPLIED){
|
||||
channelTrace.rfWord=uint32_t(double(p.freq)*1048576.0)+(firstPassDetour&&calls==1?firstPassOffsetSteps:0);
|
||||
channelTrace.modulationWord=p.cr==6?0x0a040200:0x0a040100;
|
||||
if((calls==1&&corruptFirst)||(calls==2&&corruptFinal))channelTrace.modulationWord^=0x100;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
@METHOD@
|
||||
};
|
||||
int main(){
|
||||
Bench one;assert(one.hop(1)==Result::APPLIED&&one.calls==1&&one.lastSecondPassUs==0);
|
||||
Bench two;two.hopPasses=2;assert(two.hop(1)==Result::APPLIED&&two.calls==2&&two.lastSecondPassUs>0);
|
||||
Bench busy;busy.hopPasses=2;busy.first=Result::BUSY;assert(busy.hop(1)==Result::BUSY&&busy.calls==1);
|
||||
Bench failed;failed.hopPasses=2;failed.first=Result::FAILED;assert(failed.hop(1)==Result::FAILED&&failed.calls==1);
|
||||
Bench mid;mid.hopPasses=2;mid.second=Result::BUSY;assert(mid.hop(1)==Result::FAILED&&mid.calls==2&&mid.secondPassBlocked==1);
|
||||
Bench end;end.hopPasses=2;end.second=Result::FAILED;assert(end.hop(1)==Result::FAILED&&end.calls==2);
|
||||
Bench stalled;stalled.hopPasses=2;chip.busyLine=true;assert(stalled.hop(1)==Result::FAILED&&stalled.calls==1);
|
||||
chip.busyLine=false;
|
||||
for(unsigned target=0;target<2;++target){
|
||||
Bench detour;detour.hopPasses=2;detour.firstPassDetour=true;
|
||||
assert(detour.hop(target)==Result::APPLIED&&detour.calls==2&&detour.detourChecks==1&&detour.detourErrors==0);
|
||||
assert(detour._profiles.params(target).freq==910.5f&&detour._profiles.params(target).cr==5);
|
||||
Bench hundred;hundred.hopPasses=2;hundred.firstPassDetour=true;hundred.firstPassOffsetSteps=105;
|
||||
assert(hundred.hop(target)==Result::APPLIED&&hundred.detourChecks==1&&hundred.detourErrors==0);
|
||||
assert(hundred.detourFirstRf-hundred.detourFinalRf==105);
|
||||
Bench deferred;deferred.hopPasses=2;deferred.firstPassDetour=true;deferred.first=Result::BUSY;
|
||||
assert(deferred.hop(target)==Result::BUSY&&deferred.calls==1);
|
||||
assert(deferred._profiles.params(target).freq==910.5f&&deferred._profiles.params(target).cr==5);
|
||||
Bench between;between.hopPasses=2;between.firstPassDetour=true;between.second=Result::BUSY;
|
||||
assert(between.hop(target)==Result::FAILED&&between.secondPassBlocked==1);
|
||||
assert(between._profiles.params(target).freq==910.5f&&between._profiles.params(target).cr==5);
|
||||
for(unsigned pass=0;pass<2;++pass){
|
||||
Bench bad;bad.hopPasses=2;bad.firstPassDetour=true;bad.corruptFirst=pass==0;bad.corruptFinal=pass==1;
|
||||
assert(bad.hop(target)==Result::FAILED&&bad.detourErrors==1);
|
||||
}
|
||||
}
|
||||
assert(chip.begins==chip.ends);
|
||||
}
|
||||
'''.replace('@METHOD@',body))
|
||||
|
||||
def test_complete_settings_are_not_skipped_by_modulation_cache(self):
|
||||
source=(ROOT/'tools/hil/profile_switch.cpp').read_text()
|
||||
self.assertIn('forceModulationWrite || hopPasses==2',method(source,'void beginProfileRetune('))
|
||||
self.assertIn('chip.hilInvalidateModulation()',method(source,'void beginProfileRetune('))
|
||||
|
||||
|
||||
if __name__=='__main__': unittest.main()
|
||||
@@ -0,0 +1,40 @@
|
||||
"""HIL rollback preserves production ownership and ordinary standby semantics."""
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
from test_radio_receive_contract import method
|
||||
import test_sx1262_batched_modulation as compiler
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class RollbackTests(unittest.TestCase):
|
||||
compile_run=compiler.BatchedModulationTests.compile_run
|
||||
|
||||
def test_warm_rollback_only_suppresses_request(self):
|
||||
source=(ROOT/'tools/hil/profile_switch.cpp').read_text()
|
||||
body=method(source,'void setProfileStandbyWarm(')
|
||||
self.compile_run(r'''
|
||||
#include <cassert>
|
||||
struct CustomSX1262Wrapper { bool requested=false;virtual void setProfileStandbyWarm(bool v){requested=v;} };
|
||||
struct Bench:CustomSX1262Wrapper { bool warmStandby=true; @METHOD@ };
|
||||
int main(){for(bool policy:{false,true})for(bool request:{false,true}){
|
||||
Bench b;b.warmStandby=policy;b.setProfileStandbyWarm(request);assert(b.requested==(policy&&request));
|
||||
}}
|
||||
'''.replace('#include <cassert>','#include <cassert>\n#include <initializer_list>').replace('@METHOD@',body))
|
||||
|
||||
def test_rollback_never_bypasses_hop_ownership_or_busy_checks(self):
|
||||
source=(ROOT/'tools/hil/profile_switch_channels.h').read_text()
|
||||
start=method(source,'void startChannelSweep(')
|
||||
for control in ('(channelRollback & 9)==0','(channelRollback & 4)==0',
|
||||
'(channelRollback & 2)==0','(channelRollback & 8)==0'):
|
||||
self.assertIn(control,start)
|
||||
service=method(source,'void serviceChannelSweep(')
|
||||
self.assertIn('driver.hop(slot)',service)
|
||||
self.assertIn('rc==mesh::RadioParamApplyResult::BUSY',service)
|
||||
self.assertIn('!waitBusy()',service)
|
||||
self.assertIn('rfWordAtRead=channelTrace.rfWord',service)
|
||||
self.assertIn('payloadValid && bytes[8]==channelSweep.current',service)
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Stationary baseline payload integrity and separation from the hop scheduler."""
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
from test_radio_receive_contract import method
|
||||
import test_sx1262_batched_modulation as compiler
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class StationaryBaselineTests(unittest.TestCase):
|
||||
compile_run = compiler.BatchedModulationTests.compile_run
|
||||
|
||||
def test_complete_payload_identity(self):
|
||||
source = (ROOT / 'tools/hil/profile_stationary_baseline.h').read_text()
|
||||
self.compile_run(r'''
|
||||
#include <cassert>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
@METHOD@
|
||||
int main() {
|
||||
uint8_t bytes[16]; uint32_t seq=123;
|
||||
memcpy(bytes,"CHS1",4);memcpy(bytes+4,&seq,4);bytes[8]=3;
|
||||
for(unsigned i=9;i<16;++i) bytes[i]=uint8_t(i^seq);
|
||||
assert(stationaryPayloadMatches(bytes,16,123,3));
|
||||
assert(!stationaryPayloadMatches(bytes,15,123,3));
|
||||
assert(!stationaryPayloadMatches(bytes,16,124,3));
|
||||
assert(!stationaryPayloadMatches(bytes,16,123,2));
|
||||
for(unsigned i=0;i<16;++i) {
|
||||
bytes[i]^=1;assert(!stationaryPayloadMatches(bytes,16,123,3));bytes[i]^=1;
|
||||
}
|
||||
}
|
||||
'''.replace('@METHOD@', method(source, 'bool stationaryPayloadMatches(')))
|
||||
|
||||
def test_no_retuning_or_rf_transmission_after_setup(self):
|
||||
source = (ROOT / 'tools/hil/profile_stationary_baseline.h').read_text()
|
||||
self.assertNotIn('transmit(', source)
|
||||
for signature in ('void expectStationaryPacket(', 'void serviceStationaryBaseline('):
|
||||
body = method(source, signature)
|
||||
for forbidden in ('setFrequency(', 'std_init(', 'prepareDiagnosticRadio(', 'driver.hop('):
|
||||
self.assertNotIn(forbidden, body)
|
||||
self.assertIn('stationaryBaseline.rfStart=channelTrace.rfWrites', source)
|
||||
self.assertIn('millis()+600000', source)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -41,6 +41,8 @@ struct SX1262 {
|
||||
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 setFrequency(float) { return call('F'); }
|
||||
int16_t setFrequency(float,bool) { return call('F'); }
|
||||
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'); }
|
||||
@@ -104,10 +106,12 @@ int main() {
|
||||
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", "")
|
||||
offset = (ROOT / "tools/hil/ProfileFrequencyOffset.h").read_text().replace("#pragma once", "")
|
||||
harness = r'''
|
||||
#include <cassert>
|
||||
#include <cstdint>
|
||||
#include <cstddef>
|
||||
@OFFSET@
|
||||
struct Spi {
|
||||
unsigned bulk=0;
|
||||
void transferBytes(uint8_t* out,uint8_t* in,size_t n) {
|
||||
@@ -144,9 +148,17 @@ int main() {
|
||||
assert(h.fallback==unsigned(!bulk) && h.device.bulk==unsigned(bulk));
|
||||
}
|
||||
assert(channelTrace.calls==520);
|
||||
for(int bulk=0;bulk<2;++bulk) {
|
||||
Hal h;h.bulkTransfer=bulk;
|
||||
uint8_t out[5]={0x86,0x38,0xd8,0,0},in[5]={};
|
||||
{ HilFrequencyOffsetScope offset(10);h.spiTransfer(out,5,in); }
|
||||
assert(out[4]==0 && in[4]==(10^0xa5)); // actual transmitted and observed byte
|
||||
h.spiTransfer(out,5,in);
|
||||
assert(in[4]==0xa5); // second/corrected pass has the original RF word
|
||||
}
|
||||
}
|
||||
'''
|
||||
self.compile_run(harness.replace("@OP@", operation))
|
||||
self.compile_run(harness.replace("@OP@", operation).replace("@OFFSET@", offset))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -32,7 +32,8 @@ int main() {
|
||||
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);
|
||||
Serial.output.clear();
|
||||
recordBenchResult(lastTxResult,43,"%0*d",int(sizeof(lastTxResult.text)),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);
|
||||
|
||||
@@ -31,6 +31,7 @@ class BatchedModulationTests(unittest.TestCase):
|
||||
#include <cstdint>
|
||||
#include <cstddef>
|
||||
#include <initializer_list>
|
||||
@STATE@
|
||||
using std::isfinite;
|
||||
#define RADIOLIB_ERR_NONE 0
|
||||
#define RADIOLIB_ERR_INVALID_SPREADING_FACTOR -1
|
||||
@@ -49,6 +50,7 @@ using std::isfinite;
|
||||
#define RADIOLIB_SX126X_LORA_BW_250_0 0x05
|
||||
#define RADIOLIB_SX126X_LORA_BW_500_0 0x06
|
||||
struct Radio {
|
||||
SX1262ProfileSwitchState _profileSwitch{true};
|
||||
uint8_t spreadingFactor=9, bandwidth=4, codingRate=3, ldrOptimize=0;
|
||||
float bandwidthKhz=125;
|
||||
bool ldroAuto=true;
|
||||
@@ -72,6 +74,12 @@ bool sameCache(const Radio& a,const Radio& b) {
|
||||
&& a.bandwidthKhz==b.bandwidthKhz && a.codingRate==b.codingRate
|
||||
&& a.ldrOptimize==b.ldrOptimize && a.ldroAuto==b.ldroAuto;
|
||||
}
|
||||
void beginHop(Radio& r) {
|
||||
r._profileSwitch.end(true);
|
||||
r._profileSwitch.rxResult(0,true);
|
||||
r._profileSwitch.begin(true,true);
|
||||
r._profileSwitch.standbyResult(0);
|
||||
}
|
||||
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};
|
||||
@@ -85,7 +93,55 @@ int main() {
|
||||
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);
|
||||
// Only a subsequent owned RX hop may reuse that acknowledged tuple.
|
||||
beginHop(r);
|
||||
assert(r.setLoRaModulationParams(bandwidths[i],sf,cr)==0);
|
||||
assert(r.queries==2 && r.writes==1);
|
||||
assert(r._profileSwitch.matchesModulation(sf,codes[i],cr-4,ldro));
|
||||
}
|
||||
{
|
||||
Radio r;beginHop(r);
|
||||
// Initially matching software fields are not proof of programmed hardware.
|
||||
assert(r.setLoRaModulationParams(125,9,7)==0 && r.writes==1);
|
||||
beginHop(r);assert(r.setLoRaModulationParams(125,9,7)==0 && r.writes==1);
|
||||
// Change each effective field independently, then verify repeat is skipped.
|
||||
assert(r.setLoRaModulationParams(250,9,7)==0 && r.writes==2);
|
||||
assert(r.setLoRaModulationParams(250,10,7)==0 && r.writes==3);
|
||||
assert(r.setLoRaModulationParams(250,10,5)==0 && r.writes==4);
|
||||
assert(r.setLoRaModulationParams(250,10,5)==0 && r.writes==4);
|
||||
r.ldroAuto=false;r.ldrOptimize=1;
|
||||
assert(r.setLoRaModulationParams(250,10,5)==0 && r.writes==5);
|
||||
assert(r.setLoRaModulationParams(250,10,5)==0 && r.writes==5);
|
||||
// autoLDRO() itself does not write: the next hop must apply its new value.
|
||||
r.ldroAuto=true;
|
||||
assert(r.setLoRaModulationParams(250,10,5)==0 && r.writes==6);
|
||||
r.ldroAuto=false;
|
||||
assert(r.setLoRaModulationParams(250,10,5)==0 && r.writes==6);
|
||||
r.ldroAuto=true;
|
||||
assert(r.setLoRaModulationParams(125,11,5)==0 && r.writes==7 && r.ldrOptimize==1);
|
||||
assert(r.setLoRaModulationParams(125,11,5)==0 && r.writes==7);
|
||||
// A failed changed tuple revokes reuse before physical rollback.
|
||||
r.result=-707;assert(r.setLoRaModulationParams(500,8,5)==-707);
|
||||
assert(!r._profileSwitch.modulationValid && r._profileSwitch.failed());
|
||||
r.result=0;beginHop(r);
|
||||
assert(r.setLoRaModulationParams(125,11,5)==0 && r.writes==9);
|
||||
assert(r.setLoRaModulationParams(125,11,5)==0 && r.writes==9);
|
||||
r.packetType=255;assert(r.setLoRaModulationParams(125,11,5)==-4);
|
||||
assert(!r._profileSwitch.modulationValid);
|
||||
r.packetType=1;assert(r.setLoRaModulationParams(125,11,5)==0 && r.writes==10);
|
||||
}
|
||||
for(int gate=0;gate<6;++gate) {
|
||||
Radio r;beginHop(r);assert(r.setLoRaModulationParams(125,9,7)==0);
|
||||
switch(gate) {
|
||||
case 0:r._profileSwitch.end(true);break; // no owned window
|
||||
case 1:r._profileSwitch.begin(true,true);break; // no standby yet
|
||||
case 2:r._profileSwitch.begin(false,true);break; // not continuous RX
|
||||
case 3:r._profileSwitch.begin(true,false);break; // cold oscillator
|
||||
case 4:r._profileSwitch.enabled=false;r._profileSwitch.begin(true,true);break;
|
||||
case 5:r._profileSwitch.invalidate();beginHop(r);break; // state lost
|
||||
}
|
||||
assert(r.setLoRaModulationParams(125,9,7)==0 && r.writes==2);
|
||||
}
|
||||
// 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);
|
||||
@@ -114,7 +170,51 @@ int main() {
|
||||
}
|
||||
}
|
||||
'''
|
||||
self.compile_run(harness.replace("@PRODUCTION@", production))
|
||||
state = (ROOT / "src/helpers/radiolib/SX1262ProfileSwitchState.h").read_text().replace("#pragma once", "")
|
||||
self.compile_run(harness.replace("@PRODUCTION@", production).replace("@STATE@", state))
|
||||
|
||||
def test_ordinary_setters_invalidate_acknowledged_tuple_even_on_failure(self):
|
||||
source = (ROOT / "src/helpers/radiolib/CustomSX1262.h").read_text()
|
||||
signatures = ("int16_t setBandwidth(", "int16_t setSpreadingFactor(",
|
||||
"int16_t setCodingRate(", "int16_t forceLDRO(")
|
||||
methods = "\n".join(method(source, signature) for signature in signatures)
|
||||
state = (ROOT / "src/helpers/radiolib/SX1262ProfileSwitchState.h").read_text().replace("#pragma once", "")
|
||||
harness = r'''
|
||||
#include <cassert>
|
||||
#include <cstdint>
|
||||
@STATE@
|
||||
struct SX1262 {
|
||||
int16_t result=0;unsigned calls=0;bool interleave=false;
|
||||
virtual ~SX1262()=default;
|
||||
virtual int16_t setBandwidth(float bw) { assert(bw==125);++calls;return result; }
|
||||
virtual int16_t setSpreadingFactor(uint8_t sf) { assert(sf==9);++calls;return result; }
|
||||
int16_t setCodingRate(uint8_t cr,bool li) { assert(cr==7);interleave=li;++calls;return result; }
|
||||
int16_t forceLDRO(bool enabled) { assert(enabled);++calls;return result; }
|
||||
};
|
||||
struct Radio: SX1262 {
|
||||
SX1262ProfileSwitchState _profileSwitch{true};
|
||||
@METHODS@
|
||||
};
|
||||
int main() {
|
||||
for(int setter=0;setter<5;++setter) for(int failure=0;failure<2;++failure) {
|
||||
Radio r;r.result=failure ? -707:0;
|
||||
r._profileSwitch.rxResult(0,true);r._profileSwitch.begin(true,true);
|
||||
r._profileSwitch.standbyResult(0);r._profileSwitch.modulationResult(0,9,4,3,0);
|
||||
assert(r._profileSwitch.matchesModulation(9,4,3,0));
|
||||
SX1262& base=r;int16_t rc=0;
|
||||
switch(setter) {
|
||||
case 0:rc=base.setBandwidth(125);break;
|
||||
case 1:rc=base.setSpreadingFactor(9);break;
|
||||
case 2:rc=r.setCodingRate(7);assert(!r.interleave);break;
|
||||
case 3:rc=r.setCodingRate(7,true);assert(r.interleave);break;
|
||||
case 4:rc=r.forceLDRO(true);break;
|
||||
}
|
||||
assert(rc==r.result && r.calls==1 && !r._profileSwitch.modulationValid);
|
||||
assert(!r._profileSwitch.matchesModulation(9,4,3,0));
|
||||
}
|
||||
}
|
||||
'''
|
||||
self.compile_run(harness.replace("@STATE@", state).replace("@METHODS@", methods))
|
||||
|
||||
def test_wrapper_batches_once_and_preserves_failure_short_circuit(self):
|
||||
source = (ROOT / "src/helpers/radiolib/CustomSX1262Wrapper.h").read_text()
|
||||
|
||||
@@ -89,13 +89,17 @@ void prime(Radio& r) {
|
||||
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.modulationValid); // full RX setup does not prime a tuple
|
||||
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();
|
||||
r._profileSwitch.modulationResult(0,8,4,1,0);
|
||||
assert(r._profileSwitch.matchesModulation(8,4,1,0));
|
||||
assert(r.setPreambleLength(120)==0 && r.trace.empty());
|
||||
assert(r.startReceive()==0 && r.trace=="CPWR");
|
||||
assert(r.stagedMode==0 && r._profileSwitch.rxValid);
|
||||
assert(r._profileSwitch.modulationValid); // successful fast resume preserves it
|
||||
r.endProfileSwitch(true);assert(!r._profileSwitch.open);r.trace.clear();
|
||||
}
|
||||
int main() {
|
||||
@@ -108,6 +112,7 @@ int main() {
|
||||
// Ordinary standby, mode staging (TX/CAD), sleep, reset and RXPS revoke RX.
|
||||
for(int event=0;event<7;++event) {
|
||||
Radio x;prime(x);
|
||||
x._profileSwitch.modulationResult(0,8,4,1,0);
|
||||
switch(event) {
|
||||
case 0:x.standby();break;
|
||||
case 1:x.standby(uint8_t(0));break;
|
||||
@@ -117,7 +122,8 @@ int main() {
|
||||
case 5:x.reset();break;
|
||||
case 6:x.startReceiveDutyCycle(1000,1000);break;
|
||||
}
|
||||
assert(!x._profileSwitch.rxValid);x.trace.clear();x.beginProfileSwitch(true);
|
||||
assert(!x._profileSwitch.rxValid && !x._profileSwitch.modulationValid);
|
||||
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);
|
||||
|
||||
Reference in new issue
Block a user