From 61a536c686ad2436132668bc18f0f8e5b0b04383 Mon Sep 17 00:00:00 2001 From: mikecarper Date: Fri, 23 Oct 2026 08:07:01 -0700 Subject: [PATCH] Add gated Tag and MeshTower buffered SPIM1 qualification paths --- .github/workflows/run-unit-tests.yml | 1 + platformio.ini | 1 + scripts/nrf52_hil_spim1.py | 96 ++++++++ src/helpers/nrf52/Nrf52HilSpim1Config.h | 56 +++++ src/helpers/nrf52/Nrf52HilSpim1Owner.h | 17 ++ test/test_nrf52_hil_spim1.py | 278 ++++++++++++++++++++++++ test/test_sx126x_nrf_rp_constructors.py | 4 + variants/heltec_tower_v2/target.cpp | 9 + variants/rak_wismesh_tag/target.cpp | 9 + 9 files changed, 471 insertions(+) create mode 100644 scripts/nrf52_hil_spim1.py create mode 100644 src/helpers/nrf52/Nrf52HilSpim1Config.h create mode 100644 src/helpers/nrf52/Nrf52HilSpim1Owner.h create mode 100644 test/test_nrf52_hil_spim1.py diff --git a/.github/workflows/run-unit-tests.yml b/.github/workflows/run-unit-tests.yml index dead42a37..977d19dd2 100644 --- a/.github/workflows/run-unit-tests.yml +++ b/.github/workflows/run-unit-tests.yml @@ -826,6 +826,7 @@ jobs: python3 -B test/test_nrf_radio_spi_read_probe.py -v python3 -B test/test_sx126x_nrf_rp_constructors.py -v python3 -B test/test_xiao_nrf52_buffered_spi.py -v + python3 -B test/test_nrf52_hil_spim1.py -v python3 -B test/test_esp32_buffered_radio_targets.py -v python3 -B test/test_xiao_battery_safety.py -v python3 -B test/test_peripheral_mode_prefs.py -v diff --git a/platformio.ini b/platformio.ini index c81619e45..177a86a1b 100644 --- a/platformio.ini +++ b/platformio.ini @@ -178,6 +178,7 @@ extra_scripts = create-uf2.py pre:scripts/nrf52_ble_dfu_fix.py pre:scripts/nrf52_loop_stack_fix.py pre:scripts/nrf52_hil_irq_observer.py + pre:scripts/nrf52_hil_spim1.py pre:scripts/nrf52_internal_bootloader_link.py ; Nordic's builder otherwise overwrites the LTO-aware archive tools. pre:scripts/nrf52_lto_toolchain.py diff --git a/scripts/nrf52_hil_spim1.py b/scripts/nrf52_hil_spim1.py new file mode 100644 index 000000000..2c124f575 --- /dev/null +++ b/scripts/nrf52_hil_spim1.py @@ -0,0 +1,96 @@ +"""Bind a default-off Tag/Tower radio experiment to SPIM1 in private copies. + +Global SPI keeps the board's existing initialization, recovery, and shutdown +ownership. SPI1 remains on SPIM2 for SD/display. The nrfx configuration must be +identical in every C/C++ translation unit, so force it before driver headers. +Never modify the installed framework and fail closed on a framework update. +""" + +import hashlib +import importlib.util +from pathlib import Path + + +FLAG = "MC_NRF52_HIL_SPIM1_RADIO" +SDK_FILES = { + "cores/nRF5/nordic/nrfx_config.h": "36c2e96f77a7a1b872f6ace9d880d5c7b5525f45f2498e21feb414d1ca589ff9", + "libraries/SPI/SPI.cpp": "8ab92597c833c3351c0f4a5c8c07a84290815f95cf35b60c58209cab368accfb", +} +OLD_MAPPING = " #define _SPI_DEV NRF_SPIM3 // 32 Mhz\n #define _SPI1_DEV NRF_SPIM2\n" +NEW_MAPPING = " #define _SPI_DEV NRF_SPIM1 // Private Tag/Tower radio HIL candidate\n #define _SPI1_DEV NRF_SPIM2\n" +OLD_INCLUDE = '#include "SPI.h"\n' +NEW_INCLUDE = OLD_INCLUDE + '#include \n' + + +def digest(source): + return hashlib.sha256(source.replace("\r\n", "\n").encode("ascii")).hexdigest() + + +def patched_spi(source): + source = source.replace("\r\n", "\n") + if digest(source) != SDK_FILES["libraries/SPI/SPI.cpp"]: + raise RuntimeError("nRF52 HIL SPIM1: changed pinned SPI.cpp; review before building") + if source.count(OLD_MAPPING) != 1 or source.count(OLD_INCLUDE) != 1: + raise RuntimeError("nRF52 HIL SPIM1: unrecognized global SPI binding") + return source.replace(OLD_MAPPING, NEW_MAPPING, 1).replace(OLD_INCLUDE, NEW_INCLUDE, 1) + + +def values_for(build_env): + parser_path = Path(build_env.subst("$PROJECT_DIR")) / "scripts/nrf52_flash_trim.py" + spec = importlib.util.spec_from_file_location("mesh_spim1_flag_parser", parser_path) + parser = importlib.util.module_from_spec(spec) + spec.loader.exec_module(parser) + return parser.flag_defines(build_env.get("BUILD_FLAGS", ()), build_env.get("CPPDEFINES", ())) + + +def enabled(values): + value = values.get(FLAG) + if value is None: + return False + if str(value).strip("() ") not in ("0", "1"): + raise RuntimeError("nRF52 HIL SPIM1 radio flag must be 0 or 1") + return str(value).strip("() ") == "1" + + +def replace_spi(build_env, node): + source = Path(node.srcnode().get_abspath()) + if source.name != "SPI.cpp" or source.parent.name != "SPI": + raise RuntimeError("nRF52 HIL SPIM1: unexpected SPI middleware source") + patched = patched_spi(source.read_text(encoding="ascii")) + destination = Path(build_env.subst("$BUILD_DIR")) / "patched-nrf52-hil-spim1/SPI.cpp" + destination.parent.mkdir(parents=True, exist_ok=True) + if not destination.exists() or destination.read_text(encoding="ascii") != patched: + destination.write_text(patched, encoding="ascii") + build_env.AppendUnique(CPPPATH=[str(source.parent), build_env.subst("$PROJECT_DIR/src")]) + return build_env.File(str(destination)) + + +def install(build_env): + values = values_for(build_env) + if not enabled(values): + return + if (build_env.PioPlatform().name != "nordicnrf52" + or build_env.BoardConfig().get("build.mcu", "").lower() != "nrf52840"): + raise RuntimeError("nRF52 HIL SPIM1 requires the pinned nRF52840 core") + boards = [name for name in ("RAK_WISMESH_TAG", "HELTEC_TOWER_V2") if values.get(name) is not None] + if len(boards) != 1: + raise RuntimeError("nRF52 HIL SPIM1 supports only RAK WisMesh Tag or MeshTower V2") + if any(values.get(name) is not None for name in ("ETHERNET_ENABLED", "ENV_PIN_SDA", "ENV_PIN_SCL")): + raise RuntimeError("nRF52 HIL SPIM1 has an unreviewed Ethernet or secondary I2C owner") + framework = build_env.PioPlatform().get_package_dir("framework-arduinoadafruitnrf52") + if not framework: + raise RuntimeError("nRF52 HIL SPIM1 cannot find the pinned framework") + for name, expected in SDK_FILES.items(): + source = Path(framework) / name + if digest(source.read_text(encoding="ascii")) != expected: + raise RuntimeError("nRF52 HIL SPIM1: changed pinned " + name + "; review before building") + build_env.AppendUnique(CPPDEFINES=[("MC_NRF52_HIL_SPIM1_BOUND", 1)]) + # Keep the option and argument in one token: another pre-script adds its + # own -include pair with AppendUnique, which deduplicates bare options. + build_env.AppendUnique(CCFLAGS=["-include" + build_env.subst("$PROJECT_DIR/src/helpers/nrf52/Nrf52HilSpim1Config.h")]) + build_env.AddBuildMiddleware(replace_spi, "*libraries*SPI*SPI.cpp") + + +if "Import" in globals(): + Import("env") + install(env) diff --git a/src/helpers/nrf52/Nrf52HilSpim1Config.h b/src/helpers/nrf52/Nrf52HilSpim1Config.h new file mode 100644 index 000000000..47b3fe327 --- /dev/null +++ b/src/helpers/nrf52/Nrf52HilSpim1Config.h @@ -0,0 +1,56 @@ +#pragma once + +// Private physical-qualification candidate. All ordinary recipes retain their +// existing controller, clock, and byte-at-a-time transport. +#ifndef MC_NRF52_HIL_SPIM1_RADIO +#define MC_NRF52_HIL_SPIM1_RADIO 0 +#endif +#if MC_NRF52_HIL_SPIM1_RADIO != 0 && MC_NRF52_HIL_SPIM1_RADIO != 1 +#error "nRF52 HIL SPIM1 radio flag must be 0 or 1" +#endif + +#if MC_NRF52_HIL_SPIM1_RADIO +#if !defined(NRF52_PLATFORM) || !defined(NRF52840_XXAA) +#error "nRF52 HIL SPIM1 radio requires the nRF52840 core" +#endif +#if (defined(RAK_WISMESH_TAG) + defined(HELTEC_TOWER_V2)) != 1 +#error "nRF52 HIL SPIM1 radio supports only RAK WisMesh Tag or MeshTower V2" +#endif +#if !defined(MC_NRF52_HIL_SPIM1_BOUND) || MC_NRF52_HIL_SPIM1_BOUND != 1 +#error "nRF52 HIL SPIM1 radio requires its private SDK binding script" +#endif +#if defined(ETHERNET_ENABLED) || defined(ENV_PIN_SDA) || defined(ENV_PIN_SCL) +#error "nRF52 HIL SPIM1 radio has an unreviewed Ethernet or secondary I2C owner" +#endif +#if defined(SPI_32MHZ_INTERFACE) && SPI_32MHZ_INTERFACE != 0 +#error "nRF52 HIL SPIM1 radio must preserve SPI1 on SPIM2" +#endif +#if defined(NRFX_SPIM3_NRF52840_ANOMALY_198_WORKAROUND_ENABLED) && NRFX_SPIM3_NRF52840_ANOMALY_198_WORKAROUND_ENABLED +#error "nRF52 HIL SPIM1 radio must not enable the SPIM3 protected-register workaround" +#endif +#if defined(MC_XIAO_NRF52_HIL_FAST_SPI) && MC_XIAO_NRF52_HIL_FAST_SPI +#error "nRF52 HIL SPIM1 and XIAO SPI candidates are separate" +#endif +#if defined(NRFX_H__) || defined(NRFX_SPIM_H__) +#error "nRF52 HIL SPIM1 configuration must precede nrfx driver headers" +#endif + +// This file is force-included in every C and C++ translation unit, including +// SPI.cpp and nrfx_spim.c. The original guard keeps later includes from +// resetting the configuration and changing driver instance indices. +#include +#if NRFX_SPIM0_ENABLED != 0 || NRFX_SPIM1_ENABLED != 0 || NRFX_SPIM2_ENABLED != 1 || NRFX_SPIM3_ENABLED != 1 +#error "nRF52 HIL SPIM1 radio requires the reviewed SDK controller configuration" +#endif +#if (defined(NRFX_TWIM1_ENABLED) && NRFX_TWIM1_ENABLED) || (defined(NRFX_TWI1_ENABLED) && NRFX_TWI1_ENABLED) || (defined(NRFX_TWIS1_ENABLED) && NRFX_TWIS1_ENABLED) || NRFX_SPIS1_ENABLED +#error "nRF52 HIL SPIM1 radio cannot share an enabled nrfx I2C or SPI slave driver" +#endif +#undef NRFX_SPIM1_ENABLED +#define NRFX_SPIM1_ENABLED 1 +#undef NRFX_TWIM1_ENABLED +#define NRFX_TWIM1_ENABLED 0 +#undef NRFX_TWI1_ENABLED +#define NRFX_TWI1_ENABLED 0 +#undef NRFX_TWIS1_ENABLED +#define NRFX_TWIS1_ENABLED 0 +#endif diff --git a/src/helpers/nrf52/Nrf52HilSpim1Owner.h b/src/helpers/nrf52/Nrf52HilSpim1Owner.h new file mode 100644 index 000000000..1bc81a896 --- /dev/null +++ b/src/helpers/nrf52/Nrf52HilSpim1Owner.h @@ -0,0 +1,17 @@ +#pragma once + +#include "Nrf52HilSpim1Config.h" + +#if MC_NRF52_HIL_SPIM1_RADIO +// variant.h is available here, unlike the globally forced early SDK config. +// Direct-register Wire1 owns the same peripheral and interrupt as SPIM1. +#if !defined(WIRE_INTERFACES_COUNT) || WIRE_INTERFACES_COUNT != 1 +#error "nRF52 HIL SPIM1 radio requires a variant with only the primary I2C bus" +#endif +#if !defined(SPI_INTERFACES_COUNT) || SPI_INTERFACES_COUNT < 1 || SPI_INTERFACES_COUNT > 2 +#error "nRF52 HIL SPIM1 radio requires the reviewed one- or two-bus SPI variant" +#endif +#if NRFX_SPIM1_ENABLED != 1 || NRFX_TWIM1_ENABLED != 0 || NRFX_TWI1_ENABLED != 0 || NRFX_TWIS1_ENABLED != 0 +#error "nRF52 HIL SPIM1 radio lost its global SDK controller configuration" +#endif +#endif diff --git a/test/test_nrf52_hil_spim1.py b/test/test_nrf52_hil_spim1.py new file mode 100644 index 000000000..1627b53fd --- /dev/null +++ b/test/test_nrf52_hil_spim1.py @@ -0,0 +1,278 @@ +"""Exercise the private Tag/Tower SPI mapping, SDK indices and legacy defaults.""" + +import importlib.util +import os +from pathlib import Path +import re +import shutil +import subprocess +import tempfile +import types +import unittest + +from test_radio_receive_contract import method +from test_sx126x_buffered_radio_hal import MOCK + + +ROOT = Path(__file__).resolve().parents[1] +SDK = Path.home() / ".platformio/packages/framework-arduinoadafruitnrf52" +SPEC = importlib.util.spec_from_file_location("nrf52_hil_spim1", ROOT / "scripts/nrf52_hil_spim1.py") +PATCH = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(PATCH) +CONFIG = ROOT / "src/helpers/nrf52/Nrf52HilSpim1Config.h" +OWNER = ROOT / "src/helpers/nrf52/Nrf52HilSpim1Owner.h" +BASE = ["-DNRF52_PLATFORM", "-DNRF52840_XXAA"] +FAST = ["-DMC_NRF52_HIL_SPIM1_RADIO=1", "-DMC_NRF52_HIL_SPIM1_BOUND=1"] + + +class BuildEnv(dict): + def __init__(self, directory, flags=(), defines=(), mcu="nrf52840", platform="nordicnrf52"): + super().__init__(BUILD_FLAGS=flags, CPPDEFINES=list(defines)) + self.directory, self.mcu, self.platform = directory, mcu, platform + self.middleware = [] + + def subst(self, value): + return value.replace("$PROJECT_DIR", str(ROOT)).replace("$BUILD_DIR", str(self.directory)) + + def PioPlatform(self): + return types.SimpleNamespace(name=self.platform, get_package_dir=lambda name: str(SDK)) + + def BoardConfig(self): + return {"build.mcu": self.mcu} + + def AppendUnique(self, **kwargs): + for name, values in kwargs.items(): + self.setdefault(name, []) + self[name].extend(value for value in values if value not in self[name]) + + def AddBuildMiddleware(self, callback, pattern): + self.middleware.append((callback, pattern)) + + def File(self, value): + return Path(value) + + +@unittest.skipUnless(SDK.is_dir(), "pinned nRF52 framework package unavailable") +class Nrf52HilSpim1Tests(unittest.TestCase): + def command(self, args, **kwargs): + result = subprocess.run(args, capture_output=True, text=True, timeout=60, **kwargs) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + return result + + def test_default_registers_no_hook_or_forced_sdk_configuration(self): + with tempfile.TemporaryDirectory(dir="/var/tmp") as directory: + for flags in ((), "-DMC_NRF52_HIL_SPIM1_RADIO=0", "-UMC_NRF52_HIL_SPIM1_RADIO"): + env = BuildEnv(Path(directory) / "not-created", flags) + PATCH.install(env) + self.assertEqual(env.middleware, []) + self.assertNotIn("CCFLAGS", env) + self.assertFalse(env.directory.exists()) + + def test_scons_entry_and_private_sdk_copy_are_bound_without_editing_sdk(self): + source = (ROOT / "scripts/nrf52_hil_spim1.py").read_text(encoding="ascii") + with tempfile.TemporaryDirectory(dir="/var/tmp") as directory: + directory = Path(directory) + env = BuildEnv(directory, "-DMC_NRF52_HIL_SPIM1_RADIO=1 -DRAK_WISMESH_TAG") + scope = {"Import": lambda name: scope.update(env=env)} + exec(compile(source, "nrf52_hil_spim1.py", "exec"), scope) + self.assertNotIn("__file__", scope) + self.assertEqual(len(env.middleware), 1) + self.assertEqual(env["CCFLAGS"], ["-include" + str(CONFIG)]) + self.assertIn(("MC_NRF52_HIL_SPIM1_BOUND", 1), env["CPPDEFINES"]) + sdk_path = SDK / "libraries/SPI/SPI.cpp" + original = sdk_path.read_bytes() + node = types.SimpleNamespace(srcnode=lambda: types.SimpleNamespace(get_abspath=lambda: str(sdk_path))) + private = PATCH.replace_spi(env, node) + self.assertTrue(private.is_relative_to(directory)) + self.assertEqual(private.read_text(), PATCH.patched_spi(original.decode("ascii"))) + self.assertEqual(sdk_path.read_bytes(), original) + stamp = private.stat().st_mtime_ns + self.assertEqual(PATCH.replace_spi(env, node).stat().st_mtime_ns, stamp) + with self.assertRaises(RuntimeError): + PATCH.patched_spi(original.decode("ascii") + "// SDK changed\n") + + def test_build_script_rejects_unsupported_targets_and_new_bus_owners(self): + with tempfile.TemporaryDirectory(dir="/var/tmp") as directory: + for flags, extra in ( + ("-DMC_NRF52_HIL_SPIM1_RADIO=2", {}), + ("-DMC_NRF52_HIL_SPIM1_RADIO=1 -DHELTEC_T096", {}), + ("-DMC_NRF52_HIL_SPIM1_RADIO=1 -DHELTEC_TOWER_V2 -DRAK_WISMESH_TAG", {}), + ("-DMC_NRF52_HIL_SPIM1_RADIO=1 -DRAK_WISMESH_TAG -DETHERNET_ENABLED=0", {}), + ("-DMC_NRF52_HIL_SPIM1_RADIO=1 -DRAK_WISMESH_TAG -DENV_PIN_SDA=4", {}), + ("-DMC_NRF52_HIL_SPIM1_RADIO=1 -DRAK_WISMESH_TAG", {"mcu": "nrf52832"}), + ("-DMC_NRF52_HIL_SPIM1_RADIO=1 -DRAK_WISMESH_TAG", {"platform": "espressif32"}), + ): + with self.subTest(flags=flags, extra=extra), self.assertRaises(RuntimeError): + PATCH.install(BuildEnv(Path(directory), flags, **extra)) + + def test_real_sdk_mapping_indices_constructor_recovery_and_second_bus(self): + compiler = shutil.which(os.environ.get("CXX", "g++")) + self.assertIsNotNone(compiler) + sdk_source = (SDK / "libraries/SPI/SPI.cpp").read_text() + sdk_header = (SDK / "cores/nRF5/nordic/nrfx/drivers/include/nrfx_spim.h").read_text() + enum = re.search(r"enum \{\n#if NRFX_CHECK\(NRFX_SPIM0_ENABLED\).*?\n\};", sdk_header, re.S).group(0) + sdk_constructor = sdk_source[sdk_source.index("SPIClass::SPIClass("):sdk_source.index("void SPIClass::begin()")] + mock = MOCK.replace("struct SPIClass {", r''' +struct MockSpim { unsigned number; }; +inline MockSpim dev1{1},dev2{2},dev3{3}; +inline MockSpim* NRF_SPIM1=&dev1; +inline MockSpim* NRF_SPIM2=&dev2; +inline MockSpim* NRF_SPIM3=&dev3; +using NRF_SPIM_Type=MockSpim; +inline unsigned g_ADigitalPinMap[48]={}; +#define NRF_SPIM_BIT_ORDER_MSB_FIRST 0 +struct SPIClass { + struct { MockSpim* p_reg; unsigned drv_inst_idx; } _spim; + void* _p_spi=nullptr; + bool initialized=false; + unsigned _uc_pinMiso=0,_uc_pinSCK=0,_uc_pinMosi=0,_dataMode=0,_bitOrder=0; + SPIClass(NRF_SPIM_Type*,uint8_t,uint8_t,uint8_t); + void setPins(unsigned miso,unsigned sck,unsigned mosi) { _uc_pinMiso=miso;_uc_pinSCK=sck;_uc_pinMosi=mosi; } +''') + for board, variant in (("RAK_WISMESH_TAG", "rak_wismesh_tag"), ("HELTEC_TOWER_V2", "heltec_tower_v2")): + text = (ROOT / "variants" / variant / "target.cpp").read_text() + start = text.index("#if MC_NRF52_HIL_SPIM1_RADIO\nstatic") + constructor = text[start:text.index("#endif", start) + len("#endif")] + initialization = method(text, "bool radio_init()") + for fast in (False, True): + with self.subTest(board=board, fast=fast), tempfile.TemporaryDirectory(dir="/var/tmp") as directory: + directory = Path(directory) + (directory / "hal/Arduino").mkdir(parents=True) + (directory / "hal/Arduino/ArduinoHal.h").write_text(mock, encoding="ascii") + mapping_source = PATCH.patched_spi(sdk_source) if fast else sdk_source + mapping = mapping_source[mapping_source.index("#ifndef SPI_32MHZ_INTERFACE"):mapping_source.rindex("#endif // NRF52840_XXAA")] + fixture = r''' +#include +#include +#define NRFX_CHECK(value) (value) +@ENUM@ +#include +#define SPI_INTERFACES_COUNT 2 +#define WIRE_INTERFACES_COUNT 1 +#include +#include +#define PIN_SPI_MISO 9 +#define PIN_SPI_MOSI 10 +#define PIN_SPI_SCK 8 +#define PIN_SPI1_MISO 25 +#define PIN_SPI1_MOSI 26 +#define PIN_SPI1_SCK 29 +constexpr unsigned P_LORA_NSS=4,P_LORA_DIO_1=1,P_LORA_RESET=2,P_LORA_BUSY=3; +@SDK_CONSTRUCTOR@ +@MAPPING@ +struct Module { + ArduinoHal* hal; bool owns; + Module(ArduinoHal* a,unsigned,unsigned,unsigned,unsigned):hal(a),owns(false) {} + Module(unsigned a,unsigned b,unsigned c,unsigned d,SPIClass& bus) + :Module(new ArduinoHal(bus,SPISettings(2000000,MSBFIRST,SPI_MODE0)),a,b,c,d) {owns=true;} + ~Module() {if(owns)delete hal;} +}; +struct Radio { + Module* module; bool next=true; unsigned starts=0; + Radio(Module* value):module(value) {} ~Radio(){delete module;} + bool std_init(SPIClass* bus) {assert(bus==&SPI && module->hal->spi==bus);bus->begin();++starts;return next;} +}; +#define RADIO_CLASS Radio +@CONSTRUCTOR@ +unsigned Wire=0; +struct Rtc {void begin(unsigned){}} rtc_clock; +@INITIALIZATION@ +extern "C" unsigned c_indices(void); +int main() { + assert(SPI._spim.p_reg->number==(MC_NRF52_HIL_SPIM1_RADIO?1:3)); + assert(SPI1._spim.p_reg->number==2); + assert(SPI._spim.drv_inst_idx==(MC_NRF52_HIL_SPIM1_RADIO?0:1)); + assert(SPI1._spim.drv_inst_idx==unsigned(MC_NRF52_HIL_SPIM1_RADIO)); + assert(c_indices()==(MC_NRF52_HIL_SPIM1_RADIO?0x3210u:0x2100u)); + assert(radio.module->hal->spi==&SPI && !radio.module->hal->initInterface); + assert(radio.module->hal->spiSettings.hz==(MC_NRF52_HIL_SPIM1_RADIO?8000000:2000000)); + assert(radio_init() && SPI.begins==1 && SPI1.begins==0); + uint8_t tx[]={0x86,1,2,3},rx[4]={};radio.module->hal->spiTransfer(tx,4,rx); + assert(SPI.bursts==unsigned(MC_NRF52_HIL_SPIM1_RADIO)); + assert(SPI.bytes==unsigned(MC_NRF52_HIL_SPIM1_RADIO?0:4)); + assert(rx[3]==uint8_t(tx[3]^0xa5)); + radio.module->hal->init();radio.module->hal->term();assert(SPI.ends==0); + SPI.end();radio.next=false;assert(!radio_init());radio.next=true;assert(radio_init()); + assert(SPI.ends==1 && SPI.begins==3 && radio.starts==3 && SPI1.begins==0); +} +'''.replace("@ENUM@", enum).replace("@SDK_CONSTRUCTOR@", sdk_constructor).replace("@MAPPING@", mapping).replace("@CONSTRUCTOR@", constructor).replace("@INITIALIZATION@", initialization) + c_source = '#include \n#define NRFX_CHECK(value) (value)\n' + enum + r''' +unsigned c_indices(void) { +#if MC_NRF52_HIL_SPIM1_RADIO + return NRFX_SPIM_ENABLED_COUNT*0x1000u+NRFX_SPIM3_INST_IDX*0x100u+NRFX_SPIM2_INST_IDX*0x10u+NRFX_SPIM1_INST_IDX; +#else + return NRFX_SPIM_ENABLED_COUNT*0x1000u+NRFX_SPIM3_INST_IDX*0x100u+NRFX_SPIM2_INST_IDX*0x10u; +#endif +} +''' + cpp, c, obj, executable = [directory / name for name in ("test.cpp", "indices.c", "indices.o", "test")] + cpp.write_text(fixture, encoding="ascii") + c.write_text(c_source, encoding="ascii") + flags = BASE + ["-D" + board, "-I" + str(SDK / "cores/nRF5/nordic"), "-I" + str(ROOT / "src"), "-I" + str(directory)] + if fast: + flags += FAST + ["-include" + str(CONFIG)] + self.command(["gcc", "-std=c11", "-Wall", "-Wextra", "-Werror", *flags, "-c", str(c), "-o", str(obj)]) + self.command([compiler, "-std=c++17", "-Wall", "-Wextra", "-Werror", *flags, str(cpp), str(obj), "-o", str(executable)]) + self.command([str(executable)]) + + def test_compile_gates_reject_conflicting_or_unbound_candidates(self): + with tempfile.TemporaryDirectory(dir="/var/tmp") as directory: + directory = Path(directory) + source = directory / "gate.cpp" + source.write_text('#include \n', encoding="ascii") + valid = BASE + FAST + ["-DRAK_WISMESH_TAG", "-DWIRE_INTERFACES_COUNT=1", "-DSPI_INTERFACES_COUNT=2"] + for flags in ( + ["-DMC_NRF52_HIL_SPIM1_RADIO=2"], + FAST, + BASE + FAST + ["-DHELTEC_T096"], + [item for item in valid if "_BOUND=" not in item], + valid + ["-DSPI_32MHZ_INTERFACE=1"], + valid + ["-DETHERNET_ENABLED=0"], + valid + ["-DENV_PIN_SCL=4"], + valid + ["-DNRFX_SPIM3_NRF52840_ANOMALY_198_WORKAROUND_ENABLED=1"], + valid + ["-DNRFX_H__"], + [item for item in valid if "WIRE_INTERFACES_COUNT=" not in item] + ["-DWIRE_INTERFACES_COUNT=2"], + ): + with self.subTest(flags=flags): + result = subprocess.run(["g++", "-E", *flags, "-I" + str(ROOT / "src"), "-I" + str(SDK / "cores/nRF5/nordic"), str(source)], capture_output=True, text=True, timeout=15) + self.assertNotEqual(result.returncode, 0, result.stdout) + self.assertIn("nRF52 HIL SPIM1", result.stderr) + + def test_actual_sdk_spim1_vector_and_wire1_owner_do_not_collide(self): + driver = (SDK / "cores/nRF5/nordic/nrfx/drivers/src/nrfx_spim.c").read_text() + header = (SDK / "cores/nRF5/nordic/nrfx/drivers/include/nrfx_spim.h").read_text() + aliases = (SDK / "cores/nRF5/nordic/nrfx/soc/nrfx_irqs_nrf52840.h").read_text() + wire = (SDK / "libraries/Wire/Wire_nRF52.cpp").read_text() + enum = re.search(r"enum \{\n#if NRFX_CHECK\(NRFX_SPIM0_ENABLED\).*?\n\};", header, re.S).group(0) + alias = re.search(r"^#define nrfx_spim_1_irq_handler\s+\S+", aliases, re.M).group(0) + body = re.search(r"#if NRFX_CHECK\(NRFX_SPIM1_ENABLED\)\nvoid nrfx_spim_1_irq_handler\(void\)\n\{.*?\n\}\n#endif", driver, re.S).group(0) + wire_owner = wire[wire.index("#if WIRE_INTERFACES_COUNT > 1"):wire.rindex("#endif // NRF52_SERIES")] + source = '#include \n#include \n#define NRFX_CHECK(value) (value)\n' + enum + "\n" + alias + r''' +unsigned calls=0, m_cb[NRFX_SPIM_ENABLED_COUNT]={}; +constexpr unsigned NRF_SPIM1=1; +void irq_handler(unsigned device,unsigned* control) { + assert(device==1 && control==&m_cb[NRFX_SPIM1_INST_IDX]);++calls; +} +''' + body + "\n" + wire_owner + r''' +int main() {SPIM1_SPIS1_TWIM1_TWIS1_SPI1_TWI1_IRQHandler();assert(calls==1);} +''' + with tempfile.TemporaryDirectory(dir="/var/tmp") as directory: + directory = Path(directory) + cpp, executable = directory / "irqs.cpp", directory / "irqs" + cpp.write_text(source, encoding="ascii") + self.command(["g++", "-std=c++17", "-Wall", "-Wextra", "-Werror", *BASE, *FAST, + "-DRAK_WISMESH_TAG", "-DWIRE_INTERFACES_COUNT=1", "-DSPI_INTERFACES_COUNT=2", + "-I" + str(ROOT / "src"), "-I" + str(SDK / "cores/nRF5/nordic"), + "-include" + str(CONFIG), str(cpp), "-o", str(executable)]) + self.command([str(executable)]) + + def test_production_recipes_and_t096_features_are_unchanged(self): + active = "\n".join(line for path in [ROOT / "platformio.ini", *sorted((ROOT / "variants").glob("*/platformio.ini"))] for line in path.read_text().splitlines() if not line.lstrip().startswith(";")) + self.assertNotIn("-DMC_NRF52_HIL_SPIM1_RADIO", active) + self.assertIn("pre:scripts/nrf52_hil_spim1.py", active) + self.assertNotIn("MC_NRF52_HIL_SPIM1_RADIO", (ROOT / "variants/heltec_t096/target.cpp").read_text()) + self.assertRegex((ROOT / "variants/heltec_t096/variant.h").read_text(), r"#define WIRE_INTERFACES_COUNT\s+\(2\)") + + +if __name__ == "__main__": + unittest.main() diff --git a/test/test_sx126x_nrf_rp_constructors.py b/test/test_sx126x_nrf_rp_constructors.py index 19e56f4ab..cb4fb6564 100644 --- a/test/test_sx126x_nrf_rp_constructors.py +++ b/test/test_sx126x_nrf_rp_constructors.py @@ -128,6 +128,10 @@ void check() {{ # Its separate constructor test executes the default-off # candidate gate and actual legacy/opt-in branches. self.assertIn("#if MC_XIAO_NRF52_HIL_FAST_SPI",text) + elif source.parent.name in {"rak_wismesh_tag", "heltec_tower_v2"}: + # Their SPIM1 candidate is also default-off, with the actual + # global SDK binding exercised by its separate native test. + self.assertIn("#if MC_NRF52_HIL_SPIM1_RADIO",text) else: self.assertNotIn("BufferedRadioHal",text,str(source)) constructions=re.findall(r"^RADIO_CLASS radio = new Module\(P_LORA_NSS[^;]+;",text,re.MULTILINE) diff --git a/variants/heltec_tower_v2/target.cpp b/variants/heltec_tower_v2/target.cpp index ec8e7a17d..a3838e4b8 100644 --- a/variants/heltec_tower_v2/target.cpp +++ b/variants/heltec_tower_v2/target.cpp @@ -2,11 +2,20 @@ #include #include +#include +#if MC_NRF52_HIL_SPIM1_RADIO +#include +#endif #include HeltecTowerV2Board board; +#if MC_NRF52_HIL_SPIM1_RADIO +static Nrf52BufferedRadioHal radioHal(SPI, 8000000); +RADIO_CLASS radio = new Module(&radioHal, P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY); +#else RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, SPI); +#endif WRAPPER_CLASS radio_driver(radio, board); diff --git a/variants/rak_wismesh_tag/target.cpp b/variants/rak_wismesh_tag/target.cpp index 4547ef510..2fe81c371 100644 --- a/variants/rak_wismesh_tag/target.cpp +++ b/variants/rak_wismesh_tag/target.cpp @@ -1,6 +1,10 @@ #include #include "target.h" #include +#include +#if MC_NRF52_HIL_SPIM1_RADIO +#include +#endif RAKWismeshTagBoard board; @@ -13,7 +17,12 @@ RAKWismeshTagBoard board; MomentaryButton user_btn(PIN_USER_BTN, 1000, true, true); #endif +#if MC_NRF52_HIL_SPIM1_RADIO +static Nrf52BufferedRadioHal radioHal(SPI, 8000000); +RADIO_CLASS radio = new Module(&radioHal, P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY); +#else RADIO_CLASS radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, SPI); +#endif WRAPPER_CLASS radio_driver(radio, board);