diff --git a/test/test_companion_prefs_values.py b/test/test_companion_prefs_values.py index 3d45464ba..871a7ad02 100644 --- a/test/test_companion_prefs_values.py +++ b/test/test_companion_prefs_values.py @@ -98,6 +98,9 @@ int main() { DataStore image_store; assert(image_store.savePrefs(saved, 47.125, -122.25)); auto image = image_store.fs.files["/new_prefs"]; +#if defined(WIO_E5_MINI_HEADLESS_COMPANION_UI) + assert(image[79] == saved.leds_quiet); +#endif // The frozen reference remains authoritative only for the historical // prefix. Checked new-footer behavior has dedicated persistence tests. image.resize(image.size()-mesh::companion::traffic::FooterSize); @@ -158,6 +161,9 @@ int main() { } if(got)legacy.tx_media=legacy.tx_ssh=mesh::RADIO_TX_AUTO; equalValues(actual, legacy); +#if defined(WIO_E5_MINI_HEADLESS_COMPANION_UI) + if (got) assert(actual.leds_quiet == disk[79]); +#endif assert(!memcmp(&lat, &legacy_lat, sizeof(lat))); assert(!memcmp(&lon, &legacy_lon, sizeof(lon))); assert(actual_store.fs.files["/new_prefs"] == disk); @@ -187,6 +193,15 @@ class CompanionPrefsValuesTests(unittest.TestCase): # is the authority for all old/torn images and read failure traces. legacy = (ROOT / 'test/fixtures/companion_prefs_storage/legacy_loader.inc').read_text() self.assertNotIn('copyPersistedValuesFrom', legacy) + # The headless Mini assigns the existing reserved byte at 79 to LED + # policy. Keep the independent scalar read and every failure boundary; + # only this target stores its value instead of discarding it as padding. + reserved_byte = ' readField(pad, 1);' + self.assertEqual(legacy.count(reserved_byte), 1) + legacy = legacy.replace(reserved_byte, + '#if defined(WIO_E5_MINI_HEADLESS_COMPANION_UI)\n' + ' readField(&loaded_prefs.leds_quiet, 1);\n' + '#else\n' + reserved_byte + '\n#endif') # Keep the frozen scalar prefix independent of the new GNU table. # The RAK-only checked tail was published later; add it explicitly # to this test-local reference without rewriting the frozen fixture. @@ -227,6 +242,7 @@ class CompanionPrefsValuesTests(unittest.TestCase): 'wifi_ssid': 'defined(RP2040_PLATFORM) && defined(ENABLE_WIFI_INTERFACE)', 'wifi_pwd': 'defined(RP2040_PLATFORM) && defined(ENABLE_WIFI_INTERFACE)', 'peripherals_shared': 'RAK_4631', + 'leds_quiet': 'WIO_E5_MINI_HEADLESS_COMPANION_UI', } def fields(template): @@ -281,7 +297,8 @@ inline char* utoa(unsigned int value,char* output,int base){ (work / 'helpers/IdentityStore.h').write_text(fs) cpp = work / 'test.cpp' cpp.write_text(code + tests) - for platform in ('STM32_PLATFORM', 'NRF52_PLATFORM', 'NRF52_PLATFORM,RAK_4631', 'ESP32_PLATFORM', 'RP2040_PLATFORM', + for platform in ('STM32_PLATFORM', 'STM32_PLATFORM,WIO_E5_MINI_HEADLESS_COMPANION_UI', + 'NRF52_PLATFORM', 'NRF52_PLATFORM,RAK_4631', 'ESP32_PLATFORM', 'RP2040_PLATFORM', 'ESP32_PLATFORM,TBEAM_1W', 'RP2040_PLATFORM,ENABLE_WIFI_INTERFACE'): with self.subTest(platform=platform): binary = work / 'test' diff --git a/test/test_nrf52_sleep_cycle.py b/test/test_nrf52_sleep_cycle.py index 9d138cc7b..3efd43844 100644 --- a/test/test_nrf52_sleep_cycle.py +++ b/test/test_nrf52_sleep_cycle.py @@ -272,15 +272,83 @@ int main() { self.execute(code) def test_every_application_bluefruit_attempt_invalidates_before_call(self): - for filename, call in ( - ("src/helpers/NRF52Board.cpp", "if (!Bluefruit.begin(1, 0))"), - ("src/helpers/nrf52/SerialBLEInterface.cpp", "if (!Bluefruit.begin())"), + for filename, signature, call in ( + ("src/helpers/NRF52Board.cpp", "bool NRF52Board::startOTAUpdate(", + "if (!Bluefruit.begin(1, 0))"), + ("src/helpers/nrf52/SerialBLEInterface.cpp", "bool SerialBLEInterface::begin(", + "if (!Bluefruit.begin())"), ): with self.subTest(filename=filename): source = (ROOT / filename).read_text(encoding="ascii") - at = source.index(call) - self.assertTrue(source[:at].rstrip().endswith( - "mesh_nrf52::sleepCycleState().invalidate();")) + startup = extract_braced(source, signature) + self.assertEqual(startup.count(call), 1) + at = startup.index(call) + prelude = startup[startup.index("Bluefruit.configPrphConn("):at] + invalidate = "mesh_nrf52::sleepCycleState().invalidate();" + without_invalidation = prelude.replace(invalidate, "") + # Execute the real configuration/startup prelude, allowing LED + # setup between invalidation and begin. Observe the cache at + # begin itself, including when startup partially enables SD + # and then returns failure. + variants = ( + (prelude, "", True), + (without_invalidation, "", False), + (without_invalidation, invalidate, False), + (prelude + "\nauto fresh = mesh_nrf52::sleepCycleState().begin();\n" + "mesh_nrf52::sleepCycleState().publish(fresh, false, 42);", "", False), + ) + attempts = [] + for index, (before, after, expected) in enumerate(variants): + attempts.append("static bool attempt_%d() {\n%s\n" + "const bool started = %s;\n%s\nreturn started;\n}" % + (index, before, call[len("if (!"):-1], after)) + cases = ",\n".join("{attempt_%d, %s}" % (index, str(expected).lower()) + for index, (_, _, expected) in enumerate(variants)) + self.execute(r''' +#include +#include +#include +constexpr int BLE_GATT_ATT_MTU_DEFAULT = 23, BLE_GAP_EVENT_LENGTH_MIN = 3; +constexpr int COMPANION_BLE_PRPH_MTU = 247, COMPANION_BLE_PRPH_EVENT_LENGTH = 100; +constexpr int COMPANION_BLE_PRPH_HVN_QUEUE = 3, COMPANION_BLE_PRPH_WRCMD_QUEUE = 1; +static bool begin_succeeds, actual_sd, invalidated_at_begin; +static uint32_t before_start; +struct BluefruitStub { + unsigned starts = 0; + void configPrphConn(int, int, int, int) {} + template bool begin(Args...) { + ++starts; + auto& state = mesh_nrf52::sleepCycleState(); + mesh_nrf52::SleepCycleSnapshot snapshot; + invalidated_at_begin = !state.current(before_start) && !state.snapshot(snapshot); + actual_sd = true; // A failed begin can still partially enable SoftDevice. + return begin_succeeds; + } +} Bluefruit; +namespace mesh_nrf52 { void applyBluetoothLedPolicy() {} } +@ATTEMPTS@ +int main() { + struct Case { bool (*attempt)(); bool invalidates_before_begin; }; + const Case cases[] = {@CASES@}; + for (const auto& test : cases) { + for (bool succeeds : {false, true}) { + auto& state = mesh_nrf52::sleepCycleState(); + before_start = state.begin(); + assert(state.publish(before_start, false, 42)); + mesh_nrf52::SleepCycleSnapshot snapshot; + assert(state.snapshot(snapshot) && !snapshot.softdevice_enabled); + begin_succeeds = succeeds; actual_sd = false; + const auto starts = Bluefruit.starts; + assert(test.attempt() == succeeds); + assert(Bluefruit.starts == starts + 1 && actual_sd); + assert(invalidated_at_begin == test.invalidates_before_begin); + if (test.invalidates_before_begin) { + assert(!state.current(before_start) && !state.snapshot(snapshot)); + } + } + } +} +'''.replace("@ATTEMPTS@", "\n".join(attempts)).replace("@CASES@", cases)) board = (ROOT / "src/helpers/NRF52Board.cpp").read_text(encoding="ascii") late = extract_braced(board, "void NRF52Board::sleep(uint32_t secs)") self.assertNotIn("softdeviceIsEnabled", late) diff --git a/test/test_nrf52_sleep_events.py b/test/test_nrf52_sleep_events.py index 053054775..4d1e346d2 100644 --- a/test/test_nrf52_sleep_events.py +++ b/test/test_nrf52_sleep_events.py @@ -126,16 +126,72 @@ class Nrf52SleepEventTests(unittest.TestCase): def test_enabled_crypto_owner_and_other_pending_irqs_are_preserved(self): self.run_case("irq_owner") - def test_all_sleeping_roles_prepare_before_any_work_or_policy_check(self): - entry = "\nvoid loop() {\n#if defined(NRF52_PLATFORM)\n board.prepareSleepCycle();\n#endif\n" + def test_all_sleeping_roles_prepare_after_transitions_before_work(self): + preparation = "#if defined(NRF52_PLATFORM)\n board.prepareSleepCycle();\n#endif\n" + priority = ("#if defined(BLE_PIN_CODE)\n" + " serviceCompanionUsbBluetoothPriority();\n#endif\n") for role in ("simple_repeater", "simple_room_server", "simple_sensor", "companion_radio"): with self.subTest(role=role): source = (ROOT / "examples" / role / "main.cpp").read_text(encoding="ascii") actual = body(source, "\nvoid loop() {") + # Companion's transport transition may resume/start BLE and + # invalidate the prior cache. Query SDK state after it, with + # no other loop work before this single preparation. + entry = "\nvoid loop() {\n" + (priority if role == "companion_radio" else "") + preparation self.assertTrue(actual.startswith(entry)) self.assertEqual(actual.count("board.prepareSleepCycle();"), 1) + def test_companion_transition_precedes_the_authoritative_sdk_snapshot(self): + source = (ROOT / "examples/companion_radio/main.cpp").read_text(encoding="ascii") + actual = body(source, "\nvoid loop() {") + end = actual.index("#endif\n", actual.index("board.prepareSleepCycle();")) + len("#endif\n") + entry = actual[:end].replace("void loop()", "static void companionLoopEntry()", 1) + "}\n" + harness = r''' +#define BLE_PIN_CODE 1 +#define NRF52_PLATFORM 1 +static NRF52Board board; +static bool next_softdevice; +static unsigned priority_calls = 0, queries_before_entry; +static void serviceCompanionUsbBluetoothPriority() { + ++priority_calls; + assert(state_queries == queries_before_entry); + mesh_nrf52::sleepCycleState().invalidate(); + softdevice_enabled = next_softdevice; +} +@ENTRY@ +int main(int argc, char** argv) { + assert(argc == 2); + next_softdevice = !std::strcmp(argv[1], "enabled"); + softdevice_enabled = !next_softdevice; + board.prepareSleepCycle(); // A cached snapshot from before the transition. + queries_before_entry = state_queries; + companionLoopEntry(); + assert(priority_calls == 1 && state_queries == queries_before_entry + 1); + mesh_nrf52::SleepCycleSnapshot snapshot; + assert(mesh_nrf52::sleepCycleState().snapshot(snapshot)); + assert(snapshot.softdevice_enabled == next_softdevice); + const unsigned before_sleep = state_queries; + board.sleep(0); + assert(state_queries == before_sleep && real_sleeps == 1); +} +''' + # Keep the production cache, board preparation and sleep methods; only + # model the transport transition's invalidation/SoftDevice effects. + fixture = self.cycle_source.replace("int main(", "void fixtureMain(", 1) + good = self.compile_cycle("companion-entry", fixture + harness.replace("@ENTRY@", entry)) + late_entry = entry.replace(" serviceCompanionUsbBluetoothPriority();\n", "", 1).replace( + " board.prepareSleepCycle();\n", + " board.prepareSleepCycle();\n serviceCompanionUsbBluetoothPriority();\n", 1) + late = self.compile_cycle("companion-late-transition", fixture + harness.replace("@ENTRY@", late_entry)) + for mode in ("enabled", "disabled"): + with self.subTest(mode=mode): + result = subprocess.run([str(good), mode], capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + result = subprocess.run([str(late), mode], capture_output=True, text=True) + self.assertNotEqual(result.returncode, 0) + self.assertIn("Assertion", result.stderr) + def test_actual_cache_single_attempt_stale_publication_errors_and_recovery(self): self.run_cycle_case("cache")