Reduce Indicator radio expander traffic with guarded IQ reuse
This commit is contained in:
1 parent
5cf42d0ca1
commit
64a928d18f
14 files changed
+851
-40
No files matched your search
@@ -0,0 +1,188 @@
|
||||
"""Compile the actual Indicator HAL against an error-injectable I2C device."""
|
||||
from pathlib import Path
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class IndicatorRadioHalTest(unittest.TestCase):
|
||||
def test_port_zero_transactions_fresh_busy_and_shared_irq_errors(self):
|
||||
arduino = r'''
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
#include <cstddef>
|
||||
constexpr uint32_t RADIOLIB_NC = 0xffffffff;
|
||||
constexpr int LOW=0, HIGH=1, INPUT_PULLUP=2;
|
||||
constexpr int PIN_BOARD_SDA=39, PIN_BOARD_SCL=40, P_LORA_BUSY=66;
|
||||
extern int nativeLevel, nativeWrites, nativeModes;
|
||||
inline void pinMode(uint32_t, uint32_t) { ++nativeModes; }
|
||||
inline int digitalRead(uint32_t) { return nativeLevel; }
|
||||
'''
|
||||
buffered = r'''
|
||||
#pragma once
|
||||
#include <Arduino.h>
|
||||
#include <SPI.h>
|
||||
struct ArduinoHal {
|
||||
enum { GpioModeOutput=1, GpioModeInput=0, GpioLevelLow=0, GpioLevelHigh=1,
|
||||
GpioInterruptRising=2, GpioInterruptFalling=3 };
|
||||
virtual ~ArduinoHal() = default;
|
||||
virtual void pinMode(uint32_t, uint32_t) { ++nativeModes; }
|
||||
virtual void digitalWrite(uint32_t, uint32_t) { ++nativeWrites; }
|
||||
virtual uint32_t digitalRead(uint32_t) { return nativeLevel; }
|
||||
virtual void attachInterrupt(uint32_t, void (*)(), uint32_t) {}
|
||||
virtual void detachInterrupt(uint32_t) {}
|
||||
virtual uint32_t pinToInterrupt(uint32_t pin) { return pin + 100; }
|
||||
};
|
||||
struct ESP32BufferedRadioHal : ArduinoHal {
|
||||
explicit ESP32BufferedRadioHal(SPIClass&) {}
|
||||
};
|
||||
constexpr uint32_t RISING = ArduinoHal::GpioInterruptRising;
|
||||
'''
|
||||
gfx = r'''
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
#include <cstddef>
|
||||
namespace lgfx { namespace i2c {
|
||||
struct Result { bool ok; bool has_value() const { return ok; } };
|
||||
Result readRegister(uint8_t, uint8_t, uint8_t, uint8_t*, size_t, uint32_t);
|
||||
Result transactionWrite(uint8_t, uint8_t, const uint8_t*, size_t, uint32_t);
|
||||
Result init(uint8_t, uint8_t, uint8_t);
|
||||
} }
|
||||
'''
|
||||
fixture = r'''
|
||||
#include <cassert>
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
#include "@ROOT@/variants/sensecap_indicator-espnow/IndicatorRadioHal.cpp"
|
||||
int nativeLevel=HIGH, nativeWrites=0, nativeModes=0;
|
||||
uint8_t registers[8] = {0,0,0xff,0xff,0,0,0xff,0xff};
|
||||
struct Transfer { bool write; uint8_t reg; size_t size; };
|
||||
std::vector<Transfer> transfers;
|
||||
bool failRead=false, failWrite=false, failInit=false;
|
||||
unsigned callbacks=0, inits=0;
|
||||
void irq() { ++callbacks; }
|
||||
namespace lgfx { namespace i2c {
|
||||
Result readRegister(uint8_t port,uint8_t address,uint8_t reg,uint8_t* data,
|
||||
size_t size,uint32_t frequency) {
|
||||
assert(port==0 && address==0x20 && frequency==400000);
|
||||
assert((size==1 || size==2) && reg+size<=8);
|
||||
transfers.push_back({false,reg,size});
|
||||
if(failRead) return {false};
|
||||
std::copy(registers+reg,registers+reg+size,data);return {true};
|
||||
}
|
||||
Result transactionWrite(uint8_t port,uint8_t address,const uint8_t* data,
|
||||
size_t size,uint32_t frequency) {
|
||||
assert(port==0 && address==0x20 && frequency==400000);
|
||||
assert((size==2 || size==3) && data[0]+size-1<=8);
|
||||
transfers.push_back({true,data[0],size});
|
||||
if(failWrite) return {false};
|
||||
std::copy(data+1,data+size,registers+data[0]);return {true};
|
||||
}
|
||||
Result init(uint8_t port,uint8_t sda,uint8_t scl) {
|
||||
assert(port==0 && sda==39 && scl==40);++inits;return {!failInit};
|
||||
}
|
||||
} }
|
||||
void last(bool write,uint8_t reg,size_t size) {
|
||||
assert(!transfers.empty());auto t=transfers.back();
|
||||
assert(t.write==write && t.reg==reg && t.size==size);
|
||||
}
|
||||
int main() {
|
||||
SPIClass spi;IndicatorRadioHal hal(spi);
|
||||
assert(hal.beginExpander() && transfers.size()==3);
|
||||
for(auto t:transfers) assert(!t.write && t.size==2);
|
||||
assert(hal.beginExpander() && transfers.size()==3);
|
||||
|
||||
// Low-bank pin updates send only that bank, leaving unrelated Port 1 alone.
|
||||
registers[7]=0x5a;
|
||||
hal.pinMode(64,ArduinoHal::GpioModeOutput);last(true,6,2);
|
||||
assert(registers[6]==0xfe && registers[7]==0x5a);
|
||||
registers[3]=0x5a;
|
||||
hal.digitalWrite(64,ArduinoHal::GpioLevelLow);last(true,2,2);
|
||||
assert(registers[2]==0xfe && registers[3]==0x5a);
|
||||
size_t count=transfers.size();hal.digitalWrite(64,0);
|
||||
assert(transfers.size()==count); // unchanged latch still needs no write
|
||||
|
||||
// Failed writes must not poison the software shadow or suppress the retry.
|
||||
failWrite=true;hal.digitalWrite(64,1);last(true,2,2);
|
||||
assert(registers[2]==0xfe);failWrite=false;
|
||||
hal.digitalWrite(64,1);assert(registers[2]==0xff);
|
||||
failWrite=true;hal.pinMode(65,ArduinoHal::GpioModeOutput);
|
||||
assert(registers[6]==0xfe);failWrite=false;
|
||||
hal.pinMode(65,ArduinoHal::GpioModeOutput);assert(registers[6]==0xfc);
|
||||
|
||||
// Preserve generic Port 1 support and its original whole-word transactions.
|
||||
hal.digitalWrite(72,0);last(true,2,3);assert(registers[3]==0xfe);
|
||||
hal.pinMode(72,ArduinoHal::GpioModeOutput);last(true,6,3);
|
||||
registers[1]=1;assert(hal.digitalRead(72)==1);last(false,0,2);
|
||||
|
||||
// BUSY must be read over I2C every time, even with expander INT inactive.
|
||||
nativeLevel=HIGH;registers[0]=4;
|
||||
assert(hal.digitalRead(66)==1);last(false,0,1);
|
||||
count=transfers.size();registers[0]=0;
|
||||
assert(hal.digitalRead(66)==0 && transfers.size()==count+1);last(false,0,1);
|
||||
#ifdef MC_SX1262_HIL
|
||||
// Only HIL can restore the old two-bank bus-width control in this image.
|
||||
hal.hilUsePort0Only=false;
|
||||
assert(hal.digitalRead(66)==0);last(false,0,2);
|
||||
hal.digitalWrite(64,0);last(true,2,3);
|
||||
hal.pinMode(65,ArduinoHal::GpioModeInput);last(true,6,3);
|
||||
hal.hilUsePort0Only=true;
|
||||
assert(hal.digitalRead(66)==0);last(false,0,1);
|
||||
hal.digitalWrite(64,1);last(true,2,2);
|
||||
hal.pinMode(65,ArduinoHal::GpioModeOutput);last(true,6,2);
|
||||
#endif
|
||||
failRead=true;assert(hal.digitalRead(66)==1 && hal.digitalRead(67)==0);
|
||||
failRead=false;
|
||||
|
||||
// IRQ service still reads BOTH banks, clearing all shared expander sources.
|
||||
hal.attachInterrupt(67,irq,ArduinoHal::GpioInterruptRising);last(false,0,2);
|
||||
registers[0]=8;nativeLevel=LOW;
|
||||
hal.serviceInterrupt();last(false,0,2);assert(callbacks==1);
|
||||
hal.serviceInterrupt();assert(callbacks==1);
|
||||
registers[0]=0;assert(hal.digitalRead(66)==0);assert(callbacks==1);
|
||||
failRead=true;registers[0]=8;hal.serviceInterrupt();assert(callbacks==1);
|
||||
failRead=false;hal.serviceInterrupt();assert(callbacks==2);
|
||||
hal.detachInterrupt(67);count=transfers.size();hal.serviceInterrupt();
|
||||
assert(count==transfers.size());
|
||||
|
||||
// Native and invalid pins do not accidentally address the expander.
|
||||
count=transfers.size();hal.digitalWrite(5,1);hal.pinMode(5,1);
|
||||
assert(hal.digitalRead(5)==LOW && nativeWrites==1);
|
||||
assert(hal.pinToInterrupt(5)==105 && hal.pinToInterrupt(67)==67);
|
||||
assert(hal.digitalRead(80)==0);hal.digitalWrite(80,1);hal.pinMode(80,1);
|
||||
assert(count==transfers.size());
|
||||
|
||||
// Initial bus recovery remains whole-word and fails closed when unavailable.
|
||||
IndicatorRadioHal failed(spi);failRead=true;
|
||||
assert(!failed.beginExpander() && inits==1);
|
||||
assert(failed.digitalRead(66)==1);failRead=false;
|
||||
assert(failed.beginExpander());
|
||||
}
|
||||
'''.replace("@ROOT@", str(ROOT))
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
base = Path(folder)
|
||||
(base / "helpers/radiolib").mkdir(parents=True)
|
||||
(base / "Arduino.h").write_text(arduino)
|
||||
(base / "SPI.h").write_text("#pragma once\nstruct SPIClass {};\n")
|
||||
(base / "LovyanGFX.hpp").write_text(gfx)
|
||||
(base / "helpers/radiolib/ESP32BufferedRadioHal.h").write_text(buffered)
|
||||
source, binary = base / "fixture.cpp", base / "fixture"
|
||||
source.write_text(fixture)
|
||||
for definitions in ([], ["-DMC_SX1262_HIL"]):
|
||||
with self.subTest(definitions=definitions):
|
||||
built = subprocess.run([os.environ.get("CXX", "g++"), "-std=c++17",
|
||||
"-Wall", "-Wextra", "-Werror", "-fsanitize=address,undefined",
|
||||
"-fno-omit-frame-pointer", "-no-pie", "-DSENSECAP_INDICATOR_LORA",
|
||||
*definitions, "-I", str(base), str(source), "-o", str(binary)],
|
||||
capture_output=True, text=True)
|
||||
self.assertEqual(built.returncode, 0, built.stderr)
|
||||
ran = subprocess.run([str(binary)], capture_output=True, text=True)
|
||||
self.assertEqual(ran.returncode, 0, ran.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,161 @@
|
||||
"""Execute HIL fast-policy parsing/admission without touching radio hardware."""
|
||||
from pathlib import Path
|
||||
import configparser
|
||||
import re
|
||||
import unittest
|
||||
|
||||
import test_sx1262_batched_modulation as compiler
|
||||
import test_radio_profile_clock as clock
|
||||
from test_radio_receive_contract import method
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class ProfileFastPolicyTest(unittest.TestCase):
|
||||
compile_run = compiler.BatchedModulationTests.compile_run
|
||||
|
||||
def test_hil_radiolib_matches_current_production_dependency(self):
|
||||
config = configparser.ConfigParser(interpolation=None, strict=False,
|
||||
inline_comment_prefixes=(";",))
|
||||
config.read([ROOT / "platformio.ini", ROOT / "tools/hil/profile_switch.ini"])
|
||||
|
||||
def resolve(section, option, depth=0):
|
||||
self.assertLess(depth, 30, "recursive HIL recipe interpolation")
|
||||
text = config.get(section, option)
|
||||
return re.sub(r"\$\{([^}]+)\}", lambda match:
|
||||
resolve(*match[1].split(".", 1), depth + 1), text)
|
||||
|
||||
pattern = r"https://github\.com/jgromes/RadioLib\.git#[0-9a-f]{40}"
|
||||
production = re.findall(pattern, resolve("arduino_base", "lib_deps"))
|
||||
self.assertEqual(len(production), 1)
|
||||
environments = [section for section in config.sections()
|
||||
if section.startswith("env:profile_switch_")]
|
||||
self.assertGreaterEqual(len(environments), 6)
|
||||
for section in environments:
|
||||
with self.subTest(environment=section):
|
||||
self.assertEqual(re.findall(pattern, resolve(section, "lib_deps")), production)
|
||||
|
||||
def test_policy_selection_is_exact_and_quiet_receiver_only(self):
|
||||
source = (ROOT / "tools/hil/profile_switch.cpp").read_text()
|
||||
policy = method(source, "bool selectProfileFastPolicy(")
|
||||
fixture = r'''
|
||||
#include <cassert>
|
||||
#include <cstdarg>
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
struct { bool active=false; } stationaryBaseline,preambleDiagnostic,channelSweep;
|
||||
bool packetListening=false;
|
||||
struct { bool hilUseFsOnRetune=false,hilSkipUnchangedPacket=false,hilSkipUnchangedIq=false; } chip;
|
||||
struct { bool hilUsePort0Only=true; } radioHal;
|
||||
struct SerialMock {
|
||||
std::string text;
|
||||
void println(const char* s) { text=s; }
|
||||
void printf(const char* format,...) {
|
||||
char bytes[256];va_list args;va_start(args,format);
|
||||
vsnprintf(bytes,sizeof(bytes),format,args);va_end(args);text=bytes;
|
||||
}
|
||||
} Serial;
|
||||
@POLICY@
|
||||
int main() {
|
||||
assert(selectProfileFastPolicy("fs 1") && chip.hilUseFsOnRetune);
|
||||
assert(Serial.text=="{\"fs\":true}\n");
|
||||
assert(selectProfileFastPolicy("packetcache 1") && chip.hilSkipUnchangedPacket);
|
||||
assert(Serial.text=="{\"packet_cache\":true}\n");
|
||||
assert(selectProfileFastPolicy("fs 0") && !chip.hilUseFsOnRetune);
|
||||
assert(chip.hilSkipUnchangedPacket);
|
||||
for(const char* invalid:{"fs 2","fs -1","fs 1 junk","fs 1 0","fs",
|
||||
"packetcache 2","packetcache 1 junk","packetcache", "info"}) {
|
||||
Serial.text.clear();assert(!selectProfileFastPolicy(invalid));
|
||||
assert(Serial.text.empty() && !chip.hilUseFsOnRetune && chip.hilSkipUnchangedPacket);
|
||||
}
|
||||
bool* guards[]={&packetListening,&stationaryBaseline.active,
|
||||
&preambleDiagnostic.active,&channelSweep.active};
|
||||
for(bool* guard:guards) {
|
||||
*guard=true;
|
||||
assert(selectProfileFastPolicy("fs 1") && !chip.hilUseFsOnRetune);
|
||||
assert(Serial.text.find("error")!=std::string::npos);
|
||||
assert(selectProfileFastPolicy("packetcache 0") && chip.hilSkipUnchangedPacket);
|
||||
assert(Serial.text.find("error")!=std::string::npos);
|
||||
*guard=false;
|
||||
}
|
||||
assert(selectProfileFastPolicy("packetcache 0") && !chip.hilSkipUnchangedPacket);
|
||||
assert(selectProfileFastPolicy("iqcache 1") && chip.hilSkipUnchangedIq);
|
||||
assert(Serial.text=="{\"iq_cache\":true}\n");
|
||||
for(bool* guard:guards) {
|
||||
*guard=true;assert(selectProfileFastPolicy("iqcache 0"));
|
||||
assert(chip.hilSkipUnchangedIq && Serial.text.find("error")!=std::string::npos);
|
||||
*guard=false;
|
||||
}
|
||||
assert(selectProfileFastPolicy("iqcache 0") && !chip.hilSkipUnchangedIq);
|
||||
for(const char* invalid:{"iqcache 2","iqcache -1","iqcache 1 junk","iqcache"})
|
||||
assert(!selectProfileFastPolicy(invalid) && !chip.hilSkipUnchangedIq);
|
||||
#ifdef HIL_INDICATOR
|
||||
assert(selectProfileFastPolicy("port0 0") && !radioHal.hilUsePort0Only);
|
||||
assert(Serial.text=="{\"port0\":false}\n");
|
||||
for(bool* guard:guards) {
|
||||
*guard=true;assert(selectProfileFastPolicy("port0 1"));
|
||||
assert(!radioHal.hilUsePort0Only && Serial.text.find("error")!=std::string::npos);
|
||||
*guard=false;
|
||||
}
|
||||
assert(selectProfileFastPolicy("port0 1") && radioHal.hilUsePort0Only);
|
||||
for(const char* invalid:{"port0 2","port0 -1","port0 0 junk","port0"})
|
||||
assert(!selectProfileFastPolicy(invalid) && radioHal.hilUsePort0Only);
|
||||
#else
|
||||
assert(!selectProfileFastPolicy("port0 0") && radioHal.hilUsePort0Only);
|
||||
#endif
|
||||
}
|
||||
'''.replace("@POLICY@", policy)
|
||||
self.compile_run(fixture)
|
||||
self.compile_run("#define HIL_INDICATOR\n" + fixture)
|
||||
|
||||
def test_receive_timestamp_retains_esp32_microsecond_units_and_wrap(self):
|
||||
source = (ROOT / "tools/hil/profile_switch.cpp").read_text()
|
||||
getter = method(source, "uint32_t receiveStartedUs()")
|
||||
self.assertNotIn("_profile_visit_us", getter)
|
||||
self.assertIn("#if !defined(ESP32_PLATFORM)", getter)
|
||||
self.assertIn('#error "profile_switch.cpp requires the ESP32 microsecond profile clock"', getter)
|
||||
fixture = r'''
|
||||
#include <cassert>
|
||||
#include <cstdint>
|
||||
#define ESP32_PLATFORM
|
||||
uint32_t clockUs=0;
|
||||
uint32_t micros() { return clockUs; }
|
||||
@CLOCK@
|
||||
struct BenchWrapper { uint32_t _profile_visit_stamp=0; @GETTER@ };
|
||||
int main() {
|
||||
BenchWrapper driver;
|
||||
clockUs=0xfffffff0;
|
||||
driver._profile_visit_stamp=profileTimestamp(true);
|
||||
assert(driver.receiveStartedUs()==clockUs);
|
||||
clockUs=0x15;
|
||||
assert(uint32_t(micros()-driver.receiveStartedUs())==37);
|
||||
assert(profileElapsedUs(driver.receiveStartedUs(),profileTimestamp(true),true)==37);
|
||||
clockUs=1234567;driver._profile_visit_stamp=profileTimestamp(false);
|
||||
assert(driver.receiveStartedUs()==1234567);
|
||||
}
|
||||
'''.replace("@CLOCK@", clock.CLOCK).replace("@GETTER@", getter)
|
||||
self.compile_run(fixture)
|
||||
|
||||
def test_timing_and_rf_readiness_report_exercised_fast_operations(self):
|
||||
sources = (("profile_switch.cpp", "void run("),
|
||||
("profile_switch_packets.h", "void listenPacket("))
|
||||
for name, signature in sources:
|
||||
with self.subTest(source=name):
|
||||
source = (ROOT / "tools/hil" / name).read_text()
|
||||
body = method(source, signature)
|
||||
for field in ("fs", "packet_cache", "fs_entries", "packet_skips", "iq_cache", "iq_workaround_skips"):
|
||||
self.assertIn('\\"' + field + '\\"', body)
|
||||
self.assertIn("chip.hilFsEntries-fsStart", body)
|
||||
self.assertIn("chip.hilPacketSkips-packetStart", body)
|
||||
self.assertIn("chip.hilUseFsOnRetune", body)
|
||||
self.assertIn("chip.hilSkipUnchangedPacket", body)
|
||||
self.assertIn("chip.hilIqWorkaroundSkips-iqStart", body)
|
||||
chip = (ROOT / "src/helpers/radiolib/CustomSX1262.h").read_text()
|
||||
self.assertIn("bool hilUseFsOnRetune = false;", chip)
|
||||
self.assertIn("bool hilSkipUnchangedPacket = false;", chip)
|
||||
self.assertIn("bool hilSkipUnchangedIq = false;", chip)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,253 @@
|
||||
"""Execute owned IQ-workaround reuse, wire bytes, revocation and failures."""
|
||||
from pathlib import Path
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from test_radio_receive_contract import method
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class ProfileIqCacheTest(unittest.TestCase):
|
||||
def test_only_qualified_indicator_recipe_opts_in(self):
|
||||
opt_ins = []
|
||||
for recipe in (ROOT / "variants").glob("*/platformio.ini"):
|
||||
if re.search(r"^\s*-D\s+MC_SX1262_FAST_IQ_CACHE=1\s*$",
|
||||
recipe.read_text(), re.MULTILINE):
|
||||
opt_ins.append(recipe.relative_to(ROOT).as_posix())
|
||||
self.assertEqual(opt_ins, ["variants/sensecap_indicator-espnow/platformio.ini"])
|
||||
|
||||
def compile_run(self, source):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
cpp, binary = Path(folder) / "test.cpp", Path(folder) / "test"
|
||||
cpp.write_text(source, encoding="ascii")
|
||||
built = subprocess.run([os.environ.get("CXX", "g++"), "-std=c++17",
|
||||
"-Wall", "-Wextra", "-fsanitize=address,undefined",
|
||||
"-fno-omit-frame-pointer", "-no-pie", str(cpp), "-o", str(binary)],
|
||||
capture_output=True, text=True)
|
||||
self.assertEqual(built.returncode, 0, built.stderr)
|
||||
ran = subprocess.run([str(binary)], capture_output=True, text=True)
|
||||
self.assertEqual(ran.returncode, 0, ran.stderr)
|
||||
|
||||
def test_owned_iq_ack_wire_payload_setters_lifecycle_and_errors(self):
|
||||
source = (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(", "int16_t reset(bool", "int16_t sleep(bool",
|
||||
"int16_t stageMode(", "int16_t setPreambleLength(", "int16_t setCRC(",
|
||||
"int16_t implicitHeader(", "int16_t explicitHeader()", "int16_t invertIQ(",
|
||||
"int16_t setProfileProtocol(", "int16_t writeRegister(",
|
||||
"int16_t setPacketParams(", "int16_t writeProfilePacketParams(",
|
||||
"int16_t startReceive()", "int16_t startReceiveDutyCycle(")
|
||||
methods = "\n".join(method(source, signature).replace(" override", "") for signature in signatures)
|
||||
fixture = r'''
|
||||
#include <cassert>
|
||||
#include <cstdint>
|
||||
#include <cstddef>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
@DEFINES@
|
||||
#define MC_SX1262_FAST_PACKET_CACHE 0
|
||||
#define RADIOLIB_ERR_NONE 0
|
||||
#define RADIOLIB_SX126X_STANDBY_RC 0
|
||||
#define RADIOLIB_SX126X_RX_TIMEOUT_INF 0xffffff
|
||||
#define RADIOLIB_SX126X_PACKET_TYPE_LORA 1
|
||||
#define RADIOLIB_SX126X_CMD_SET_PACKET_PARAMS 0x8c
|
||||
#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_SX126X_LORA_CRC_ON 1
|
||||
#define RADIOLIB_SX126X_LORA_HEADER_EXPLICIT 0
|
||||
#define RADIOLIB_SX126X_LORA_IQ_STANDARD 0
|
||||
using RadioModeType_t=int;
|
||||
using RadioLibIrqFlags_t=uint32_t;
|
||||
struct RadioModeConfig_t {};
|
||||
@STATE@
|
||||
struct Module {
|
||||
enum { MODE_RX=1 };
|
||||
std::string* trace;char* fail;std::vector<uint8_t> packet;
|
||||
int16_t SPIwriteStream(uint16_t command,const uint8_t* data,size_t size) {
|
||||
assert(command==0x8c && size==6);packet.assign(data,data+size);
|
||||
*trace+='P';return *fail=='P' ? -100:0;
|
||||
}
|
||||
void setRfSwitchState(int mode) { assert(mode==MODE_RX);*trace+='W'; }
|
||||
};
|
||||
struct SX1262 {
|
||||
std::string trace;char fail=0;int modem=1;bool standbyXOSC=true;
|
||||
uint16_t preambleLengthLoRa=32;
|
||||
uint8_t crcTypeLoRa=1,headerType=0,invertIQEnabled=0;
|
||||
size_t implicitLen=255;
|
||||
uint32_t rxTimeout=0;int stagedMode=3;float tcxoVoltage=1.8f;
|
||||
Module module{&trace,&fail,{}};Module* mod=&module;
|
||||
int16_t call(char c) { trace+=c;return c==fail ? -100:0; }
|
||||
Module* getMod() { return mod; }
|
||||
int16_t standby(uint8_t) { return call('S'); }
|
||||
int16_t sleep(bool) { return call('L'); }
|
||||
int16_t reset(bool) { return call('Z'); }
|
||||
virtual int16_t stageMode(RadioModeType_t,RadioModeConfig_t*) { return call('G'); }
|
||||
int16_t setPacketParams(uint16_t p,uint8_t crc,uint8_t len,uint8_t hdr,uint8_t iq) {
|
||||
int16_t rc=call('I');if(!rc) rc=call('i');
|
||||
const uint8_t data[]={uint8_t(p>>8),uint8_t(p),hdr,len,crc,iq};
|
||||
if(!rc) rc=module.SPIwriteStream(0x8c,data,sizeof(data));return rc;
|
||||
}
|
||||
virtual int16_t setPreambleLength(size_t p) {
|
||||
preambleLengthLoRa=p;return setPacketParams(p,crcTypeLoRa,implicitLen,headerType,invertIQEnabled);
|
||||
}
|
||||
int16_t setCRC(uint8_t crc,uint16_t,uint16_t,bool) {
|
||||
crcTypeLoRa=crc;return setPacketParams(preambleLengthLoRa,crc,implicitLen,headerType,invertIQEnabled);
|
||||
}
|
||||
int16_t implicitHeader(size_t n) {
|
||||
implicitLen=n;headerType=1;
|
||||
return setPacketParams(preambleLengthLoRa,crcTypeLoRa,implicitLen,headerType,invertIQEnabled);
|
||||
}
|
||||
int16_t explicitHeader() {
|
||||
implicitLen=255;headerType=0;
|
||||
return setPacketParams(preambleLengthLoRa,crcTypeLoRa,implicitLen,headerType,invertIQEnabled);
|
||||
}
|
||||
virtual int16_t invertIQ(bool enable) {
|
||||
invertIQEnabled=enable;
|
||||
return setPacketParams(preambleLengthLoRa,crcTypeLoRa,implicitLen,headerType,invertIQEnabled);
|
||||
}
|
||||
int16_t setSyncWord(uint8_t) { return call('Y'); }
|
||||
int16_t writeRegister(uint16_t,const uint8_t*,uint8_t) { return call('J'); }
|
||||
int16_t startReceive(uint32_t,uint32_t,uint32_t,size_t) {
|
||||
int16_t rc=stageMode(1,nullptr);if(!rc) rc=call('F');
|
||||
if(!rc) rc=setPacketParams(preambleLengthLoRa,crcTypeLoRa,implicitLen,headerType,invertIQEnabled);
|
||||
if(!rc) rc=call('R');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 setRx(uint32_t timeout) { assert(timeout==0xffffff);return call('R'); }
|
||||
};
|
||||
struct Radio : SX1262 {
|
||||
SX1262ProfileSwitchState _profileSwitch{true};
|
||||
bool _coldStandby=true,_tcxoWakePending=false,_rx_ps_rf_rx_disabled=false;
|
||||
uint32_t _profileFastResumes=0;
|
||||
#ifdef MC_SX1262_HIL
|
||||
bool hilSkipUnchangedPacket=false,hilSkipUnchangedIq=true;
|
||||
uint32_t hilPacketSkips=0,hilIqWorkaroundSkips=0;
|
||||
#endif
|
||||
@METHODS@
|
||||
};
|
||||
void prime(Radio& r) {
|
||||
assert(r.startReceive()==0);
|
||||
assert(r.trace.find("IiP")!=std::string::npos && r.trace.back()=='Q');
|
||||
assert(r._profileSwitch.rxValid && r._profileSwitch.packetValid);
|
||||
assert(!r._profileSwitch.matchesPacketIq(r.invertIQEnabled));
|
||||
r.trace.clear();
|
||||
}
|
||||
void arm(Radio& r) {
|
||||
r.beginProfileSwitch(true);
|
||||
assert(!r._profileSwitch.matchesPacketIq(r.invertIQEnabled));
|
||||
r._profileSwitch.standbyResult(0);
|
||||
}
|
||||
int main() {
|
||||
// Only IQ is reused: changing every other packet field still emits its full
|
||||
// six-byte command in the exact SX126x wire order, including both pre bytes.
|
||||
for(uint8_t iq:{0,1}) {
|
||||
Radio r;r.invertIQEnabled=iq;prime(r);arm(r);
|
||||
assert(r._profileSwitch.matchesPacketIq(iq));
|
||||
r.preambleLengthLoRa=0x1234;r.crcTypeLoRa=2;r.implicitLen=73;r.headerType=1;
|
||||
assert(r.startReceive()==0 && r.trace=="CPWR");
|
||||
assert(r.module.packet==std::vector<uint8_t>({0x12,0x34,1,73,2,iq}));
|
||||
assert(r._profileSwitch.packetValid && r._profileSwitch.packetPreamble==0x1234);
|
||||
r.endProfileSwitch(true);
|
||||
}
|
||||
// A changed IQ or an unacknowledged packet must run the original workaround.
|
||||
for(int gate=0;gate<3;++gate) {
|
||||
Radio r;prime(r);arm(r);
|
||||
if(gate==0) r.invertIQEnabled=1;
|
||||
if(gate==1) r._profileSwitch.invalidatePacket();
|
||||
#ifdef MC_SX1262_HIL
|
||||
if(gate==2) r.hilSkipUnchangedIq=false;
|
||||
#else
|
||||
if(gate==2) continue;
|
||||
#endif
|
||||
assert(r.startReceive()==0 && r.trace=="CIiPWR");
|
||||
}
|
||||
// Owned preamble staging is the intended fast case, unlike an ordinary
|
||||
// preamble command. Every ordinary packet/direct-register path revokes IQ.
|
||||
{ Radio r;prime(r);arm(r);assert(r.setPreambleLength(64)==0 && r.trace.empty());
|
||||
assert(r.startReceive()==0 && r.trace=="CPWR"); }
|
||||
for(int setter=0;setter<8;++setter) for(bool failure:{false,true}) {
|
||||
Radio r;prime(r);
|
||||
if(setter!=4) arm(r);
|
||||
r.fail=failure ? (setter==5?'Y':setter==6?'J':'P'):0;
|
||||
uint8_t value=4;
|
||||
switch(setter) {
|
||||
case 0:r.setCRC(2);break;
|
||||
case 1:r.implicitHeader(73);break;
|
||||
case 2:r.explicitHeader();break;
|
||||
case 3:r.invertIQ(false);break;
|
||||
case 4:r.setPreambleLength(64);break;
|
||||
case 5:r.setProfileProtocol(0x2b);break;
|
||||
case 6:r.writeRegister(0x736,&value,1);break;
|
||||
case 7:r.setPacketParams(64,1,255,0,0);break;
|
||||
}
|
||||
assert(!r._profileSwitch.packetValid);
|
||||
r.fail=0;r.trace.clear();
|
||||
if(failure && setter==5) {
|
||||
assert(!r._profileSwitch.rxValid);continue;
|
||||
}
|
||||
if(setter==4) arm(r);
|
||||
assert(!r._profileSwitch.matchesPacketIq(r.invertIQEnabled));
|
||||
assert(r.startReceive()==0 && r.trace=="CIiPWR");
|
||||
}
|
||||
// The acknowledged tuple cannot survive TX/CAD staging, either sleep,
|
||||
// reset, RX duty cycling, explicit disable, rollback, or a failed RX command.
|
||||
for(int event=0;event<8;++event) for(bool failure:{false,true}) {
|
||||
Radio r;prime(r);arm(r);r.fail=failure?'G':0;
|
||||
switch(event) {
|
||||
case 0:r.stageMode(2,nullptr);break;
|
||||
case 1:r.stageMode(3,nullptr);break;
|
||||
case 2:r.sleep(true);break;
|
||||
case 3:r.sleep(false);break;
|
||||
case 4:r.reset();break;
|
||||
case 5:r.startReceiveDutyCycle(1000,1000);break;
|
||||
case 6:r.setProfileSwitchOptimization(false);break;
|
||||
case 7:r.endProfileSwitch(false);break;
|
||||
}
|
||||
assert(!r._profileSwitch.packetValid && !r._profileSwitch.rxValid);
|
||||
assert(!r._profileSwitch.matchesPacketIq(r.invertIQEnabled));
|
||||
}
|
||||
for(char failure:std::string("CIiPR")) {
|
||||
Radio r;prime(r);arm(r);
|
||||
if(failure=='I' || failure=='i') r._profileSwitch.invalidatePacket();
|
||||
r.fail=failure;assert(r.startReceive()==-100 && r.trace.back()==failure);
|
||||
assert(!r._profileSwitch.rxValid && !r._profileSwitch.packetValid);
|
||||
r.endProfileSwitch(false);r.fail=0;r.trace.clear();prime(r);
|
||||
}
|
||||
for(int gate=0;gate<4;++gate) {
|
||||
Radio r;prime(r);
|
||||
switch(gate) {
|
||||
case 0:r.beginProfileSwitch(false);r._profileSwitch.standbyResult(0);break;
|
||||
case 1:r.standbyXOSC=false;arm(r);break;
|
||||
case 2:r.beginProfileSwitch(true);break;
|
||||
case 3:r._profileSwitch.packetResult(-100,32,1,255,0,0);break;
|
||||
}
|
||||
assert(!r._profileSwitch.matchesPacketIq(0));
|
||||
}
|
||||
}
|
||||
'''.replace("@STATE@", state).replace("@METHODS@", methods)
|
||||
for definitions in ("#define MC_SX1262_FAST_IQ_CACHE 1",
|
||||
"#define MC_SX1262_FAST_IQ_CACHE 0\n#define MC_SX1262_HIL"):
|
||||
with self.subTest(definitions=definitions):
|
||||
self.compile_run(fixture.replace("@DEFINES@", definitions))
|
||||
|
||||
def test_unqualified_boards_keep_the_original_live_modem_query_and_iq_path(self):
|
||||
source = (ROOT / "src/helpers/radiolib/CustomSX1262.h").read_text()
|
||||
self.assertIn("#define MC_SX1262_FAST_IQ_CACHE 0", source)
|
||||
modulation = method(source, "int16_t setLoRaModulationParams(")
|
||||
self.assertIn("if (getPacketType() != RADIOLIB_SX126X_PACKET_TYPE_LORA)", modulation)
|
||||
helper = method(source, "int16_t writeProfilePacketParams(")
|
||||
self.assertIn("return getMod()->SPIwriteStream(RADIOLIB_SX126X_CMD_SET_PACKET_PARAMS,", helper)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -59,7 +59,7 @@ struct Radio {
|
||||
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,
|
||||
// The pinned RadioLib 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;
|
||||
|
||||
Reference in new issue
Block a user