Use buffered radio SPI and acknowledged RX reuse on direct-I/O boards
This commit is contained in:
1 parent
b8b7880a48
commit
3892599300
80 files changed
+846
-173
No files matched your search
@@ -0,0 +1,145 @@
|
||||
"""Execute actual ESP32 radio constructors with local and default SPI buses."""
|
||||
from pathlib import Path
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from test_sx126x_buffered_radio_hal import MOCK
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
TARGETS = (
|
||||
"ebyte_eora_s3", "generic-e22", "heltec_ct62", "heltec_e213",
|
||||
"heltec_e290", "heltec_rc32", "heltec_t190", "heltec_tracker",
|
||||
"heltec_tracker_v2", "heltec_v3", "heltec_v4", "heltec_v4_r8",
|
||||
"heltec_wireless_paper", "lilygo_t3s3", "lilygo_tbeam_1w",
|
||||
"lilygo_tbeam_SX1262", "lilygo_tbeam_supreme_SX1262", "lilygo_tdeck",
|
||||
"lilygo_teth_elite", "lilygo_tlora_c6", "m5stack_unit_c6l",
|
||||
"meshadventurer", "mke_s3", "nibble_screen_connect",
|
||||
"nibble_zero_connect", "rak3112", "station_g2", "station_g3_esp32",
|
||||
"tenstar_c3", "thinknode_m2", "thinknode_m5", "wio-tracker-l2",
|
||||
"xiao_c3", "xiao_c6", "xiao_s3", "xiao_s3_wio",
|
||||
)
|
||||
LEGACY_FALLBACKS = {"lilygo_tdeck", "xiao_s3_wio"}
|
||||
|
||||
|
||||
def construction(target):
|
||||
filename = {"xiao_c6": "XiaoC6Board.cpp",
|
||||
"m5stack_unit_c6l": "UnitC6LBoard.cpp"}.get(target, "target.cpp")
|
||||
source = (ROOT / "variants" / target / filename).read_text(encoding="ascii")
|
||||
prefix = source[:source.index("WRAPPER_CLASS radio_driver")]
|
||||
# Only the target's actual global constructors are under test. The real
|
||||
# portable and platform HAL headers are included once by the harness;
|
||||
# unrelated board/sensor/display classes have inert stand-ins.
|
||||
prefix = re.sub(r"^\s*#include[^\n]*\n", "", prefix, flags=re.MULTILINE)
|
||||
opened = len(re.findall(r"^\s*#if(?:def|ndef)?\b", prefix, re.MULTILINE))
|
||||
closed = len(re.findall(r"^\s*#endif\b", prefix, re.MULTILINE))
|
||||
prefix += "\n#endif\n" * (opened - closed)
|
||||
board = re.search(r"^\s*(\w+) board;", prefix, re.MULTILINE).group(1)
|
||||
return prefix, board
|
||||
|
||||
|
||||
class Esp32BufferedRadioTargetTests(unittest.TestCase):
|
||||
def test_actual_constructors_keep_bus_pins_clock_and_initialization_ownership(self):
|
||||
compiler = shutil.which(os.environ.get("CXX", "g++"))
|
||||
self.assertIsNotNone(compiler)
|
||||
mock = MOCK.replace("struct SPIClass {", """struct SPIClass {
|
||||
explicit SPIClass(int = 0) {}""")
|
||||
prelude = r'''
|
||||
#include <helpers/radiolib/SX126xBufferedRadioHal.h>
|
||||
#include <cassert>
|
||||
SPIClass SPI;
|
||||
constexpr unsigned FSPI=2, HSPI=3;
|
||||
constexpr unsigned P_LORA_NSS=1, P_LORA_DIO_1=2, P_LORA_RESET=3, P_LORA_BUSY=4;
|
||||
struct InertBoard {};
|
||||
struct Module {
|
||||
ArduinoHal* hal;
|
||||
bool owned=false;
|
||||
Module(ArduinoHal* h,unsigned cs,unsigned irq,unsigned reset,unsigned busy):hal(h) {
|
||||
assert(cs==1 && irq==2 && reset==3 && busy==4);
|
||||
}
|
||||
Module(unsigned cs,unsigned irq,unsigned reset,unsigned busy)
|
||||
:Module(new ArduinoHal(SPI,SPISettings(2000000,MSBFIRST,SPI_MODE0)),cs,irq,reset,busy) {
|
||||
owned=true;hal->initInterface=true;
|
||||
}
|
||||
~Module() { if(owned) delete hal; }
|
||||
};
|
||||
struct Radio {
|
||||
Module* module;
|
||||
Radio(Module* m):module(m) {}
|
||||
~Radio() { delete module; }
|
||||
};
|
||||
#define RADIO_CLASS Radio
|
||||
'''
|
||||
declarations = {8000000: [], 8888888: []}
|
||||
calls = {8000000: [], 8888888: []}
|
||||
for index, target in enumerate(TARGETS):
|
||||
prefix, board = construction(target)
|
||||
self.assertNotIn("sensecap_indicator", target)
|
||||
for local in (True, False):
|
||||
has_local = "static SPIClass spi" in prefix
|
||||
if not local and has_local and "defined(P_LORA_SCLK)" not in prefix:
|
||||
continue
|
||||
if local and not has_local:
|
||||
continue
|
||||
clock = 8888888 if target == "lilygo_tdeck" else 8000000
|
||||
buffered = local or target not in LEGACY_FALLBACKS
|
||||
expected = (4000000 if local else 2000000) if target == "heltec_rc32" else (
|
||||
clock if buffered else 2000000)
|
||||
selected = "spi" if local else "::SPI"
|
||||
name = f"target_{index}_{int(local)}"
|
||||
options = f"#define P_LORA_SCLK 5\n" if local else ""
|
||||
check = f'''
|
||||
void check() {{
|
||||
auto& bus={selected};auto& hal=*radio.module->hal;
|
||||
assert(hal.spi==&bus && hal.spiSettings.hz=={expected});
|
||||
assert(hal.spiSettings.order==MSBFIRST && hal.spiSettings.mode==SPI_MODE0);
|
||||
bus.begins=bus.ends=bus.bursts=bus.bytes=0;
|
||||
hal.init();hal.term();
|
||||
assert(bus.begins=={int(not local)} && bus.ends=={int(not local)});
|
||||
uint8_t tx[]={{1,2,3,4,5,6,7}},rx[7]={{}};
|
||||
hal.spiTransfer(tx,sizeof(tx),rx);
|
||||
assert(bus.bursts=={int(buffered)} && bus.bytes=={0 if buffered else 7});
|
||||
for(unsigned i=0;i<7;++i) assert(rx[i]==uint8_t(tx[i]^0xa5));
|
||||
}}
|
||||
'''
|
||||
declarations[clock].append(options + f"namespace {name} {{\nusing {board}=InertBoard;\n"
|
||||
+ prefix + check + "}\n#undef P_LORA_SCLK\n")
|
||||
calls[clock].append(f"{name}::check();")
|
||||
self.assertEqual(len(TARGETS), 36)
|
||||
self.assertEqual(sum(len(group) for group in calls.values()), 63)
|
||||
with tempfile.TemporaryDirectory(prefix="esp32-buffered-targets-") as folder:
|
||||
work = Path(folder)
|
||||
(work / "hal/Arduino").mkdir(parents=True)
|
||||
(work / "hal/Arduino/ArduinoHal.h").write_text(mock, encoding="ascii")
|
||||
cpp, binary = work / "test.cpp", work / "test"
|
||||
flags = [] if os.name == "nt" else ["-fsanitize=address,undefined", "-fno-pie", "-no-pie"]
|
||||
# Parse the real helper's default argument once per recipe clock,
|
||||
# without rewriting any production constructor or HAL type.
|
||||
for clock in declarations:
|
||||
code = (prelude + "\n".join(declarations[clock])
|
||||
+ "\nint main(){" + "".join(calls[clock]) + "}\n")
|
||||
legacy = code.replace(
|
||||
"new Module(&radio_hal, P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY)",
|
||||
"new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY)", 1)
|
||||
self.assertNotEqual(legacy, code)
|
||||
for text, succeeds in ((code, True), (legacy, False)):
|
||||
with self.subTest(clock=clock, buffered=succeeds):
|
||||
cpp.write_text(text, encoding="ascii")
|
||||
built = subprocess.run([compiler, "-std=c++17", "-Wall", "-Wextra",
|
||||
"-DESP32_PLATFORM", f"-DMC_SX1262_SPI_HZ={clock}", *flags,
|
||||
"-I", str(work), "-I", str(ROOT / "src"),
|
||||
str(cpp), "-o", str(binary)], capture_output=True, text=True, timeout=60)
|
||||
self.assertEqual(built.returncode, 0, built.stdout + built.stderr)
|
||||
ran = subprocess.run([str(binary)], capture_output=True, text=True, timeout=20)
|
||||
if succeeds:
|
||||
self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)
|
||||
else:
|
||||
self.assertNotEqual(ran.returncode, 0, "unbuffered constructor negative control passed")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -18,6 +18,7 @@ class LR1110ProfileSwitchTests(unittest.TestCase):
|
||||
"t1000-e": "Nrf52BufferedRadioHal",
|
||||
"wio_wm1110": "Nrf52BufferedRadioHal",
|
||||
"thinknode_m3": "Nrf52BufferedRadioHal",
|
||||
"thinknode_m4": "Nrf52BufferedRadioHal",
|
||||
"minewsemi_me25ls01": "Nrf52BufferedRadioHal",
|
||||
"thinknode_m7": "ESP32BufferedRadioHal",
|
||||
"thinknode_m9": "ESP32BufferedRadioHal",
|
||||
|
||||
@@ -14,15 +14,35 @@ ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class ProfileIqCacheTest(unittest.TestCase):
|
||||
def test_only_qualified_recipes_opt_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.assertCountEqual(opt_ins, ["variants/sensecap_indicator-espnow/platformio.ini",
|
||||
"variants/lilygo_tdeck/platformio.ini",
|
||||
"variants/rak3401/platformio.ini"])
|
||||
def test_shared_defaults_preserve_opt_outs_and_indicator_policy(self):
|
||||
source = (ROOT / "src/helpers/radiolib/CustomSX1262.h").read_text()
|
||||
defaults = source[source.index("#ifndef MC_SX1262_FAST_PROFILE_SWITCH"):
|
||||
source.index("#ifndef SX126X_TX_BUSY_TIMEOUT_MS")]
|
||||
cases = (
|
||||
("", (1, 1, 1, 1, 1)),
|
||||
("#define MC_SX1262_FAST_PROFILE_SWITCH 0", (0, 0, 0, 0, 0)),
|
||||
("#define MC_SX1262_FAST_FS 0", (1, 0, 1, 0, 0)),
|
||||
("#define MC_SX1262_FAST_IQ_CACHE 0\n"
|
||||
"#define MC_SX1262_FAST_MODEM_CACHE 0", (1, 1, 1, 0, 0)),
|
||||
("#define MC_SX1262_FAST_PACKET_CACHE 0", (1, 1, 0, 1, 1)),
|
||||
)
|
||||
# Use the real expander recipe: its explicit IQ reuse remains on,
|
||||
# while its FS and packet opt-outs keep modem-query reuse off.
|
||||
indicator = (ROOT / "variants/sensecap_indicator-espnow/platformio.ini").read_text()
|
||||
section = indicator.split("[SenseCapIndicator-LoRa]", 1)[1].split("\n[", 1)[0]
|
||||
flags = re.findall(r"^\s*-D\s+(MC_SX1262_FAST_\w+=\d+)\s*$",
|
||||
section, re.MULTILINE)
|
||||
self.assertGreaterEqual(len(flags), 4)
|
||||
cases += (("\n".join("#define " + flag.replace("=", " ") for flag in flags),
|
||||
(1, 0, 0, 1, 0)),)
|
||||
names = ("PROFILE_SWITCH", "FS", "PACKET_CACHE", "IQ_CACHE", "MODEM_CACHE")
|
||||
for overrides, expected in cases:
|
||||
with self.subTest(overrides=overrides):
|
||||
assertions = "\n".join(
|
||||
f'static_assert(MC_SX1262_FAST_{name} == {value}, "{name}");'
|
||||
for name, value in zip(names, expected))
|
||||
self.compile_run(overrides + "\n" + defaults + "\n" + assertions
|
||||
+ "\nint main() {}\n")
|
||||
|
||||
def compile_run(self, source):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
@@ -246,12 +266,10 @@ int main() {
|
||||
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):
|
||||
def test_explicit_cache_opt_outs_keep_live_queries_and_owned_gates(self):
|
||||
source = (ROOT / "src/helpers/radiolib/CustomSX1262.h").read_text()
|
||||
self.assertIn("#define MC_SX1262_FAST_IQ_CACHE 0", source)
|
||||
self.assertIn("#define MC_SX1262_FAST_MODEM_CACHE 0", source)
|
||||
# Execute the shared production-method fixture: default-off builds must
|
||||
# query the modem, while opted-in/HIL reuse must retain all ownership,
|
||||
# Execute the shared production-method fixture: explicit opt-outs must
|
||||
# query the modem, while enabled/HIL reuse must retain all ownership,
|
||||
# initialization and failure gates. Do not depend on an if's spelling.
|
||||
modem_cache.ModemCacheTests.test_confirmed_modem_requires_owned_warm_rx_and_survives_no_failure(self)
|
||||
helper = method(source, "int16_t writeProfilePacketParams(")
|
||||
|
||||
@@ -468,7 +468,9 @@ class Rak3401OnboardRadioTests(unittest.TestCase):
|
||||
self.assertIn("digitalWrite(SX126X_POWER_EN, HIGH);", begin)
|
||||
init = extract_braced(target, "bool radio_init()")
|
||||
self.assertIn("radio.std_init(&SPI)", init)
|
||||
self.assertIn("P_LORA_RESET, P_LORA_BUSY, SPI)", target)
|
||||
self.assertIn("SX126xBufferedRadioHal radioHal(SPI)", target)
|
||||
self.assertIn("new Module(&radioHal, P_LORA_NSS, P_LORA_DIO_1, "
|
||||
"P_LORA_RESET, P_LORA_BUSY)", target)
|
||||
# External-radio construction and retry must retain their SPI1 owner.
|
||||
external_target = (VARIANT / "target.cpp").read_text()
|
||||
self.assertIn("Nrf52BufferedRadioHal radioHal(SPI1, 8000000)", external_target)
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
"""Execute portable radio SPI buffering, settings and bus ownership."""
|
||||
from pathlib import Path
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
RADIO = ROOT / "src/helpers/radiolib"
|
||||
|
||||
MOCK = r'''
|
||||
#pragma once
|
||||
#include <cassert>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
constexpr unsigned MSBFIRST=1, SPI_MODE0=0;
|
||||
struct SPISettings {
|
||||
unsigned hz, order, mode;
|
||||
SPISettings(unsigned h, unsigned o, unsigned m) : hz(h), order(o), mode(m) {}
|
||||
};
|
||||
struct SPIClass {
|
||||
unsigned bursts=0, bytes=0, begins=0, ends=0;
|
||||
const void* lastOut=nullptr; void* lastIn=nullptr; size_t lastLength=0;
|
||||
void begin() { ++begins; }
|
||||
void end() { ++ends; }
|
||||
void burst(const void* out, void* in, size_t length) {
|
||||
++bursts; lastOut=out; lastIn=in; lastLength=length;
|
||||
const auto* tx=static_cast<const uint8_t*>(out);
|
||||
auto* rx=static_cast<uint8_t*>(in);
|
||||
for (size_t i=0; i<length; ++i) rx[i]=tx[i]^0xa5;
|
||||
}
|
||||
#if defined(NRF52_PLATFORM) || defined(RP2040_PLATFORM)
|
||||
void transfer(const void* out, void* in, size_t length) { burst(out,in,length); }
|
||||
#else
|
||||
void transferBytes(const uint8_t* out, uint8_t* in, size_t length) {
|
||||
burst(out,in,length);
|
||||
}
|
||||
#endif
|
||||
uint8_t transfer(uint8_t value) { ++bytes; return value^0xa5; }
|
||||
};
|
||||
struct ArduinoHal {
|
||||
SPIClass* spi; SPISettings spiSettings; bool initInterface=false;
|
||||
explicit ArduinoHal(SPIClass& bus,SPISettings settings)
|
||||
: spi(&bus),spiSettings(settings) {}
|
||||
virtual ~ArduinoHal()=default;
|
||||
virtual void init() { if (initInterface) spi->begin(); }
|
||||
virtual void term() { if (initInterface) spi->end(); }
|
||||
virtual void spiTransfer(uint8_t* out,size_t length,uint8_t* in) {
|
||||
for (size_t i=0;i<length;++i) in[i]=spi->transfer(out[i]);
|
||||
}
|
||||
};
|
||||
'''
|
||||
|
||||
FIXTURE = r'''
|
||||
#include <array>
|
||||
#include <initializer_list>
|
||||
#include <helpers/radiolib/SX126xBufferedRadioHal.h>
|
||||
SPIClass unused, explicitBus, fallbackBus;
|
||||
int main() {
|
||||
SX126xBufferedRadioHal external(explicitBus);
|
||||
SX126xBufferedRadioHal fallback(fallbackBus,MC_SX1262_SPI_HZ,true);
|
||||
SX126xBufferedRadioHal slower(explicitBus,4000000);
|
||||
assert(external.spiSettings.hz == MC_SX1262_SPI_HZ);
|
||||
assert(slower.spiSettings.hz == 4000000);
|
||||
assert(external.spiSettings.order == MSBFIRST && external.spiSettings.mode == SPI_MODE0);
|
||||
assert(!external.initInterface && fallback.initInterface);
|
||||
ArduinoHal& hal=external;
|
||||
hal.init(); hal.term();
|
||||
assert(explicitBus.begins==0 && explicitBus.ends==0);
|
||||
fallback.init(); fallback.term();
|
||||
assert(fallbackBus.begins==1 && fallbackBus.ends==1);
|
||||
// A board/storage handoff can restart this SAME bus without replacing HAL.
|
||||
explicitBus.end(); explicitBus.begin();
|
||||
assert(hal.spi == &explicitBus);
|
||||
std::array<uint8_t,260> tx{}, rx{};
|
||||
for (size_t i=0;i<tx.size();++i) tx[i]=uint8_t(i);
|
||||
const auto original=tx;
|
||||
for (size_t length : {size_t(1),size_t(2),size_t(7),size_t(260)}) {
|
||||
rx.fill(0x77);
|
||||
const unsigned before=explicitBus.bursts;
|
||||
hal.spiTransfer(tx.data(),length,rx.data());
|
||||
assert(explicitBus.bursts==before+1 && explicitBus.bytes==0);
|
||||
assert(explicitBus.lastOut==tx.data() && explicitBus.lastIn==rx.data());
|
||||
assert(explicitBus.lastLength==length && tx==original);
|
||||
for (size_t i=0;i<length;++i) assert(rx[i]==uint8_t(tx[i]^0xa5));
|
||||
for (size_t i=length;i<rx.size();++i) assert(rx[i]==0x77);
|
||||
}
|
||||
const unsigned before=explicitBus.bursts;
|
||||
hal.spiTransfer(nullptr,0,nullptr);
|
||||
assert(explicitBus.bursts==before && explicitBus.bytes==0);
|
||||
assert(unused.bursts==0 && fallbackBus.bursts==0);
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class SX126xBufferedRadioHalTests(unittest.TestCase):
|
||||
def test_real_platform_buffers_forward_bytes_without_taking_explicit_bus_ownership(self):
|
||||
compiler=shutil.which(os.environ.get("CXX","g++"))
|
||||
self.assertIsNotNone(compiler)
|
||||
headers={name:(RADIO/name).read_text(encoding="ascii") for name in (
|
||||
"SX126xBufferedRadioHal.h","Nrf52BufferedRadioHal.h","ESP32BufferedRadioHal.h")}
|
||||
with tempfile.TemporaryDirectory(prefix="sx126x-buffered-radio-") as folder:
|
||||
base=Path(folder)
|
||||
(base/"hal/Arduino").mkdir(parents=True)
|
||||
(base/"helpers/radiolib").mkdir(parents=True)
|
||||
(base/"hal/Arduino/ArduinoHal.h").write_text(MOCK,encoding="ascii")
|
||||
cpp,executable=base/"test.cpp",base/"test"
|
||||
cpp.write_text(FIXTURE,encoding="ascii")
|
||||
for arch,header in (("NRF52_PLATFORM","Nrf52BufferedRadioHal.h"),
|
||||
("ESP32_PLATFORM","ESP32BufferedRadioHal.h"),
|
||||
("RP2040_PLATFORM","SX126xBufferedRadioHal.h")):
|
||||
# Without the real override, byte-for-byte correctness alone
|
||||
# still passes; the per-command transfer requirement must fail.
|
||||
legacy=re.sub(r" void spiTransfer\([^}]+\}\n","",headers[header])
|
||||
self.assertNotEqual(legacy,headers[header])
|
||||
for clock in (8000000,8888888):
|
||||
for name,implementation,succeeds in (("buffered",headers[header],True),
|
||||
("per-byte",legacy,False)):
|
||||
with self.subTest(arch=arch,clock=clock,implementation=name):
|
||||
for file,content in headers.items():
|
||||
(base/"helpers/radiolib"/file).write_text(
|
||||
implementation if file==header else content,encoding="ascii")
|
||||
built=subprocess.run([compiler,"-std=c++17","-Wall","-Wextra",
|
||||
"-Werror",f"-D{arch}",f"-DMC_SX1262_SPI_HZ={clock}",
|
||||
"-I",str(base),str(cpp),"-o",str(executable)],
|
||||
capture_output=True,text=True,timeout=60)
|
||||
self.assertEqual(built.returncode,0,built.stdout+built.stderr)
|
||||
ran=subprocess.run([str(executable)],capture_output=True,
|
||||
text=True,timeout=10)
|
||||
if succeeds:
|
||||
self.assertEqual(ran.returncode,0,ran.stdout+ran.stderr)
|
||||
else:
|
||||
self.assertNotEqual(ran.returncode,0,
|
||||
"per-byte negative control did not fail")
|
||||
|
||||
def test_default_clock_matches_all_capable_spi_controllers(self):
|
||||
header=(RADIO/"SX126xBufferedRadioHal.h").read_text(encoding="ascii")
|
||||
self.assertIn("#define MC_SX1262_SPI_HZ 8000000",header)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,165 @@
|
||||
"""Compile real nRF52/RP2040 target constructors and preserve bus ownership."""
|
||||
from pathlib import Path
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from test_sx126x_buffered_radio_hal import MOCK, RADIO, ROOT
|
||||
|
||||
|
||||
PREFIX = r'''
|
||||
#include <helpers/radiolib/SX126xBufferedRadioHal.h>
|
||||
constexpr unsigned P_LORA_NSS=1,P_LORA_DIO_1=2,P_LORA_RESET=3,P_LORA_BUSY=4;
|
||||
struct Module {
|
||||
ArduinoHal* hal; bool owned=false;
|
||||
Module(ArduinoHal* adapter,unsigned cs,unsigned irq,unsigned reset,unsigned busy)
|
||||
: hal(adapter) { assert(cs==1 && irq==2 && reset==3 && busy==4); }
|
||||
Module(unsigned cs,unsigned irq,unsigned reset,unsigned busy,SPIClass& bus)
|
||||
: hal(new ArduinoHal(bus,SPISettings(2000000,MSBFIRST,SPI_MODE0))),owned(true) {
|
||||
assert(cs==1 && irq==2 && reset==3 && busy==4);
|
||||
}
|
||||
~Module() { if (owned) delete hal; }
|
||||
};
|
||||
struct Radio {
|
||||
Module* mod;
|
||||
Radio(Module* value) : mod(value) {}
|
||||
~Radio() { delete mod; }
|
||||
};
|
||||
#define RADIO_CLASS Radio
|
||||
'''
|
||||
|
||||
|
||||
def target_sources(architecture):
|
||||
sources=set()
|
||||
for config in sorted((ROOT/"variants").glob("*/platformio.ini")):
|
||||
text=config.read_text()
|
||||
if not re.search(r"^\s*-D\s+RADIO_CLASS=CustomSX1262\s*$",text,re.MULTILINE):
|
||||
continue
|
||||
base=re.search(r"^extends\s*=\s*(\S+)",text,re.MULTILINE)
|
||||
if not base or base.group(1) not in architecture:
|
||||
continue
|
||||
if config.parent.name=="rak3401":
|
||||
continue # Dedicated physical-board test pins its qualified SPI1 setup.
|
||||
source=config.with_name("target.cpp")
|
||||
if config.parent.name=="wio-tracker-l1-eink":
|
||||
source=ROOT/"variants/wio-tracker-l1/target.cpp"
|
||||
sources.add(source)
|
||||
return sorted(sources)
|
||||
|
||||
|
||||
class SX126xTargetConstructors(unittest.TestCase):
|
||||
def compile_run(self,architecture,source,*,defines=()):
|
||||
compiler=shutil.which(os.environ.get("CXX","g++"))
|
||||
self.assertIsNotNone(compiler)
|
||||
with tempfile.TemporaryDirectory(prefix="sx126x-target-constructors-") as folder:
|
||||
base=Path(folder)
|
||||
(base/"hal/Arduino").mkdir(parents=True)
|
||||
(base/"hal/Arduino/ArduinoHal.h").write_text(MOCK,encoding="ascii")
|
||||
cpp,executable=base/"test.cpp",base/"test"
|
||||
cpp.write_text(source,encoding="ascii")
|
||||
built=subprocess.run([compiler,"-std=c++17","-Wall","-Wextra","-Werror",
|
||||
f"-D{architecture}",*[f"-D{item}" for item in defines],"-I",str(base),
|
||||
"-I",str(ROOT/"src"),str(cpp),"-o",str(executable)],
|
||||
capture_output=True,text=True,timeout=60)
|
||||
self.assertEqual(built.returncode,0,built.stdout+built.stderr)
|
||||
ran=subprocess.run([str(executable)],capture_output=True,text=True,timeout=10)
|
||||
self.assertEqual(ran.returncode,0,ran.stdout+ran.stderr)
|
||||
|
||||
def test_all_actual_nrf52_and_rp2040_constructions_keep_selected_bus(self):
|
||||
for arch,bases in (("NRF52_PLATFORM",{"nrf52_base","rak4631_hw"}),
|
||||
("RP2040_PLATFORM",{"rp2040_base"})):
|
||||
with self.subTest(architecture=arch):
|
||||
cases=[]
|
||||
sources=target_sources(bases)
|
||||
self.assertTrue(sources)
|
||||
for source in sources:
|
||||
text=source.read_text()
|
||||
self.assertIn("#include <helpers/radiolib/SX126xBufferedRadioHal.h>",
|
||||
text,str(source))
|
||||
constructions=re.findall(
|
||||
r"^static SX126xBufferedRadioHal radioHal\(([^;]+)\);\n"
|
||||
r"(RADIO_CLASS radio = new Module\(&radioHal,[^;]+;)",
|
||||
text,re.MULTILINE)
|
||||
self.assertTrue(constructions,str(source))
|
||||
# Every direct Module construction is now buffered except
|
||||
# the deliberately unchanged Muzi Duo LR1121 selection.
|
||||
legacy=re.findall(r"new Module\(P_LORA_NSS[^;]+;",text)
|
||||
self.assertEqual(len(legacy),1 if source.parent.name=="muzi_base" else 0,
|
||||
str(source))
|
||||
for ordinal,(arguments,module) in enumerate(constructions):
|
||||
bus=arguments.split(",")[0]
|
||||
expected_bus="SPI1" if source.parent.name in {
|
||||
"rak11310","rpi_picow","waveshare_rp2040_lora"} else "SPI"
|
||||
self.assertEqual(bus,expected_bus,str(source))
|
||||
# These are the pre-existing Module() default-bus
|
||||
# branches. Every other constructor passed its bus
|
||||
# explicitly and must leave begin/end board-owned.
|
||||
owns=source.parent.name=="xiao_rp2040" or (
|
||||
source.parent.name in {"heltec_t096","heltec_t1","heltec_t114"}
|
||||
and ordinal==1)
|
||||
name=f"case_{len(cases)}"
|
||||
cases.append((name,f'''
|
||||
namespace {name} {{
|
||||
SPIClass SPI,SPI1;
|
||||
static SX126xBufferedRadioHal radioHal({arguments});
|
||||
{module}
|
||||
void check() {{
|
||||
assert(radio.mod->hal==&radioHal && radioHal.spi==&{bus});
|
||||
assert(radioHal.spiSettings.hz==8000000);
|
||||
assert(radioHal.initInterface=={str(owns).lower()});
|
||||
radio.mod->hal->init();radio.mod->hal->term();
|
||||
assert({bus}.begins=={int(owns)} && {bus}.ends=={int(owns)});
|
||||
}}
|
||||
}}
|
||||
'''))
|
||||
fixture=PREFIX+"\n".join(code for _,code in cases)
|
||||
fixture+="\nint main() {"+"".join(f"{name}::check();" for name,_ in cases)+"}\n"
|
||||
self.compile_run(arch,fixture)
|
||||
|
||||
def test_muzi_uno_selection_does_not_change_the_lr1121_duo_constructor(self):
|
||||
text=(ROOT/"variants/muzi_base/target.cpp").read_text()
|
||||
block=re.search(r"^#if defined\(USE_SX1262\)\nstatic SX126xBufferedRadioHal "
|
||||
r"radioHal\([^#]+#else\n[^#]+#endif",text,re.MULTILINE)
|
||||
self.assertIsNotNone(block)
|
||||
fixture=PREFIX+"\nSPIClass SPI;\n"+block.group(0)+r'''
|
||||
int main() {
|
||||
assert(radio.mod->hal->spi==&SPI);
|
||||
#ifdef USE_SX1262
|
||||
assert(!radio.mod->owned && radio.mod->hal==&radioHal);
|
||||
assert(radio.mod->hal->spiSettings.hz==8000000);
|
||||
#else
|
||||
assert(radio.mod->owned && radio.mod->hal->spiSettings.hz==2000000);
|
||||
#endif
|
||||
}
|
||||
'''
|
||||
for definitions in ((),("USE_SX1262",)):
|
||||
with self.subTest(defines=definitions):
|
||||
self.compile_run("NRF52_PLATFORM",fixture,defines=definitions)
|
||||
|
||||
def test_lr1110_m4_keeps_manual_spi_start_and_uses_buffered_8mhz_bus(self):
|
||||
text=(ROOT/"variants/thinknode_m4/target.cpp").read_text()
|
||||
construction=re.search(r"^static Nrf52BufferedRadioHal radioHal\([^;]+;\n"
|
||||
r"RADIO_CLASS radio = new Module\([^;]+;",text,re.MULTILINE)
|
||||
self.assertIsNotNone(construction)
|
||||
self.assertIn("SPI.setPins(P_LORA_MISO, P_LORA_SCLK, P_LORA_MOSI);",text)
|
||||
self.assertIn("SPI.begin();",text)
|
||||
self.assertIn("int status = radio.begin(",text)
|
||||
fixture=PREFIX+"\nSPIClass SPI;\n"+construction.group(0)+r'''
|
||||
int main() {
|
||||
assert(radio.mod->hal==&radioHal && radioHal.spi==&SPI);
|
||||
assert(radioHal.spiSettings.hz==8000000 && !radioHal.initInterface);
|
||||
radio.mod->hal->init();radio.mod->hal->term();
|
||||
assert(SPI.begins==0 && SPI.ends==0);
|
||||
uint8_t tx[]={1,0x7f,0xff},rx[3]={};
|
||||
radio.mod->hal->spiTransfer(tx,3,rx);
|
||||
assert(SPI.bursts==1 && SPI.bytes==0 && rx[0]==(1^0xa5));
|
||||
}
|
||||
'''
|
||||
self.compile_run("NRF52_PLATFORM",fixture)
|
||||
|
||||
|
||||
if __name__=="__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user