diff --git a/.github/workflows/run-unit-tests.yml b/.github/workflows/run-unit-tests.yml index 4d5e5233d..b2b4b217c 100644 --- a/.github/workflows/run-unit-tests.yml +++ b/.github/workflows/run-unit-tests.yml @@ -816,6 +816,8 @@ jobs: python3 -B test/test_sx126x_buffered_radio_hal.py -v python3 -B test/test_profile_switch_timing.py -v python3 -B test/test_nrf_radio_yield_budget.py -v + python3 -B test/test_nrf_radio_priority_lease.py -v + python3 -B test/test_nrf_radio_priority_integration.py -v python3 -B test/test_sx126x_nrf_rp_constructors.py -v python3 -B test/test_esp32_buffered_radio_targets.py -v python3 -B test/test_xiao_battery_safety.py -v diff --git a/src/helpers/radiolib/CustomSX1262.h b/src/helpers/radiolib/CustomSX1262.h index 2855c639f..b0dc781d0 100644 --- a/src/helpers/radiolib/CustomSX1262.h +++ b/src/helpers/radiolib/CustomSX1262.h @@ -120,6 +120,12 @@ class CustomSX1262 : public SX1262 { void beginProfileSwitch(bool continuousRx) { _profileSwitch.begin(continuousRx, standbyXOSC); } void endProfileSwitch(bool success) { _profileSwitch.end(success); } bool profileSwitchFailed() const { return _profileSwitch.failed(); } +#if defined(MC_NRF_RADIO_PROFILE_PRIORITY) && MC_NRF_RADIO_PROFILE_PRIORITY + bool hilOwnsWarmProfileRetune() const { + return _profileSwitch.open && _profileSwitch.active + && _profileSwitch.rxValid && !_coldStandby; + } +#endif uint32_t getOptimizedProfileSwitches() const { return _profileFastResumes; } #ifdef MC_SX1262_HIL // Same-image lab baseline: force only 0x8B, preserving fast RX ownership. diff --git a/src/helpers/radiolib/CustomSX1262Wrapper.h b/src/helpers/radiolib/CustomSX1262Wrapper.h index 135d460cc..1315e5650 100644 --- a/src/helpers/radiolib/CustomSX1262Wrapper.h +++ b/src/helpers/radiolib/CustomSX1262Wrapper.h @@ -24,6 +24,11 @@ protected: void endProfileRetune(bool success) override { static_cast(_radio)->endProfileSwitch(success); } +#if defined(MC_NRF_RADIO_PROFILE_PRIORITY) && MC_NRF_RADIO_PROFILE_PRIORITY + bool ownsWarmProfileRetune() const override { + return static_cast(_radio)->hilOwnsWarmProfileRetune(); + } +#endif void setProfileStandbyWarm(bool enabled) override { if (enabled == _profile_standby_held) return; diff --git a/src/helpers/radiolib/Nrf52BufferedRadioHal.h b/src/helpers/radiolib/Nrf52BufferedRadioHal.h index be855c5e8..56aa7bd37 100644 --- a/src/helpers/radiolib/Nrf52BufferedRadioHal.h +++ b/src/helpers/radiolib/Nrf52BufferedRadioHal.h @@ -2,6 +2,13 @@ #include +#ifndef MC_NRF_RADIO_PROFILE_PRIORITY +#define MC_NRF_RADIO_PROFILE_PRIORITY 0 +#endif +#if MC_NRF_RADIO_PROFILE_PRIORITY +#include "NrfRadioPriorityLease.h" +#endif + #ifndef MC_NRF_RADIO_BUSY_SPIN_POLLS #define MC_NRF_RADIO_BUSY_SPIN_POLLS 0 #endif @@ -20,6 +27,15 @@ public: explicit Nrf52BufferedRadioHal(SPIClass& bus, uint32_t hz = 16000000) : ArduinoHal(bus, SPISettings(hz, MSBFIRST, SPI_MODE0)) {} +#if MC_NRF_RADIO_PROFILE_PRIORITY + void spiBeginTransaction() override { + // Check before RadioLib lowers CS, so restoring task priority does not + // suspend this task with a newly selected, unclocked radio command. + mesh::radiopriority::beforeFrame(); + ArduinoHal::spiBeginTransaction(); + } +#endif + void spiTransfer(uint8_t* out, size_t len, uint8_t* in) override { if (!len) return; spi->transfer(out, in, len); @@ -28,17 +44,27 @@ public: #endif } -#if MC_NRF_RADIO_BUSY_SPIN_POLLS > 0 +#if MC_NRF_RADIO_BUSY_SPIN_POLLS > 0 || MC_NRF_RADIO_PROFILE_PRIORITY // Diagnostic only, off by default. RadioLib calls yield() during SPI BUSY // polls and other waits. Spend at most N non-yielding polls after a real // frame, then delegate every call until another frame resets the budget. // An unused budget can reach a later non-BUSY wait; this is not BUSY-only // detection. No GPIO reads, status checks, timeouts or interrupts change. void yield() override { +#if MC_NRF_RADIO_PROFILE_PRIORITY + const auto decision = mesh::radiopriority::beforeYield(); + if (decision == mesh::radiopriority::Suppress) return; + if (decision == mesh::radiopriority::Expired) { + ArduinoHal::yield(); + return; + } +#endif +#if MC_NRF_RADIO_BUSY_SPIN_POLLS > 0 if (_busy_spin_polls_remaining) { --_busy_spin_polls_remaining; return; } +#endif ArduinoHal::yield(); } #endif diff --git a/src/helpers/radiolib/NrfRadioPriorityLease.cpp b/src/helpers/radiolib/NrfRadioPriorityLease.cpp new file mode 100644 index 000000000..01d4ce3a3 --- /dev/null +++ b/src/helpers/radiolib/NrfRadioPriorityLease.cpp @@ -0,0 +1,12 @@ +#include "NrfRadioPriorityLease.h" + +#if MC_NRF_RADIO_PROFILE_PRIORITY +namespace mesh { namespace radiopriority { +extern "C" { +volatile Capture mesh_hil_radio_priority = { + 0x4d435250, 1, sizeof(Capture), DeadlineTicks, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0}; +} +Work work = {}; +} } +#endif diff --git a/src/helpers/radiolib/NrfRadioPriorityLease.h b/src/helpers/radiolib/NrfRadioPriorityLease.h new file mode 100644 index 000000000..bbbe4fc0c --- /dev/null +++ b/src/helpers/radiolib/NrfRadioPriorityLease.h @@ -0,0 +1,127 @@ +#pragma once + +#ifndef MC_NRF_RADIO_PROFILE_PRIORITY +#define MC_NRF_RADIO_PROFILE_PRIORITY 0 +#endif +#if MC_NRF_RADIO_PROFILE_PRIORITY != 0 && MC_NRF_RADIO_PROFILE_PRIORITY != 1 +#error "Radio profile priority experiment must be 0 or 1" +#endif +#if MC_NRF_RADIO_PROFILE_PRIORITY +#if !defined(NRF52_PLATFORM) || !defined(MESH_HIL_PROFILE_TIMING) || !MESH_HIL_PROFILE_TIMING +#error "Radio profile priority experiment requires nRF52 HIL profile timing" +#endif + +#include +#include +#include + +namespace mesh { namespace radiopriority { + +static_assert(configMAX_PRIORITIES > TASK_PRIO_HIGH + 1, + "Radio priority experiment needs a task priority above USB"); +static constexpr uint32_t DeadlineTicks = 32; // about 0.977 ms at 32768 Hz +static constexpr uint32_t RtcMask = 0x00ffffff; +enum YieldDecision { Inactive, Suppress, Expired }; + +// Independent single-word counters for private read-only SWD observation. +// They are not an atomic multiword snapshot. All policy state is loop-owned. +struct Capture { + uint32_t magic, version, size_bytes, deadline_ticks; + uint32_t active, entries, releases, expired; + uint32_t skipped_not_owned, skipped_isr, skipped_nested; + uint32_t skipped_task, skipped_priority, suppressed_yields, frame_checks; +}; +struct Work { + TaskHandle_t owner; + uint32_t started_ticks; + bool active; +}; +extern "C" { +extern volatile Capture mesh_hil_radio_priority; +} +extern Work work; + +inline bool enter(bool owned_warm_rx) { + auto& capture = mesh_hil_radio_priority; + if (!owned_warm_rx) { ++capture.skipped_not_owned; return false; } + if (isInISR()) { ++capture.skipped_isr; return false; } + if (work.active) { ++capture.skipped_nested; return false; } + const TaskHandle_t owner = xTaskGetCurrentTaskHandle(); + const char* name = pcTaskGetName(owner); + if (!name || strcmp(name, "loop") != 0) { + ++capture.skipped_task; + return false; + } + // Effective elevated/inherited priorities are not a restorable base + // priority. This experiment admits only the known ordinary loop state. + if (uxTaskPriorityGet(owner) != TASK_PRIO_LOW) { + ++capture.skipped_priority; + return false; + } + work.owner = owner; + work.started_ticks = NRF_RTC2->COUNTER & RtcMask; + work.active = true; + capture.active = 1; + ++capture.entries; + vTaskPrioritySet(owner, TASK_PRIO_HIGH + 1); + return true; +} + +inline void release(bool expired = false) { + if (!work.active) return; + const TaskHandle_t owner = work.owner; + work.active = false; + work.owner = nullptr; + mesh_hil_radio_priority.active = 0; + ++mesh_hil_radio_priority.releases; + if (expired) ++mesh_hil_radio_priority.expired; + // Publish inactive BEFORE lowering priority, which can immediately let + // the USB task run. Only an admitted priority-1 loop can own this lease. + vTaskPrioritySet(owner, TASK_PRIO_LOW); +} + +inline bool isOwner() { + return work.active && !isInISR() && work.owner == xTaskGetCurrentTaskHandle(); +} + +inline bool checkDeadline() { + if (!isOwner()) return false; + if (((NRF_RTC2->COUNTER - work.started_ticks) & RtcMask) < DeadlineTicks) + return true; + release(true); + return false; +} + +inline void beforeFrame() { + if (!isOwner()) return; + ++mesh_hil_radio_priority.frame_checks; + (void)checkDeadline(); +} + +inline YieldDecision beforeYield() { + if (!isOwner()) return Inactive; + if (!checkDeadline()) return Expired; + ++mesh_hil_radio_priority.suppressed_yields; + return Suppress; +} + +// No scheduler suspension or IRQ masking. Normal BUSY polls lose the lease +// at the next yield/frame check after the RTC deadline. Existing nrfx's +// blocking transfer has no timeout hook: a hung peripheral cannot have a +// strict lease-time guarantee here and retains the board watchdog fallback. +class Lease { + bool _owns; +public: + explicit Lease(bool owned_warm_rx) : _owns(enter(owned_warm_rx)) {} + Lease(const Lease&) = delete; + Lease& operator=(const Lease&) = delete; + ~Lease() { release(); } + void release() { + if (!_owns) return; + _owns = false; + radiopriority::release(); + } +}; + +} } // namespace mesh::radiopriority +#endif diff --git a/src/helpers/radiolib/RadioLibWrappers.cpp b/src/helpers/radiolib/RadioLibWrappers.cpp index 7cc906e4f..b2eecd31d 100644 --- a/src/helpers/radiolib/RadioLibWrappers.cpp +++ b/src/helpers/radiolib/RadioLibWrappers.cpp @@ -4,6 +4,7 @@ #include "RadioInterruptEvents.h" #include "RadioProfileChip.h" #include "ProfileSwitchTiming.h" +#include "NrfRadioPriorityLease.h" #if MESH_HIL_PROFILE_TIMING namespace mesh { namespace profiletiming { extern "C" { @@ -643,12 +644,20 @@ mesh::RadioParamApplyResult RadioLibWrapper::tuneProfile(uint8_t profile) { mesh::profiletiming::begin(_active_profile, profile, mesh::profiletiming::readClock()); #endif beginProfileRetune(isInRecvMode() && !_rx_ps_armed && !_rx_ps_enabled); +#if MC_NRF_RADIO_PROFILE_PRIORITY + mesh::radiopriority::Lease profile_priority(dual_profile && _active_profile != profile + && ownsWarmProfileRetune()); +#endif const uint8_t resume = beginReconfigure(); if (resume > 1) { endProfileRetune(resume == 2); // Only a BUSY guard deferred before changing hardware. #if MESH_HIL_PROFILE_TIMING + const uint32_t finished_ticks = mesh::profiletiming::readClock(); +#if MC_NRF_RADIO_PROFILE_PRIORITY + profile_priority.release(); +#endif mesh::profiletiming::finish(resume == 2 ? mesh::profiletiming::Busy - : mesh::profiletiming::Failure, mesh::profiletiming::readClock()); + : mesh::profiletiming::Failure, finished_ticks); #endif return resume == 2 ? mesh::RadioParamApplyResult::BUSY : mesh::RadioParamApplyResult::FAILED; } @@ -696,7 +705,11 @@ mesh::RadioParamApplyResult RadioLibWrapper::tuneProfile(uint8_t profile) { #if MESH_HIL_PROFILE_TIMING // Finish before rollback: restoration is a different operation and must // not overwrite the failed hop's partial stage evidence. - mesh::profiletiming::finish(mesh::profiletiming::Failure, mesh::profiletiming::readClock()); + const uint32_t finished_ticks = mesh::profiletiming::readClock(); +#if MC_NRF_RADIO_PROFILE_PRIORITY + profile_priority.release(); +#endif + mesh::profiletiming::finish(mesh::profiletiming::Failure, finished_ticks); #endif ++_profiles.switch_failures; // RX restart is part of the transaction, not merely a best-effort tail. @@ -745,7 +758,11 @@ mesh::RadioParamApplyResult RadioLibWrapper::tuneProfile(uint8_t profile) { } #if MESH_HIL_PROFILE_TIMING mesh::profiletiming::mark(mesh::profiletiming::Tail, mesh::profiletiming::readClock()); - mesh::profiletiming::finish(mesh::profiletiming::Success, mesh::profiletiming::readClock()); + const uint32_t finished_ticks = mesh::profiletiming::readClock(); +#if MC_NRF_RADIO_PROFILE_PRIORITY + profile_priority.release(); +#endif + mesh::profiletiming::finish(mesh::profiletiming::Success, finished_ticks); #endif return applied ? mesh::RadioParamApplyResult::APPLIED : mesh::RadioParamApplyResult::FAILED; } diff --git a/src/helpers/radiolib/RadioLibWrappers.h b/src/helpers/radiolib/RadioLibWrappers.h index d7fe89457..6a9306266 100644 --- a/src/helpers/radiolib/RadioLibWrappers.h +++ b/src/helpers/radiolib/RadioLibWrappers.h @@ -387,6 +387,9 @@ protected: virtual void setProfileStandbyWarm(bool) {} virtual void beginProfileRetune(bool) {} virtual void endProfileRetune(bool) {} +#if defined(MC_NRF_RADIO_PROFILE_PRIORITY) && MC_NRF_RADIO_PROFILE_PRIORITY + virtual bool ownsWarmProfileRetune() const { return false; } +#endif // 0 = reconfigure from idle, 1 = resume RX afterwards, 2 = currently busy. uint8_t beginReconfigure(); void endReconfigure(bool resume_rx); diff --git a/test/test_nrf_radio_priority_integration.py b/test/test_nrf_radio_priority_integration.py new file mode 100644 index 000000000..6af06539e --- /dev/null +++ b/test/test_nrf_radio_priority_integration.py @@ -0,0 +1,151 @@ +"""Execute the real profile transaction's optional priority-lease boundaries.""" +from pathlib import Path +import unittest + +from test_radio_receive_contract import method +import test_profile_switch_timing as timing +import test_radio_profile_scan as scan + + +ROOT=Path(__file__).resolve().parents[1] + + +class NrfRadioPriorityIntegrationTests(unittest.TestCase): + compile_run=timing.ProfileSwitchTimingTest.compile_run + + def test_real_transaction_includes_entry_cost_and_releases_before_stats_or_rollback(self): + source=(ROOT/"src/helpers/radiolib/RadioLibWrappers.cpp").read_text() + methods="\n".join(method(source,signature) for signature in ( + "uint8_t RadioLibWrapper::beginReconfigure(", + "void RadioLibWrapper::endReconfigure(", + "mesh::RadioParamApplyResult RadioLibWrapper::tuneProfile(")) + fixture=scan.HARNESS.split("int main() {",1)[0] + fixture=fixture.replace("static uint64_t elapsed_us;",r''' +static uint64_t elapsed_us; +static bool priority_active=false,expected_owned=false,applied_priority[8]={}; +static unsigned entries=0,releases=0; +static uint32_t sequence_at_start=0; +''') + fixture=fixture.replace(" void beginProfileRetune(bool) {}",r''' + bool warm_allowed=true,retune_owned=false; + void beginProfileRetune(bool continuous) { retune_owned=continuous && warm_allowed; } + bool ownsWarmProfileRetune() const { return retune_owned; } +''').replace(" void endProfileRetune(bool) {}", + " void endProfileRetune(bool) { retune_owned=false; }") + fixture=fixture.replace("{ ++applies; elapsed_us+=switch_apply_us;", + "{ applied_priority[applies]=priority_active; ++applies; elapsed_us+=switch_apply_us;") + globals_source=timing.ProfileSwitchTimingTest.production_globals() + lease=r''' +#include +@GLOBALS@ +namespace mesh { namespace radiopriority { +class Lease { + bool admitted=false; + public: + explicit Lease(bool owned) { + assert(owned==expected_owned); + if(!owned) return; + assert(!priority_active); + admitted=priority_active=true;++entries; + elapsed_us+=11; // Raising priority must be charged to the hop. + } + void release() { + if(!admitted) return; + assert(priority_active); + // Timing publication must happen after normal priority is restored. + assert(profiletiming::mesh_hil_profile_timing.sequence==sequence_at_start); + admitted=priority_active=false;++releases; + elapsed_us+=1000; // Model immediate USB scheduling during restoration. + } + ~Lease() { release(); } +}; +} } +'''.replace("@GLOBALS@",globals_source) + fixture=fixture.replace("@METHODS@",lease+methods) + fixture=r'''#define MESH_HIL_PROFILE_TIMING 1 +#define MC_NRF_RADIO_PROFILE_PRIORITY 1 +'''+fixture+r''' +int main() { + using Result=mesh::RadioParamApplyResult; + for(unsigned scenario=0;scenario<8;++scenario) { + RadioLibWrapper radio; + mesh::RadioProfileConfig second; + second.params=radio._profiles.primary;second.params.freq+=1; + second.mode=mesh::RadioProfileMode::RxTx; + radio._profiles.setSecondary(second,false); + radio._rx_ps_enabled=radio._rx_ps_armed=false; + radio._profile_refresh_required=true; + entries=releases=0;priority_active=false; + for(bool& value:applied_priority) value=false; + uint8_t target=1; + switch(scenario) { + case 1: radio.busy=true;break; + case 2: radio.fail=true;break; + case 3: radio.failRxStarts=1;break; + case 4: radio.warm_allowed=false;break; + case 5: radio._rx_ps_enabled=true;break; + case 6: radio._rx_ps_armed=true;break; + case 7: target=0;break; + } + expected_owned=scenario<4; + auto& capture=mesh::profiletiming::mesh_hil_profile_timing; + sequence_at_start=capture.sequence; + const auto result=radio.tuneProfile(target); + assert(!priority_active && entries==unsigned(expected_owned) && releases==entries); + if(scenario==1) { + assert(result==Result::BUSY && radio.applies==0); + assert(capture.direction[0].last_us[mesh::profiletiming::Whole]==11); + } else if(scenario==2 || scenario==3) { + assert(result==Result::FAILED && radio.applies==2); + assert(applied_priority[0] && !applied_priority[1]); + assert(capture.direction[0].last_result==mesh::profiletiming::Failure); + assert(capture.direction[0].last_us[mesh::profiletiming::Whole]==1211); + } else { + assert(result==Result::APPLIED); + if(scenario==0) { + assert(applied_priority[0]); + assert(radio._profiles.longest_switch_us==1211); + assert(radio._profiles.switch_test_max_us[0]==1211); + assert(capture.direction[0].last_us[mesh::profiletiming::Whole]==1211); + assert(elapsed_us-radio._profile_visit_stamp==1000); + } else assert(!applied_priority[0]); + } + } +} +''' + self.compile_run(fixture) + + def test_chip_capability_requires_live_owned_warm_receive_state(self): + source=(ROOT/"src/helpers/radiolib/CustomSX1262.h").read_text() + accessor=method(source,"bool hilOwnsWarmProfileRetune(") + self.compile_run(r''' +#include +#include +struct Radio { + SX1262ProfileSwitchState _profileSwitch{true}; + bool _coldStandby=false; + @ACCESSOR@ +}; +int main() { + for(unsigned gate=0;gate<7;++gate) { + Radio radio; + radio._profileSwitch.rxResult(0,true); + radio._profileSwitch.begin(true,true); + assert(radio.hilOwnsWarmProfileRetune()); + switch(gate) { + case 0: radio._profileSwitch.end(true);break; + case 1: radio._profileSwitch.begin(false,true);break; + case 2: radio._profileSwitch.begin(true,false);break; + case 3: radio._profileSwitch.rxResult(-1,true);break; + case 4: radio._profileSwitch.standbyResult(-1);break; + case 5: radio._profileSwitch.invalidate();break; + case 6: radio._coldStandby=true;break; + } + assert(!radio.hilOwnsWarmProfileRetune()); + } +} +'''.replace("@ACCESSOR@",accessor)) + + +if __name__=="__main__": + unittest.main() diff --git a/test/test_nrf_radio_priority_lease.py b/test/test_nrf_radio_priority_lease.py new file mode 100644 index 000000000..3f6d9f292 --- /dev/null +++ b/test/test_nrf_radio_priority_lease.py @@ -0,0 +1,170 @@ +"""Execute diagnostic task-priority admission, restoration and RTC deadline.""" +from pathlib import Path +import os +import subprocess +import tempfile +import unittest + +from test_rak3401_buffered_radio_hal import MOCK_HAL + +ROOT=Path(__file__).resolve().parents[1] +SOURCE=ROOT/'src/helpers/radiolib/NrfRadioPriorityLease.cpp' + +ARDUINO=r''' +#pragma once +#include +#include +using UBaseType_t=unsigned; +struct TaskMock { unsigned priority; const char* name; }; +using TaskHandle_t=TaskMock*; +enum { TASK_PRIO_LOW=1,TASK_PRIO_HIGH=3 }; +#define configMAX_PRIORITIES 5 +struct RtcMock { uint32_t COUNTER; }; +extern RtcMock rtc; +#define NRF_RTC2 (&rtc) +extern TaskMock loopTask,otherTask; +extern TaskHandle_t currentTask; +extern bool inIsr; +extern unsigned prioritySets; +inline bool isInISR() { return inIsr; } +inline TaskHandle_t xTaskGetCurrentTaskHandle() { return currentTask; } +inline const char* pcTaskGetName(TaskHandle_t task) { return task->name; } +inline unsigned uxTaskPriorityGet(TaskHandle_t task) { return task->priority; } +inline void vTaskPrioritySet(TaskHandle_t task,unsigned priority) { + assert(!inIsr && task==&loopTask && priority<5); + task->priority=priority;++prioritySets; +} +''' + +MOCK=MOCK_HAL.replace('#include ','#include \n#include ') +MOCK=MOCK.replace('virtual ~ArduinoHal() = default;',r''' + unsigned yields=0,transactions=0,lastTransactionPriority=0; + virtual ~ArduinoHal() = default; + virtual void yield() { ++yields; } + virtual void spiBeginTransaction() { + ++transactions;lastTransactionPriority=currentTask->priority; + } +''') + +FIXTURE=r''' +#include +RtcMock rtc{}; +TaskMock loopTask{1,"loop"},otherTask{3,"usbd"}; +TaskHandle_t currentTask=&loopTask; +bool inIsr=false; +unsigned prioritySets=0; +int failEarly(bool fail) { + mesh::radiopriority::Lease lease(true); + assert(loopTask.priority==4); + if(fail) return -1; + lease.release(); + assert(loopTask.priority==1); + return 0; +} +int main() { + using namespace mesh::radiopriority; + auto& capture=mesh_hil_radio_priority; + assert(capture.magic==0x4d435250 && capture.size_bytes==60); + SPIClass bus;Nrf52BufferedRadioHal concrete(bus,8000000); + ArduinoHal& hal=concrete; + { Lease lease(false);assert(loopTask.priority==1); } + inIsr=true;{ Lease lease(true); }inIsr=false; + currentTask=&otherTask;{ Lease lease(true); }currentTask=&loopTask; + loopTask.priority=3;{ Lease lease(true); }loopTask.priority=1; + assert(prioritySets==0 && capture.entries==0); + assert(capture.skipped_not_owned==1 && capture.skipped_isr==1); + assert(capture.skipped_task==1 && capture.skipped_priority==1); + + // Nested rejection must not release its outer caller's admitted lease. + rtc.COUNTER=100; + { Lease outer(true);assert(loopTask.priority==4 && capture.active==1); + { Lease inner(true); }assert(loopTask.priority==4 && capture.active==1); + hal.yield();assert(hal.yields==0 && capture.suppressed_yields==1); + hal.spiBeginTransaction(); + assert(hal.transactions==1 && hal.lastTransactionPriority==4); + currentTask=&otherTask;hal.yield();assert(hal.yields==1); + currentTask=&loopTask; + outer.release();assert(loopTask.priority==1 && capture.active==0); + outer.release(); + } + assert(capture.skipped_nested==1 && capture.entries==1 && capture.releases==1); + assert(prioritySets==2); + + // The RTC is 24-bit. Expiry drops priority BEFORE normal USB-flushing yield. + rtc.COUNTER=0x00fffff0; + { Lease lease(true); + rtc.COUNTER=(0x00fffff0+31)&RtcMask; + hal.yield();assert(loopTask.priority==4 && hal.yields==1); + rtc.COUNTER=(0x00fffff0+32)&RtcMask; + hal.yield();assert(loopTask.priority==1 && hal.yields==2); + assert(capture.active==0 && capture.expired==1); + } + assert(capture.entries==2 && capture.releases==2 && prioritySets==4); + for(unsigned i=0;i<10000;++i) hal.yield(); + assert(hal.yields==10002); // No lease means no suppressed normal yields. + + // Frame checks expire before the base transaction can lower radio CS. + rtc.COUNTER=100; + { Lease lease(true);rtc.COUNTER=132;hal.spiBeginTransaction(); + assert(hal.transactions==2 && hal.lastTransactionPriority==1); + assert(loopTask.priority==1 && capture.expired==2); + } + uint8_t tx[]={0x86,0x12,0x34},rx[3]={}; + hal.spiTransfer(tx,3,rx);hal.spiTransfer(nullptr,0,nullptr); + assert(bus.bursts==1 && bus.bytes==0 && rx[1]==uint8_t(tx[1]^0xa5)); + + // Both early failure and explicit successful release restore exactly once. + rtc.COUNTER=200; + assert(failEarly(true)==-1 && loopTask.priority==1); + assert(failEarly(false)==0 && loopTask.priority==1); + assert(capture.entries==5 && capture.releases==5 && prioritySets==10); + assert(capture.active==0 && capture.frame_checks==2); +} +''' + + +class NrfRadioPriorityLeaseTest(unittest.TestCase): + def test_real_lease_and_hal_preserve_yields_and_restore_on_every_exit(self): + with tempfile.TemporaryDirectory() as directory: + folder=Path(directory) + (folder/'hal/Arduino').mkdir(parents=True) + (folder/'Arduino.h').write_text(ARDUINO,encoding='ascii') + (folder/'hal/Arduino/ArduinoHal.h').write_text(MOCK,encoding='ascii') + cpp,binary=folder/'test.cpp',folder/'test.exe' + cpp.write_text(FIXTURE,encoding='ascii') + built=subprocess.run([os.environ.get('CXX','g++'),'-std=c++17', + '-Wall','-Wextra','-Werror','-DNRF52_PLATFORM', + '-DMESH_HIL_PROFILE_TIMING=1','-DMC_NRF_RADIO_PROFILE_PRIORITY=1', + '-I',str(folder),'-I',str(ROOT/'src'),str(cpp),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) + + def test_default_off_has_no_code_types_ram_or_sdk_dependencies(self): + preprocessed=subprocess.run([os.environ.get('CXX','g++'),'-std=c++17', + '-E','-P','-x','c++','-I',str(ROOT/'src'),'-'], + input='#include \nint main() {}\n', + capture_output=True,text=True) + self.assertEqual(preprocessed.returncode,0,preprocessed.stderr) + self.assertEqual(preprocessed.stdout.strip(),'int main() {}') + implementation=subprocess.run([os.environ.get('CXX','g++'),'-std=c++17', + '-E','-P',str(SOURCE)],capture_output=True,text=True) + self.assertEqual(implementation.returncode,0,implementation.stderr) + self.assertFalse(implementation.stdout.strip()) + + def test_experiment_rejects_missing_nrf_or_timing(self): + for flags in (['-DMC_NRF_RADIO_PROFILE_PRIORITY=1'], + ['-DMC_NRF_RADIO_PROFILE_PRIORITY=1','-DNRF52_PLATFORM'], + ['-DMC_NRF_RADIO_PROFILE_PRIORITY=1','-DMESH_HIL_PROFILE_TIMING=1']): + with self.subTest(flags=flags): + result=subprocess.run([os.environ.get('CXX','g++'),'-E','-x','c++', + *flags,'-I',str(ROOT/'src'),'-'], + input='#include \n', + capture_output=True,text=True) + self.assertNotEqual(result.returncode,0) + self.assertIn('requires nRF52 HIL profile timing',result.stderr) + + +if __name__=='__main__': + unittest.main()