From 1b17feb71a51b15e34ced05ef623d5aaa34a7a41 Mon Sep 17 00:00:00 2001 From: Usman Mehmood Date: Mon, 9 Nov 2026 11:58:28 +0100 Subject: [PATCH 01/11] ci(hil): add Windows HIL workflow with UART fixture control Add a maintainer-triggered workflow that flashes a pinned Zephyr image to the nRF52 DK fixture and then runs the baseline and fault insertion suites on a self-hosted Windows runner, one selected group at a time. Windows now arms fixture faults over the DK's USB virtual COM port instead of BLE, so a link that the fault under test tears down can no longer drop the control command: - hil_serial_io.dart drives a PowerShell serial bridge over a loopback socket and serialises request/reply exchanges; hil_serial_stub.dart is selected by conditional import where dart:io serial control is absent. - HilPeripheral opens the wired link, validates the reported fixture address and contract revision, exposes wired telemetry reads, and gains dispose() so the serial bridge is released with the connection. - Fault insertion tests carry a group tag in their names so the workflow can select a single group, trace FIT-CONN-009/013 timings, and fail loudly instead of tolerating BLE control-path write errors when the wired path is in use. - run_windows_hil_group.ps1 runs each group in a worker process under a timeout so a hung group cannot block the remaining groups. --- .github/workflows/windows_hil.yml | 172 ++++++++++++++ hil/COVERAGE.md | 8 +- hil/README.md | 86 ++++++- hil/integration_test/baseline_hil_test.dart | 67 +++++- .../fault_injection_hil_test.dart | 223 +++++++++++++----- hil/lib/main.dart | 2 +- hil/lib/src/hil_peripheral.dart | 115 +++++++-- hil/lib/src/hil_serial_io.dart | 197 ++++++++++++++++ hil/lib/src/hil_serial_stub.dart | 12 + hil/run_windows_hil_group.ps1 | 56 +++++ 10 files changed, 827 insertions(+), 111 deletions(-) create mode 100644 .github/workflows/windows_hil.yml create mode 100644 hil/lib/src/hil_serial_io.dart create mode 100644 hil/lib/src/hil_serial_stub.dart create mode 100644 hil/run_windows_hil_group.ps1 diff --git a/.github/workflows/windows_hil.yml b/.github/workflows/windows_hil.yml new file mode 100644 index 00000000..fbe87924 --- /dev/null +++ b/.github/workflows/windows_hil.yml @@ -0,0 +1,172 @@ +name: Windows HIL and Fault Insertion Tests + +on: + workflow_dispatch: + inputs: + test_group: + description: Test group to run (all includes baseline and fault insertion tests) + type: choice + default: all + options: + - all + - baseline + - connection-discovery + - gatt-operations + - notifications-indications + - mtu-resources + - timing-sweeps + +permissions: + contents: read + +concurrency: + group: windows-hil-fixture + cancel-in-progress: false + +jobs: + hil: + # Only run reviewed code from the protected default branch. + if: github.ref == format('refs/heads/{0}', github.event.repository.default_branch) + environment: windows-hil + runs-on: + # group: windows-hil + labels: [self-hosted, Windows, X64, universal-ble-hil] + timeout-minutes: 60 + defaults: + run: + shell: pwsh + working-directory: hil + env: + HIL_DEVICE_ID: ${{ vars.HIL_DEVICE_ID }} + HIL_JLINK_SERIAL: ${{ vars.HIL_JLINK_SERIAL }} + # Update these together when the Flutter harness needs new firmware. + HIL_FIRMWARE_TAG: 'v0.2' + HIL_FIRMWARE_SHA256: '105e6b0a525fd91710633a11b8ee276ff4715979aeba07bdb2294519db5caea1' + + steps: + - name: Create log directory for this attempt + working-directory: ${{ runner.temp }} + run: | + $logs = Join-Path $env:RUNNER_TEMP "windows-hil-$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT" + New-Item -ItemType Directory -Path $logs | Out-Null + "HIL_LOG_DIR=$logs" >> $env:GITHUB_ENV + + - uses: actions/checkout@v4 + with: + persist-credentials: false + + - name: Resolve fixture COM port from J-Link serial + run: | + if ($env:HIL_JLINK_SERIAL -notmatch '^[0-9]{6,12}$' -or + $env:HIL_JLINK_SERIAL.TrimStart('0') -notmatch '^[1-9][0-9]{5,11}$') { + throw 'Set HIL_JLINK_SERIAL to the dedicated DK onboard J-Link serial number.' + } + $serial = $env:HIL_JLINK_SERIAL.TrimStart('0') + $ports = @(Get-PnpDevice -PresentOnly -Class Ports | ForEach-Object { + if ($_.FriendlyName -notmatch '\((COM[1-9][0-9]*)\)$') { return } + $port = $Matches[1] + $id = $_.InstanceId + for ($depth = 0; $id -and $depth -lt 8; $depth++) { + if ($id -match '^USB\\VID_1366&PID_[0-9A-F]{4}\\0*([1-9][0-9]*)$') { + if ($Matches[1] -eq $serial) { $port } + break + } + $id = (Get-PnpDeviceProperty -InstanceId $id -KeyName DEVPKEY_Device_Parent -ErrorAction SilentlyContinue).Data + } + }) + if ($ports.Count -ne 1) { + throw "Expected one COM port for J-Link $env:HIL_JLINK_SERIAL; found $($ports.Count): $($ports -join ', '). Check the DK USB connection and SEGGER CDC driver." + } + Write-Host "J-Link $env:HIL_JLINK_SERIAL UART: $($ports[0])" + "HIL_SERIAL_PORT=$($ports[0])" >> $env:GITHUB_ENV + "HIL_JLINK_SERIAL=$serial" >> $env:GITHUB_ENV + + - name: Prepare Windows test app + run: | + flutter create --platforms=windows --no-pub . + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + flutter pub get + exit $LASTEXITCODE + + - name: Clean-flash the nRF52 DK + timeout-minutes: 5 + run: | + # Java also ships a jlink.exe; do not resolve this tool from PATH. + $jlink = Join-Path $env:ProgramFiles 'SEGGER\JLink\JLink.exe' + if (-not (Test-Path -LiteralPath $jlink -PathType Leaf)) { + throw "Install SEGGER J-Link Commander at $jlink on the Windows runner." + } + $repo = 'usmanmehmood55/universal_ble_hil_firmware' + $tag = [Uri]::EscapeDataString($env:HIL_FIRMWARE_TAG) + $expectedHash = $env:HIL_FIRMWARE_SHA256 + $dir = New-Item -ItemType Directory -Path (Join-Path $env:RUNNER_TEMP "hil-firmware-$([guid]::NewGuid())") + $hex = Join-Path $dir.FullName 'zephyr.hex' + Invoke-WebRequest -Uri "https://github.com/$repo/releases/download/$tag/zephyr.hex" -OutFile $hex + if ((Get-FileHash -LiteralPath $hex -Algorithm SHA256).Hash -ne $expectedHash) { + throw "Firmware $tag does not match the pinned SHA-256. The fixture was not erased." + } + Write-Host "Flashing $tag zephyr.hex (SHA-256: $expectedHash) via J-Link $env:HIL_JLINK_SERIAL" + $commands = Join-Path $dir.FullName 'flash.jlink' + @('erase', "loadfile `"$hex`"", 'r', 'g', 'exit') | + Set-Content -LiteralPath $commands -Encoding ascii + $PSNativeCommandUseErrorActionPreference = $false + & $jlink -USB $env:HIL_JLINK_SERIAL -Device NRF52832_XXAA -If SWD -Speed 4000 ` + -AutoConnect 1 -NoGui 1 -ExitOnError 1 -CommandFile $commands 2>&1 | + Tee-Object -FilePath (Join-Path $env:HIL_LOG_DIR 'flash-hil.log') + exit $LASTEXITCODE + + + - name: Baseline + id: baseline + if: inputs.test_group == 'all' || inputs.test_group == 'baseline' + continue-on-error: true + run: ./run_windows_hil_group.ps1 -Group baseline + + - name: 'Fault insertion tests: connection and discovery' + id: connection-discovery + if: inputs.test_group == 'all' || inputs.test_group == 'connection-discovery' + continue-on-error: true + run: ./run_windows_hil_group.ps1 -Group connection-discovery + + - name: 'Fault insertion tests: GATT operations' + id: gatt-operations + if: inputs.test_group == 'all' || inputs.test_group == 'gatt-operations' + continue-on-error: true + run: ./run_windows_hil_group.ps1 -Group gatt-operations + + - name: 'Fault insertion tests: notifications and indications' + id: notifications-indications + if: inputs.test_group == 'all' || inputs.test_group == 'notifications-indications' + continue-on-error: true + run: ./run_windows_hil_group.ps1 -Group notifications-indications + + - name: 'Fault insertion tests: MTU and resource pressure' + id: mtu-resources + if: inputs.test_group == 'all' || inputs.test_group == 'mtu-resources' + continue-on-error: true + run: ./run_windows_hil_group.ps1 -Group mtu-resources + + - name: 'Fault insertion tests: timing sweeps' + id: timing-sweeps + if: inputs.test_group == 'all' || inputs.test_group == 'timing-sweeps' + continue-on-error: true + run: ./run_windows_hil_group.ps1 -Group timing-sweeps + + - name: Fail if any selected test group failed + if: > + steps.baseline.outcome == 'failure' || + steps.connection-discovery.outcome == 'failure' || + steps.gatt-operations.outcome == 'failure' || + steps.notifications-indications.outcome == 'failure' || + steps.mtu-resources.outcome == 'failure' || + steps.timing-sweeps.outcome == 'failure' + run: throw 'One or more selected Windows test groups failed. See the per-group logs.' + + - name: Upload test logs + if: always() + uses: actions/upload-artifact@v4 + with: + name: windows-hil-logs-${{ github.run_attempt }} + path: ${{ runner.temp }}/windows-hil-${{ github.run_id }}-${{ github.run_attempt }}/*-hil.log + if-no-files-found: ignore + retention-days: 14 diff --git a/hil/COVERAGE.md b/hil/COVERAGE.md index 030548ef..e1aba7c2 100644 --- a/hil/COVERAGE.md +++ b/hil/COVERAGE.md @@ -63,13 +63,13 @@ and finally the Zephyr GATT server on the fixture. | `FIT-CONN-003` | Immediate disconnect is followed by reconnect and a successful read | Incomplete cleanup of the old connection | | `FIT-CONN-006` | Two simultaneous connects resolve to one usable replacement connection | Superseded native attempts disturbing the active link | | `FIT-CONN-007` | Sweep host disconnect before/around/after a measured peripheral deadline; verify timer telemetry and reconnect | Blocking WinRT teardown, double cleanup, and stale timers | -| `FIT-CONN-009` | Reconnects before the old native disconnect callback has necessarily run | Stale map entries suppressing the replacement attempt | +| `FIT-CONN-009` | Connects without queueing or retrying at 0–25 ms after a reported peripheral disconnect, then reads immediately | Reconnect returning before the replacement link is usable | | `FIT-CONN-010` | Five immediate peripheral disconnect/reconnect cycles all remain readable | State or resources leaking between connections | | `FIT-CONN-013` | Five rapid cycles emit alternating disconnected/connected events in order | Missing, duplicate, stale, and out-of-order callbacks | -For immediate disconnects, observation starts before the control write. A lost -write acknowledgement is accepted only when the disconnect occurs; otherwise -the original write error is rethrown. +For immediate disconnects, observation starts before the fixture command. +Windows requires both a UART acknowledgement and an observed BLE disconnect. +The legacy BLE control path can lose its acknowledgement when the link drops. ### 2.2. Reads diff --git a/hil/README.md b/hil/README.md index 466946b3..73caf2e7 100644 --- a/hil/README.md +++ b/hil/README.md @@ -5,7 +5,9 @@ a physical nRF52 DK. It lives outside the normal package tests because it needs the DK and exclusive access to a Bluetooth adapter. The firmware is in the [`universal_ble_hil_firmware`](https://github.com/usmanmehmood55/universal_ble_hil_firmware) -repository. Test commands go over BLE. USB serial is only used for Zephyr logs. +repository. On Windows, fixture commands go over the DK's USB virtual COM +port. The BLE operations under test still go over the radio. Android and the +interactive Web runner retain the BLE control path. ## 1. Current coverage @@ -31,13 +33,14 @@ runner for the portable baseline path. ## 2. How fault injection tests work -The test first writes a fault plan to the fixture's control characteristic. +The Windows test first sends a fault plan over USB serial and waits for the +fixture to acknowledge it. The firmware keeps that plan and applies it when the next matching GATT operation arrives. For example, a disconnect-during-read test performs these steps: -1. Write a one-shot read plan containing a callback delay and disconnect delay. +1. Arm a one-shot read plan containing a callback delay and disconnect delay. 2. Start a normal read through `universal_ble`. 3. Let the firmware disconnect while its read callback is pending. 4. Assert bounded failure, reconnect, and a successful recovery read. @@ -52,8 +55,9 @@ The automated suite currently runs on Windows. Calls start at the public Dart API and go through Pigeon, the Windows C++ plugin, WinRT, the Bluetooth stack, the radio link, and finally the Zephyr GATT server. -Fixture control also uses BLE, so faults are armed while the device is -connected. The firmware then runs them locally using valid GATT behavior. +The UART acknowledgement means the fixture accepted a command, not that a +disconnect or notification has already occurred. Tests still assert the BLE +outcome and use fixture telemetry where they need proof a fault fired. ## 4. Running the tests @@ -76,16 +80,21 @@ element in `android/app/src/main/AndroidManifest.xml`: ``` -Flash the matching firmware and confirm that `UniversalBLE-HIL` is -advertising. From this directory, run: +Flash the UART-enabled revision 2 firmware (older revision 2 images do not +implement the serial handshake). Connect the DK over USB, find its COM port +in Device Manager, and close any serial monitor using that port. The harness +uses Windows PowerShell (`powershell.exe`) to open the port. From this +directory, run: ```powershell flutter pub get +$env:HIL_SERIAL_PORT = 'COM4' # Replace with the DK's port. flutter test integration_test/baseline_hil_test.dart -d windows flutter test integration_test/fault_injection_hil_test.dart -d windows ``` -If you already know the Windows device ID, you can skip the initial scan: +The UART handshake supplies the fixture's BLE address. Optionally assert that +it matches the expected address: ```powershell flutter test integration_test/baseline_hil_test.dart -d windows ` @@ -109,6 +118,65 @@ Web Bluetooth requires a secure context, a real user gesture, and browser device permission. Click **Select device and run**, then select `UniversalBLE-HIL` in Chrome's chooser. +### Maintainer-triggered Windows CI + +In Actions, open Windows HIL and fault insertion tests and click Run workflow. +The workflow runs on the protected default branch. Choose `all` (the default) or one +group: `baseline`, `connection-discovery`, `gatt-operations`, +`notifications-indications`, `mtu-resources`, or `timing-sweeps`. Existing +pairing and bonding cases are included in `connection-discovery`. + +The workflow flashes once, then runs the selected groups serially on the same +fixture. Each group has an eight-minute timeout and its own log. A failed or +timed-out group fails the job without preventing later selected groups from +running. Logs are kept separately for each run attempt. The workflow does not run on +pushes or pull requests and does not accept a separate checkout ref. + +To run a single group locally from this directory after preparing the fixture: + +```powershell +./run_windows_hil_group.ps1 -Group gatt-operations +``` + +Before enabling it, configure: + +- A dedicated Windows x64 self-hosted runner with the label + `universal-ble-hil`. The trial workflow selects by label so the maintainer + can test it on their own runner. Before upstreaming, enable + `runs-on.group: windows-hil` and restrict that organization runner group + to this repository and to + `Navideck/universal_ble/.github/workflows/windows_hil.yml@refs/heads/main` + (adjust the owner and ref for a different deployment). Do not use a + general-purpose runner or allow pull-request workflows to use this runner. +- A repository environment named `windows-hil`, restricted to the protected + default branch, with maintainers as required reviewers. Users with write + access can request a run; a maintainer must approve the hardware job. +- Flutter and PowerShell 7 on the runner account's PATH, Visual Studio with **Desktop + development with C++**, and an interactive Windows session with a working + Bluetooth adapter. Check `flutter doctor -v` and `flutter devices` from the + same account that runs Actions. +- A dedicated nRF52 DK (nRF52832) connected over USB with no external SWD + target attached. Install SEGGER J-Link Commander (7.92d or newer) at the + default location, `%ProgramFiles%\SEGGER\JLink\JLink.exe`. The workflow + uses this path to avoid picking up Java's `jlink.exe`. In the GitHub environment's + **Variables**, set `HIL_JLINK_SERIAL` to the onboard probe's serial number. + You can copy it from nRF Connect, including any leading zeros. + CI finds that probe's COM port through the Windows USB device tree and + stops before flashing if it can't find exactly one match. Optionally set + `HIL_DEVICE_ID` to assert the expected BLE address. + +Before running the selected groups, CI downloads `zephyr.hex` from the +firmware release pinned by `HIL_FIRMWARE_TAG` in the workflow. It checks the +file against `HIL_FIRMWARE_SHA256` before erasing, programming, verifying, and +resetting the selected DK. This wipes existing target firmware and settings. +When the Flutter harness needs new firmware, publish it under a new release +tag and update both pins in the same change as the harness. The firmware must +support the UART telemetry command (`fe`) used by the timing sweeps. The +flash log is included in the test artifact when J-Link runs. + +The run uploads the test output as a log artifact. Existing test skips still +apply; the Apple-only duplicate-UUID suite is not part of Windows CI. + ## 5. Isolation and diagnosis Each Windows test connects, resets the fixture, runs one case, and disconnects. @@ -121,7 +189,7 @@ fixture state, and notification bursts through sequence numbers. When a test fails, collect both outputs: - Flutter integration-test output and `universal_ble` debug logs; -- Zephyr serial logs from the nRF52 DK. +- Fixture serial output forwarded into the test log during command exchanges. If setup cannot find the fixture, confirm that it is advertising and that no other host holds its single connection slot. diff --git a/hil/integration_test/baseline_hil_test.dart b/hil/integration_test/baseline_hil_test.dart index d4d2d081..5261a89d 100644 --- a/hil/integration_test/baseline_hil_test.dart +++ b/hil/integration_test/baseline_hil_test.dart @@ -28,23 +28,63 @@ void main() { UniversalBle.onValueChange = null; if (setupSucceeded) { setupSucceeded = false; - await peripheral.close(); + await peripheral.dispose(); } }); testWidgets('discovers the named peripheral and advertised service', ( _, ) async { - expect(peripheral.device.name, HilPeripheral.deviceName); - expect( - peripheral.device.services, - anyElement( - predicate( - (uuid) => BleUuidParser.compareStrings(uuid, HilUuid.service), + final elapsed = Stopwatch()..start(); + void trace(String message) => debugPrintSynchronously( + 'HIL-SCAN +${elapsed.elapsedMilliseconds}ms ' + 'fixture=${peripheral.deviceId} $message', + ); + trace('disconnect before fresh scan'); + await peripheral.close(); + final complete = Completer(); + String? name; + var hasService = false; + int? rssi; + // The advertisement and scan response can arrive separately. Collect + // evidence only from this fixture and only during this scan. + final subscription = UniversalBle.scanStream.listen((device) { + if (device.deviceId != peripheral.deviceId || complete.isCompleted) { + return; + } + trace('result name=${device.name} rawName=${device.rawName} ' + 'services=${device.services} rssi=${device.rssi} ' + 'connectable=${device.connectable}'); + if (device.name == HilPeripheral.deviceName) name = device.name; + hasService |= device.services.any( + (uuid) => BleUuidParser.compareStrings(uuid, HilUuid.service), + ); + rssi = device.rssi ?? rssi; + if (name != null && hasService && rssi != null) { + trace('collected name=$name hasService=$hasService rssi=$rssi'); + complete.complete(); + } + }); + try { + trace('start filtered scan; timeout=${HilPeripheral.scanTimeout}'); + await UniversalBle.startScan( + scanFilter: ScanFilter( + withServices: const [HilUuid.service], + withNamePrefix: const [HilPeripheral.deviceName], ), - ), - ); - expect(peripheral.device.rssi, isNotNull); + ); + await complete.future.timeout( + HilPeripheral.scanTimeout, + onTimeout: () => fail( + 'Incomplete fixture advertisement: name=$name, ' + 'hasService=$hasService, rssi=$rssi', + ), + ); + } finally { + await subscription.cancel(); + await UniversalBle.stopScan(); + trace('scan stopped; name=$name hasService=$hasService rssi=$rssi'); + } }); testWidgets('performs a fresh scan through both result APIs', (_) async { @@ -55,14 +95,17 @@ void main() { final streamResult = Completer(); final callbackResult = Completer(); + final fixtureId = UniversalBle.canonicalDeviceId(peripheral.deviceId); final subscription = UniversalBle.scanStream.listen((device) { - if (device.name == HilPeripheral.deviceName && + if (device.deviceId == fixtureId && + device.name == HilPeripheral.deviceName && !streamResult.isCompleted) { streamResult.complete(device); } }); UniversalBle.onScanResult = (device) { - if (device.name == HilPeripheral.deviceName && + if (device.deviceId == fixtureId && + device.name == HilPeripheral.deviceName && !callbackResult.isCompleted) { callbackResult.complete(device); } diff --git a/hil/integration_test/fault_injection_hil_test.dart b/hil/integration_test/fault_injection_hil_test.dart index 47dba2cf..7d03ec19 100644 --- a/hil/integration_test/fault_injection_hil_test.dart +++ b/hil/integration_test/fault_injection_hil_test.dart @@ -8,10 +8,18 @@ import 'package:integration_test/integration_test.dart'; import 'package:universal_ble/universal_ble.dart'; import 'package:universal_ble_hil/src/hil_peripheral.dart'; +abstract final class _FaultGroup { + static const connection = 'connection-discovery'; + static const gatt = 'gatt-operations'; + static const delivery = 'notifications-indications'; + static const mtu = 'mtu-resources'; + static const timing = 'timing-sweeps'; +} + void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); - group('UniversalBle fault injection tests (FIT)', () { + group('UniversalBle fault insertion tests', () { late HilPeripheral peripheral; var setupSucceeded = false; @@ -27,14 +35,14 @@ void main() { if (setupSucceeded) { setupSucceeded = false; try { - await peripheral.close(); + await peripheral.dispose(); } catch (_) { // A fault scenario may deliberately leave the peripheral offline. } } }); - group('advertising and scanning', () { + group('[${_FaultGroup.connection}] advertising and scanning', () { _pending( '[FIT-ADV-001] discovers a peripheral that starts advertising after the scan begins', ); @@ -61,7 +69,8 @@ void main() { ); }); - group('connection establishment and teardown', () { + group('[${_FaultGroup.connection}] connection establishment and teardown', + () { _pending( '[FIT-CONN-001] fails within the deadline when advertising stops before connection', ); @@ -142,7 +151,7 @@ void main() { var attempted = 0; var hostFirst = 0; var peripheralFirst = 0; - // The peripheral deadline starts inside the control-write callback. + // The peripheral deadline starts when the fixture accepts the plan. // Sweep host teardown before, around, and after that deadline. These // are fault offsets, not an ACK grace period. Counters prove that // the peripheral plan executed or was cancelled. Event ordering @@ -161,6 +170,10 @@ void main() { const Duration(milliseconds: 250), )); if (armResult is _AsyncFailure) { + if (peripheral.usesWiredControl) { + Error.throwWithStackTrace( + armResult.error, armResult.stackTrace); + } expect(armResult.error, isA()); } debugPrint( @@ -216,14 +229,23 @@ void main() { '[FIT-CONN-008] handles two concurrent connect requests without duplicate connected events', ); testWidgets( - '[FIT-CONN-009] reconnects while the old disconnect callback is pending', + '[FIT-CONN-009] reconnects immediately after a reported link loss', (_) async { UniversalBle.queueType = QueueType.none; + final clock = Stopwatch()..start(); + var delayMs = 0; + void trace(String message) => debugPrintSynchronously( + 'FIT-CONN-009 +${clock.elapsedMilliseconds}ms ' + 'delayMs=$delayMs fixture=${peripheral.deviceId} $message', + ); + final subscription = + UniversalBle.connectionChangeStream(peripheral.deviceId) + .listen((event) => trace('event $event')); + addTearDown(subscription.cancel); - // Sweep a narrow window between the native link becoming disconnected - // and ConnectionStatusChanged removing the old device agent. Merely - // finding the agent in the native map must not produce a false - // connected result or suppress the replacement attempt. + // The fixture ACK is not evidence that the link is down. + // Start at the host's disconnect event, without waiting for a + // settling period or retrying a failed connection or read. for (final delay in [ Duration.zero, const Duration(milliseconds: 1), @@ -231,20 +253,29 @@ void main() { const Duration(milliseconds: 10), const Duration(milliseconds: 25), ]) { - try { - await peripheral.requestDisconnect(Duration.zero); - } catch (_) { - // The disconnect may win the race with the control-write ACK. - } - await Future.delayed(delay); - - await UniversalBle.connect( - peripheral.deviceId, - timeout: HilPeripheral.operationTimeout, - ); - expect( - utf8.decode(await peripheral.read(HilUuid.read)), - 'HIL-READ-V1', + delayMs = delay.inMilliseconds; + await _requestDisconnectAndWait( + peripheral, + Duration.zero, + trace: trace, + afterDisconnect: () async { + if (delay > Duration.zero) await Future.delayed(delay); + + trace('connect begin; queue=none, no retries'); + await UniversalBle.connect( + peripheral.deviceId, + timeout: HilPeripheral.operationTimeout, + ); + trace('connect returned; immediate read begin'); + final value = utf8.decode(await peripheral.read(HilUuid.read)); + trace('read returned: $value'); + expect( + value, + 'HIL-READ-V1', + reason: + 'Reconnect delay after link loss: ${delay.inMilliseconds} ms', + ); + }, ); } }, @@ -283,18 +314,38 @@ void main() { (_) async { const cycles = 5; final events = []; - final subscription = peripheral.connections.listen(events.add); + final clock = Stopwatch()..start(); + var currentCycle = 0; + void trace(String message) => debugPrintSynchronously( + 'FIT-CONN-013 +${clock.elapsedMilliseconds}ms ' + 'cycle=$currentCycle fixture=${peripheral.deviceId} $message', + ); + final subscription = + UniversalBle.connectionChangeStream(peripheral.deviceId).listen( + (event) { + events.add(event.isConnected); + trace('event #${events.length}: $event'); + }, + ); addTearDown(subscription.cancel); for (var cycle = 0; cycle < cycles; cycle++) { - await _requestImmediateDisconnect(peripheral); - await peripheral.reconnect(); + currentCycle = cycle + 1; + await _requestDisconnectAndWait( + peripheral, + Duration.zero, + trace: trace, + ); + trace('reconnect begin'); + await peripheral.reconnect(trace: trace); await _waitUntil( () async => events.where((connected) => connected).length >= cycle + 1, ); + trace('cycle complete; events=$events'); } await Future.delayed(const Duration(milliseconds: 300)); + trace('final event order=$events'); expect( events, @@ -323,7 +374,7 @@ void main() { peripheral.deviceId, timeout: HilPeripheral.operationTimeout, ); - final discovered = await _discoverHilPeripheral(); + final discovered = await _discoverHilPeripheral(peripheral); // Connect immediately after discovery. Do not use // HilPeripheral.reconnect(), because its retry loop would hide a @@ -372,7 +423,9 @@ void main() { ); }); - group('service discovery and GATT database changes', () { + group( + '[${_FaultGroup.connection}] service discovery and GATT database changes', + () { _pending( '[FIT-DISC-001] fails safely when the peripheral disconnects during service discovery', ); @@ -536,7 +589,7 @@ void main() { ); }); - group('read faults', () { + group('[${_FaultGroup.gatt}] read faults', () { testWidgets( '[FIT-READ-001] reports an ATT read error without disconnecting', (_) async { @@ -681,7 +734,7 @@ void main() { ); }); - group('write-with-response faults', () { + group('[${_FaultGroup.gatt}] write-with-response faults', () { testWidgets( '[FIT-WRITE-001] reports an ATT write error without disconnecting', (_) async { @@ -791,7 +844,7 @@ void main() { ); }); - group('write-without-response faults', () { + group('[${_FaultGroup.gatt}] write-without-response faults', () { _pending( '[FIT-WNR-001] remains connected when the peripheral rejects a command write', ); @@ -815,7 +868,7 @@ void main() { ); }); - group('descriptor faults', () { + group('[${_FaultGroup.gatt}] descriptor faults', () { testWidgets( '[FIT-DESC-001] reports an ATT descriptor read error and recovers', (_) async { @@ -886,7 +939,7 @@ void main() { ); }); - group('notification subscription faults', () { + group('[${_FaultGroup.delivery}] notification subscription faults', () { _pending( '[FIT-SUB-001] fails safely when the peripheral disconnects during CCC enable', ); @@ -993,7 +1046,7 @@ void main() { ); }); - group('notification delivery faults', () { + group('[${_FaultGroup.delivery}] notification delivery faults', () { testWidgets( '[FIT-NOTIFY-001] receives a notification emitted immediately after CCC enable', (_) async { @@ -1192,7 +1245,7 @@ void main() { ); }); - group('indication delivery faults', () { + group('[${_FaultGroup.delivery}] indication delivery faults', () { testWidgets( '[FIT-IND-001] receives an indication emitted immediately after CCC enable', (_) async { @@ -1221,6 +1274,9 @@ void main() { peripheral.requestIndicationScenario(reboot ? 2 : 1)); expect(await disconnected, isNot(isA<_AsyncFailure>())); if (result is _AsyncFailure) { + if (peripheral.usesWiredControl) { + Error.throwWithStackTrace(result.error, result.stackTrace); + } expect(result.error, isA()); } await peripheral.reconnect(); @@ -1304,7 +1360,7 @@ void main() { ); }); - group('MTU, long values, and resource pressure', () { + group('[${_FaultGroup.mtu}] MTU, long values, and resource pressure', () { _unsupported( '[FIT-MTU-001] handles disconnect while querying the negotiated MTU', 'Windows reads local MTU metadata; no fixture-side query callback to interrupt.', @@ -1409,7 +1465,9 @@ void main() { ); }); - group('pairing, bonding, and encrypted attributes', () { + group( + '[${_FaultGroup.connection}] pairing, bonding, and encrypted attributes', + () { _unsupportedPairing( '[FIT-SMP-001] triggers pairing when an encrypted read is attempted', ); @@ -1434,7 +1492,8 @@ void main() { ); }); - group('deterministic timing sweeps and recovery', () { + group('[${_FaultGroup.timing}] deterministic timing sweeps and recovery', + () { testWidgets( '[FIT-RACE-001] sweeps disconnect timing across connection establishment', (_) async { @@ -1443,7 +1502,7 @@ void main() { await peripheral .armConnectFault(Duration(milliseconds: milliseconds)); await peripheral.close(); - await _discoverHilPeripheral(); + await _discoverHilPeripheral(peripheral); // The one-shot plan survives the host disconnect and starts at // the next firmware connection callback. A sufficiently early // failure may prevent Windows from emitting any "connected" event. @@ -1467,7 +1526,7 @@ void main() { delay: const Duration(milliseconds: 300), disconnectAfter: Duration(milliseconds: milliseconds)); await peripheral.close(); - await _discoverHilPeripheral(); + await _discoverHilPeripheral(peripheral); // Connect performs uncached discovery. discoverServices() alone // can return Windows' cached map without reaching the fixture. await _connectThroughFixtureFault(peripheral); @@ -1591,7 +1650,9 @@ Future _runTimingScenarioOnce( await peripheral.armCccFault( disconnectAfter: disconnectAfter, callbackDelay: callbackDelay); } - final disconnected = _captureResult(_waitForDisconnect(peripheral)); + final disconnected = _captureResult(peripheral.connections + .firstWhere((connected) => !connected) + .timeout(HilPeripheral.operationTimeout)); final Future action = switch (operation) { 'read' => peripheral.read(HilUuid.read), 'write' => peripheral.write(HilUuid.write, [0x41, 0x42]), @@ -1610,17 +1671,37 @@ Future _runTimingScenarioOnce( // A later disconnect can still precede delivery of the ATT response to Windows. expect(result.error, isA()); } - await peripheral.reconnect(); - // Read before reset clears the counters. Link loss alone does not prove that - // the armed fixture callback ran and its scheduled disconnect executed. - final telemetry = await peripheral.readTelemetry(); + // Snapshot the fault before recovery can add unrelated disconnects. + final scenario = '$operation disconnectAfterMs=$milliseconds'; + final wired = peripheral.usesWiredControl; + late HilTelemetry telemetry; + if (wired) { + // WinRT can report disconnection before the fixture sees link teardown. + await _waitUntil(() async { + telemetry = await peripheral.readWiredTelemetry(); + return telemetry.physicalDisconnects != 0; + }); + } else { + await peripheral.reconnect(); + telemetry = await peripheral.readTelemetry(); + } expect(telemetry.disconnectTimersArmed, 1); expect(telemetry.disconnectTimersAttempted, 1); expect(telemetry.disconnectTimersCancelled, 0); - expect(telemetry.physicalDisconnects, 1); + expect(telemetry.physicalDisconnects, 1, reason: scenario); if (operation == 'enable' || operation == 'disable') { expect(telemetry.cccFaultsTriggered, 1); } + if (wired) { + await peripheral.reconnect( + trace: (message) => + debugPrintSynchronously('HIL timing $scenario: $message'), + ); + final recovered = await peripheral.readWiredTelemetry(); + debugPrintSynchronously('HIL timing $scenario: physical disconnects ' + '${telemetry.physicalDisconnects} before recovery, ' + '${recovered.physicalDisconnects} after recovery'); + } await peripheral.reset(); await _verifyRecovery(peripheral); } @@ -1635,10 +1716,12 @@ Future _waitForDisconnect(HilPeripheral peripheral) async { .timeout(HilPeripheral.operationTimeout); } -Future _discoverHilPeripheral() async { +Future _discoverHilPeripheral(HilPeripheral peripheral) async { final result = Completer(); + final fixtureId = UniversalBle.canonicalDeviceId(peripheral.deviceId); final subscription = UniversalBle.scanStream.listen((device) { if (!result.isCompleted && + device.deviceId == fixtureId && (device.name == HilPeripheral.deviceName || device.services.any(_isHilService))) { result.complete(device); @@ -1675,25 +1758,37 @@ Future _requestImmediateDisconnect(HilPeripheral peripheral) async { Future _requestDisconnectAndWait( HilPeripheral peripheral, - Duration delay, -) async { - final disconnected = _waitForDisconnect(peripheral); - Object? commandError; - StackTrace? commandStackTrace; - try { + Duration delay, { + void Function(String message)? trace, + Future Function()? afterDisconnect, +}) async { + final disconnected = _captureResult(_waitForDisconnect(peripheral)); + final command = _captureResult(() async { + trace?.call( + 'request peripheral disconnect; delayMs=${delay.inMilliseconds}'); await peripheral.requestDisconnect(delay); - } catch (error, stackTrace) { - commandError = error; - commandStackTrace = stackTrace; + trace?.call('fixture acknowledged disconnect command'); + }()); + + if (!peripheral.usesWiredControl) await command; + final event = await disconnected; + if (event is! _AsyncFailure) { + trace?.call('host observed disconnected'); + try { + await afterDisconnect?.call(); + } finally { + await command; + } } - - try { - await disconnected; - } catch (_) { - if (commandError != null) { - Error.throwWithStackTrace(commandError, commandStackTrace!); + final result = await command; + if (result is _AsyncFailure) { + trace?.call('fixture disconnect command failed: ${result.error}'); + if (peripheral.usesWiredControl || event is _AsyncFailure) { + Error.throwWithStackTrace(result.error, result.stackTrace); } - rethrow; + } + if (event is _AsyncFailure) { + Error.throwWithStackTrace(event.error, event.stackTrace); } } diff --git a/hil/lib/main.dart b/hil/lib/main.dart index 78a48252..06ea3a66 100644 --- a/hil/lib/main.dart +++ b/hil/lib/main.dart @@ -183,7 +183,7 @@ class _HilWebRunnerPageState extends State { ); }); } finally { - await peripheral.close(); + await peripheral.dispose(); } } catch (error, stackTrace) { setState(() => _fatalError = '$error\n$stackTrace'); diff --git a/hil/lib/src/hil_peripheral.dart b/hil/lib/src/hil_peripheral.dart index c4b97cad..d3faaec5 100644 --- a/hil/lib/src/hil_peripheral.dart +++ b/hil/lib/src/hil_peripheral.dart @@ -3,6 +3,8 @@ import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:universal_ble/universal_ble.dart'; +import 'hil_serial_stub.dart' if (dart.library.io) 'hil_serial_io.dart'; + abstract final class HilUuid { static const service = '7e570001-7e57-4e57-8e57-7e5700000001'; static const control = '7e570002-7e57-4e57-8e57-7e5700000001'; @@ -127,7 +129,7 @@ final class HilState { } final class HilPeripheral { - HilPeripheral._(this.device); + HilPeripheral._(this.device, this._serial); static const deviceName = 'UniversalBLE-HIL'; static const contractRevision = 2; @@ -138,37 +140,75 @@ final class HilPeripheral { static BleDevice? _discoveredDevice; final BleDevice device; + final HilSerial? _serial; String get deviceId => device.deviceId; + bool get usesWiredControl => _serial != null; static Future open() async { UniversalBle.timeout = operationTimeout; UniversalBle.queueType = QueueType.global; await UniversalBle.setLogLevel(BleLogLevel.verbose); - final device = _configuredDeviceId.isEmpty || kIsWeb - ? _discoveredDevice ??= await _discover() - : BleDevice(deviceId: _configuredDeviceId, name: deviceName); + final serial = await HilSerial.open(); + HilPeripheral? peripheral; + try { + final address = serial?.address ?? _configuredDeviceId; + if (serial != null && + _configuredDeviceId.isNotEmpty && + UniversalBle.canonicalDeviceId(address) != + UniversalBle.canonicalDeviceId(_configuredDeviceId)) { + throw StateError( + 'HIL_SERIAL_PORT fixture does not match HIL_DEVICE_ID'); + } + final device = serial != null + ? await _discoverSerialFixture(address) + : address.isEmpty || kIsWeb + ? _discoveredDevice ??= await _discover() + : BleDevice(deviceId: address, name: deviceName); + peripheral = HilPeripheral._(device, serial); + await peripheral.reconnect(timeout: scanTimeout); + await peripheral.reset(); + final actualContractRevision = + (await peripheral.readState()).contractRevision; + if (actualContractRevision != contractRevision) { + throw StateError( + 'HIL fixture contract mismatch: expected revision $contractRevision, ' + 'received $actualContractRevision. Build and flash the matching ' + 'universal_ble_hil_firmware image.', + ); + } + return peripheral; + } catch (_) { + try { + if (peripheral != null) { + await peripheral.dispose(); + } else { + await serial?.close(); + } + } catch (error) { + debugPrintSynchronously('HIL setup cleanup failed: $error'); + } + rethrow; + } + } - final peripheral = HilPeripheral._(device); - await peripheral.reconnect(timeout: scanTimeout); - await peripheral.reset(); - final actualContractRevision = - (await peripheral.readState()).contractRevision; - if (actualContractRevision != contractRevision) { - throw StateError( - 'HIL fixture contract mismatch: expected revision $contractRevision, ' - 'received $actualContractRevision. Build and flash the matching ' - 'universal_ble_hil_firmware image.', - ); + static Future _discoverSerialFixture(String address) async { + final cached = _discoveredDevice; + if (cached != null && + cached.deviceId == UniversalBle.canonicalDeviceId(address)) { + return cached; } - return peripheral; + return _discoveredDevice = await _discover(address: address); } - static Future _discover() async { + static Future _discover({String? address}) async { final result = Completer(); + final expected = + address == null ? null : UniversalBle.canonicalDeviceId(address); final subscription = UniversalBle.scanStream.listen((device) { if (!result.isCompleted && + (expected == null || device.deviceId == expected) && (device.name == deviceName || device.services.any(_isHilService))) { result.complete(device); } @@ -194,29 +234,55 @@ final class HilPeripheral { Future close() => UniversalBle.disconnect(deviceId, timeout: operationTimeout); - Future reconnect({Duration timeout = scanTimeout}) async { + Future dispose() async { + try { + await close(); + } finally { + await _serial?.close(); + } + } + + Future reconnect({ + Duration timeout = scanTimeout, + void Function(String message)? trace, + }) async { final deadline = DateTime.now().add(timeout); Object? lastError; + var attempt = 0; do { + attempt++; + var phase = 'connect'; try { + trace?.call('attempt=$attempt connect begin'); await UniversalBle.connect( deviceId, timeout: const Duration(seconds: 5), ); + trace?.call('attempt=$attempt connect returned'); try { - await UniversalBle.requestMtu(deviceId, 247); - } catch (_) { + final mtu = await UniversalBle.requestMtu(deviceId, 247); + trace?.call('attempt=$attempt MTU=$mtu'); + } catch (error) { // MTU negotiation may fail after some disconnect sequences; // the connection is still usable with the default MTU. + trace?.call('attempt=$attempt MTU failed: $error'); } - await discover(); + phase = 'discover'; + trace?.call('attempt=$attempt discovery begin'); + final services = await discover(); + trace?.call( + 'attempt=$attempt discovery returned ${services.length} services'); return; } catch (error) { lastError = error; + trace?.call('attempt=$attempt phase=$phase failed: $error'); + trace?.call('attempt=$attempt cleanup disconnect begin'); await UniversalBle.disconnect( deviceId, timeout: const Duration(seconds: 2), ); + trace?.call( + 'attempt=$attempt cleanup disconnect returned; retry in 1000 ms'); await Future.delayed(const Duration(seconds: 1)); } } while (DateTime.now().isBefore(deadline)); @@ -254,6 +320,7 @@ final class HilPeripheral { ); Future command(int opcode, [List payload = const []]) => + _serial?.command([opcode, ...payload]) ?? write(HilUuid.control, [opcode, ...payload]); Future reset() => command(HilCommand.reset); @@ -273,6 +340,12 @@ final class HilPeripheral { Future readTelemetry() async => HilTelemetry(await read(HilUuid.telemetry)); + Future readWiredTelemetry() async { + final serial = _serial; + if (serial == null) throw StateError('UART fixture control is unavailable'); + return HilTelemetry(await serial.readTelemetry()); + } + Future armIndicationOnSubscribe() => command(HilCommand.indicateOnSubscribe); diff --git a/hil/lib/src/hil_serial_io.dart b/hil/lib/src/hil_serial_io.dart new file mode 100644 index 00000000..b4595b5d --- /dev/null +++ b/hil/lib/src/hil_serial_io.dart @@ -0,0 +1,197 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter/foundation.dart'; + +// The helper owns the COM port for one case. A private loopback connection +// carries serial lines and closes automatically if the test app exits. +const _bridge = r''' +$ErrorActionPreference = 'Stop' +$port = [IO.Ports.SerialPort]::new($env:HIL_SERIAL_PORT, 115200) +$port.DtrEnable = $true +$port.WriteTimeout = 2000 +$port.ReadTimeout = 4000 +$port.ReadBufferSize = 65536 +$client = [Net.Sockets.TcpClient]::new() +try { + $client.Connect('127.0.0.1', [int]$env:HIL_UART_BRIDGE_PORT) + $client.NoDelay = $true + $stream = $client.GetStream() + $reader = [IO.StreamReader]::new($stream) + $writer = [IO.StreamWriter]::new($stream) + $writer.AutoFlush = $true + $port.Open() + $port.WriteLine('') + while ($true) { + $line = $reader.ReadLine() + if ($null -eq $line) { break } + $prefix = 'HIL ' + $line.Substring(0, 8) + ' ' + $port.WriteLine($line) + do { + $received = $port.ReadLine().TrimEnd([char]13) + $writer.WriteLine($received) + } until ($received.StartsWith($prefix, [StringComparison]::Ordinal)) + } +} finally { + $port.Dispose() + $client.Dispose() +} +'''; + +class HilSerial { + HilSerial._(this._process, this._socket, this._nextId) { + _replies = _socket + .cast>() + .transform(const Utf8Decoder(allowMalformed: true)) + .transform(const LineSplitter()) + .listen(_onLine, onError: _fail, onDone: () { + _fail(StateError('HIL UART bridge disconnected')); + }); + unawaited(_process.stdout.drain()); + _stderr = _process.stderr + .transform(const Utf8Decoder(allowMalformed: true)) + .transform(const LineSplitter()) + .listen((line) => debugPrintSynchronously('HIL UART helper: $line')); + unawaited(_process.exitCode.then((code) { + _fail(StateError('HIL UART helper exited ($code)')); + })); + } + + final Process _process; + final Socket _socket; + late final StreamSubscription _replies; + late final StreamSubscription _stderr; + late String address; + int _nextId; + String? _pendingId; + Completer? _pending; + Object? _failure; + Future _tail = Future.value(); + + static Future open() async { + if (!Platform.isWindows) return null; + final port = Platform.environment['HIL_SERIAL_PORT'] ?? ''; + if (!RegExp(r'^COM[1-9][0-9]*$', caseSensitive: false).hasMatch(port)) { + throw StateError( + 'Set HIL_SERIAL_PORT to the fixture COM port (e.g. COM4).'); + } + final script = base64.encode([ + for (final unit in _bridge.codeUnits) ...[unit & 255, unit >> 8], + ]); + final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); + Process? process; + final Socket socket; + try { + process = await Process.start('powershell.exe', [ + '-NoLogo', + '-NoProfile', + '-NonInteractive', + '-OutputFormat', + 'Text', + '-EncodedCommand', + script, + ], environment: { + 'HIL_UART_BRIDGE_PORT': '${server.port}' + }); + socket = await server.first.timeout(const Duration(seconds: 5)); + } catch (_) { + process?.kill(); + rethrow; + } finally { + await server.close(); + } + socket.setOption(SocketOption.tcpNoDelay, true); + final serial = + HilSerial._(process, socket, DateTime.now().microsecondsSinceEpoch); + try { + final reply = await serial._exchange([0xff]); + final match = RegExp(r'^READY 2 ((?:[0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2})$') + .firstMatch(reply); + if (match == null) { + throw StateError('Unexpected HIL UART handshake: $reply'); + } + serial.address = match[1]!; + debugPrintSynchronously('HIL UART $port: fixture ${serial.address}'); + return serial; + } catch (_) { + await serial.close(); + rethrow; + } + } + + Future command(List bytes) { + return _request(bytes).then((reply) { + if (reply != '0') { + throw StateError('Fixture rejected UART opcode ${bytes.first}: $reply'); + } + }); + } + + Future readTelemetry() async { + final reply = await _request([0xfe]); + final match = RegExp(r'^TELEMETRY ([0-9a-fA-F]{72})$').firstMatch(reply); + if (match == null) { + throw StateError( + 'Fixture must support UART telemetry; reflash the matching firmware. Reply: $reply'); + } + final hex = match[1]!; + return Uint8List.fromList([ + for (var i = 0; i < hex.length; i += 2) + int.parse(hex.substring(i, i + 2), radix: 16), + ]); + } + + Future _request(List bytes) { + final result = _tail.then((_) => _exchange(bytes)); + _tail = result.then((_) {}, onError: (Object _, StackTrace __) {}); + return result; + } + + Future _exchange(List bytes) async { + if (_failure case final failure?) throw failure; + final id = (_nextId++ & 0xffffffff).toRadixString(16).padLeft(8, '0'); + final reply = Completer(); + _pendingId = id; + _pending = reply; + final hex = + bytes.map((byte) => byte.toRadixString(16).padLeft(2, '0')).join(); + try { + _socket.write('$id $hex\n'); + await _socket.flush(); + return await reply.future.timeout(const Duration(seconds: 5)); + } on TimeoutException { + final error = + StateError('HIL UART timed out (request $id, opcode ${bytes.first})'); + _fail(error); + throw error; + } finally { + _pending = null; + _pendingId = null; + } + } + + void _onLine(String line) { + final prefix = 'HIL $_pendingId '; + final pending = _pending; + if (pending != null && !pending.isCompleted && line.startsWith(prefix)) { + pending.complete(line.substring(prefix.length)); + } else { + debugPrintSynchronously('HIL fixture: $line'); + } + } + + void _fail(Object error) { + _failure ??= error; + final pending = _pending; + if (pending != null && !pending.isCompleted) pending.completeError(error); + } + + Future close() async { + _socket.destroy(); + _process.kill(); + await _process.exitCode; + await _replies.cancel(); + await _stderr.cancel(); + } +} diff --git a/hil/lib/src/hil_serial_stub.dart b/hil/lib/src/hil_serial_stub.dart new file mode 100644 index 00000000..c6df853b --- /dev/null +++ b/hil/lib/src/hil_serial_stub.dart @@ -0,0 +1,12 @@ +import 'dart:typed_data'; + +class HilSerial { + static Future open() async => null; + + String get address => throw UnsupportedError('UART is unavailable'); + Future command(List bytes) => + throw UnsupportedError('UART is unavailable'); + Future readTelemetry() => + throw UnsupportedError('UART is unavailable'); + Future close() async {} +} diff --git a/hil/run_windows_hil_group.ps1 b/hil/run_windows_hil_group.ps1 new file mode 100644 index 00000000..13b70c8f --- /dev/null +++ b/hil/run_windows_hil_group.ps1 @@ -0,0 +1,56 @@ +param( + [Parameter(Mandatory)] + [ValidateSet('baseline', 'connection-discovery', 'gatt-operations', + 'notifications-indications', 'mtu-resources', 'timing-sweeps')] + [string]$Group, + [ValidateRange(1, 3600)] + [int]$TimeoutSeconds = 480, + [switch]$Worker +) + +$ErrorActionPreference = 'Stop' +$logDirectory = if ($env:HIL_LOG_DIR) { $env:HIL_LOG_DIR } else { $PSScriptRoot } +$log = Join-Path $logDirectory "$Group-hil.log" + +if (-not $Worker) { + $start = [Diagnostics.ProcessStartInfo]::new() + $start.FileName = Join-Path $PSHOME 'pwsh.exe' + $start.WorkingDirectory = $PSScriptRoot + $start.UseShellExecute = $false + foreach ($argument in @('-NoProfile', '-NonInteractive', '-File', + $PSCommandPath, '-Group', $Group, '-Worker')) { + $start.ArgumentList.Add($argument) + } + $process = [Diagnostics.Process]::Start($start) + try { + if ($process.WaitForExit($TimeoutSeconds * 1000)) { + exit $process.ExitCode + } + $message = "$Group timed out after $TimeoutSeconds seconds." + Write-Host $message + try { + $process.Kill($true) + if (-not $process.WaitForExit(10000)) { + throw "The $Group test process did not exit after termination." + } + } finally { + Add-Content -LiteralPath $log -Value $message + } + exit 124 + } finally { + $process.Dispose() + } +} + +$PSNativeCommandUseErrorActionPreference = $false +$suite = if ($Group -eq 'baseline') { 'baseline' } else { 'fault_injection' } +$arguments = @('test', "integration_test/${suite}_hil_test.dart", '-d', 'windows', + '--no-pub', '--reporter=expanded') +if ($Group -ne 'baseline') { + $arguments += @('--plain-name', "[$Group]") +} +if ($env:HIL_DEVICE_ID) { + $arguments += "--dart-define=HIL_DEVICE_ID=$env:HIL_DEVICE_ID" +} +flutter @arguments 2>&1 | Tee-Object -FilePath $log +exit $LASTEXITCODE From 7b9cf1b6727e650cdecff9da975c51c44b95fd09 Mon Sep 17 00:00:00 2001 From: Foti Dim Date: Thu, 12 Nov 2026 20:30:19 +0100 Subject: [PATCH 02/11] fix(hil): robust prefix matching and buffer discard for HIL UART bridge --- hil/lib/src/hil_serial_io.dart | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/hil/lib/src/hil_serial_io.dart b/hil/lib/src/hil_serial_io.dart index b4595b5d..2841a585 100644 --- a/hil/lib/src/hil_serial_io.dart +++ b/hil/lib/src/hil_serial_io.dart @@ -22,6 +22,7 @@ try { $writer = [IO.StreamWriter]::new($stream) $writer.AutoFlush = $true $port.Open() + $port.DiscardInBuffer() $port.WriteLine('') while ($true) { $line = $reader.ReadLine() @@ -31,7 +32,7 @@ try { do { $received = $port.ReadLine().TrimEnd([char]13) $writer.WriteLine($received) - } until ($received.StartsWith($prefix, [StringComparison]::Ordinal)) + } until ($received.IndexOf($prefix, [StringComparison]::Ordinal) -ge 0) } } finally { $port.Dispose() @@ -174,8 +175,9 @@ class HilSerial { void _onLine(String line) { final prefix = 'HIL $_pendingId '; final pending = _pending; - if (pending != null && !pending.isCompleted && line.startsWith(prefix)) { - pending.complete(line.substring(prefix.length)); + final index = line.indexOf(prefix); + if (pending != null && !pending.isCompleted && index >= 0) { + pending.complete(line.substring(index + prefix.length)); } else { debugPrintSynchronously('HIL fixture: $line'); } From a3d52742b7ff312688505e804a0e45f5ee5853aa Mon Sep 17 00:00:00 2001 From: Foti Dim Date: Thu, 12 Nov 2026 20:36:56 +0100 Subject: [PATCH 03/11] ci(hil): support dual-port J-Link OB devices by selecting VCOM0 --- .github/workflows/windows_hil.yml | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/.github/workflows/windows_hil.yml b/.github/workflows/windows_hil.yml index fbe87924..328d4d83 100644 --- a/.github/workflows/windows_hil.yml +++ b/.github/workflows/windows_hil.yml @@ -66,19 +66,24 @@ jobs: if ($_.FriendlyName -notmatch '\((COM[1-9][0-9]*)\)$') { return } $port = $Matches[1] $id = $_.InstanceId + $isVcom0 = $id -match '&MI_00' for ($depth = 0; $id -and $depth -lt 8; $depth++) { if ($id -match '^USB\\VID_1366&PID_[0-9A-F]{4}\\0*([1-9][0-9]*)$') { - if ($Matches[1] -eq $serial) { $port } + if ($Matches[1] -eq $serial) { [PSCustomObject]@{ Port = $port; Vcom0 = $isVcom0 } } break } $id = (Get-PnpDeviceProperty -InstanceId $id -KeyName DEVPKEY_Device_Parent -ErrorAction SilentlyContinue).Data } }) - if ($ports.Count -ne 1) { - throw "Expected one COM port for J-Link $env:HIL_JLINK_SERIAL; found $($ports.Count): $($ports -join ', '). Check the DK USB connection and SEGGER CDC driver." + if ($ports.Count -eq 0) { + throw "Expected at least one COM port for J-Link $env:HIL_JLINK_SERIAL; found 0. Check the DK USB connection and SEGGER CDC driver." } - Write-Host "J-Link $env:HIL_JLINK_SERIAL UART: $($ports[0])" - "HIL_SERIAL_PORT=$($ports[0])" >> $env:GITHUB_ENV + $selectedPort = ($ports | Where-Object { $_.Vcom0 } | Select-Object -ExpandProperty Port -First 1) + if (-not $selectedPort) { + $selectedPort = $ports[0].Port + } + Write-Host "J-Link $env:HIL_JLINK_SERIAL UART: $selectedPort (from: $($ports.Port -join ', '))" + "HIL_SERIAL_PORT=$selectedPort" >> $env:GITHUB_ENV "HIL_JLINK_SERIAL=$serial" >> $env:GITHUB_ENV - name: Prepare Windows test app From 397fcea959be9ea673461d641e3332484b6d5813 Mon Sep 17 00:00:00 2001 From: Foti Dim Date: Thu, 12 Nov 2026 21:24:57 +0100 Subject: [PATCH 04/11] ci(hil): enable runs-on.group: windows-hil for upstream deployment --- .github/workflows/windows_hil.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/windows_hil.yml b/.github/workflows/windows_hil.yml index 328d4d83..7623217e 100644 --- a/.github/workflows/windows_hil.yml +++ b/.github/workflows/windows_hil.yml @@ -29,7 +29,7 @@ jobs: if: github.ref == format('refs/heads/{0}', github.event.repository.default_branch) environment: windows-hil runs-on: - # group: windows-hil + group: windows-hil labels: [self-hosted, Windows, X64, universal-ble-hil] timeout-minutes: 60 defaults: From fd37dda83279bb3b583900986a0f327c029fb651 Mon Sep 17 00:00:00 2001 From: Foti Dim Date: Thu, 19 Nov 2026 10:47:11 +0100 Subject: [PATCH 05/11] ci(hil): keep the hardware runner behind org controls and fit the budgets The branch guard cannot protect the self-hosted runner: a workflow_dispatch run executes the YAML of the selected ref, so anyone with write access can dispatch a branch whose copy of this file drops the guard. Say so in the header, name the two organization controls the job actually depends on (the runner group's workflow-access allowlist and the environment's deployment-branch and reviewer rules), and add github.workflow_ref as a second signal rather than implying the file is sufficient on its own. Budgets: - pass a per-group -TimeoutSeconds above that group's declared per-test timeouts; timing-sweeps alone sums to 34 minutes, so 480 seconds could never fit; - raise the job timeout to cover 180 minutes of group budgets plus preparation, the warm build, and the flash; - warm the CMake/MSVC build once outside the timed groups; - start from a clean windows/, build/ and .metadata on a persistent runner. Smaller fixes: - mask HIL_JLINK_SERIAL, and keep the configured serial (leading zeros included) for the jlink -USB selection while matching the PnP instance id without them; - fail and print the discovered ports when no VCOM0 interface exists instead of falling back to $ports[0]; - invoke the group script with an explicit execution policy; - guard the group conditions with `inputs.test_group || 'all'`; - pin the used actions by SHA on the hardware runner; - name the PCA10040 board next to the device name; - warn instead of ignoring a missing log artifact. --- .github/workflows/windows_hil.yml | 136 ++++++++++++++++++++++++------ 1 file changed, 111 insertions(+), 25 deletions(-) diff --git a/.github/workflows/windows_hil.yml b/.github/workflows/windows_hil.yml index 7623217e..553788db 100644 --- a/.github/workflows/windows_hil.yml +++ b/.github/workflows/windows_hil.yml @@ -1,5 +1,22 @@ name: Windows HIL and Fault Insertion Tests +# This job needs a self-hosted runner with a physical nRF52 DK attached. Safety +# of that hardware depends on two organization settings that this file cannot +# enforce: +# +# 1. The `windows-hil` runner group must restrict workflow access to this +# repository and to +# Navideck/universal_ble/.github/workflows/windows_hil.yml@refs/heads/main. +# 2. The `windows-hil` environment must allow deployments only from the +# protected default branch and require a maintainer reviewer. +# +# The `if:` on the job below is an accident guard, not a security control: +# `workflow_dispatch` runs the workflow file of the selected ref, so anyone with +# write access could dispatch a branch whose copy of this file drops the guard +# and still asks for the hardware runner. Only the runner group's +# workflow-access allowlist and the environment's deployment rules keep the +# fixture out of reach; do not treat this file as sufficient on its own. + on: workflow_dispatch: inputs: @@ -25,13 +42,26 @@ concurrency: jobs: hil: - # Only run reviewed code from the protected default branch. - if: github.ref == format('refs/heads/{0}', github.event.repository.default_branch) + # Accident guard only; see the header comment. A dispatched branch can + # weaken this copy of the file, which is why the runner group allowlist and + # the environment rules are the load-bearing controls. The second clause + # also requires the default-branch copy of this workflow file, so a dispatch + # from a feature branch is refused even if that branch owns the YAML it runs. + # Update the owner, repository, path and ref when this workflow is deployed + # under another name or on a default branch other than `main`. + if: > + github.ref == format('refs/heads/{0}', github.event.repository.default_branch) && + github.workflow_ref == + 'Navideck/universal_ble/.github/workflows/windows_hil.yml@refs/heads/main' environment: windows-hil runs-on: group: windows-hil labels: [self-hosted, Windows, X64, universal-ble-hil] - timeout-minutes: 60 + # Per-group budgets below total 180 minutes when every group is selected; + # app preparation (15), the warm build (25) and the flash (10) add 50 more + # at their own caps, so this covers the worst case. It does not include the + # time an environment reviewer takes to approve the deployment. + timeout-minutes: 240 defaults: run: shell: pwsh @@ -51,7 +81,15 @@ jobs: New-Item -ItemType Directory -Path $logs | Out-Null "HIL_LOG_DIR=$logs" >> $env:GITHUB_ENV - - uses: actions/checkout@v4 + # Mask first: every later step prints step output, and the serial is used + # in several messages and command lines. This runs before checkout, so it + # cannot use the `hil` working directory yet. + - name: Mask the J-Link serial + working-directory: ${{ runner.temp }} + run: | + if ($env:HIL_JLINK_SERIAL) { "::add-mask::$env:HIL_JLINK_SERIAL" } + + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 with: persist-credentials: false @@ -61,6 +99,9 @@ jobs: $env:HIL_JLINK_SERIAL.TrimStart('0') -notmatch '^[1-9][0-9]{5,11}$') { throw 'Set HIL_JLINK_SERIAL to the dedicated DK onboard J-Link serial number.' } + # The PnP instance id drops leading zeros; SEGGER's -USB argument + # uses the serial as printed by J-Link, which keeps them. Match with + # the stripped form and select the probe with the value as configured. $serial = $env:HIL_JLINK_SERIAL.TrimStart('0') $ports = @(Get-PnpDevice -PresentOnly -Class Ports | ForEach-Object { if ($_.FriendlyName -notmatch '\((COM[1-9][0-9]*)\)$') { return } @@ -76,25 +117,44 @@ jobs: } }) if ($ports.Count -eq 0) { - throw "Expected at least one COM port for J-Link $env:HIL_JLINK_SERIAL; found 0. Check the DK USB connection and SEGGER CDC driver." + throw "Expected at least one COM port for the configured J-Link serial; found 0. Check the DK USB connection and SEGGER CDC driver." } + # The fixture's console is VCOM0. Guessing another interface would + # silently talk to the wrong endpoint, so fail with what was found. $selectedPort = ($ports | Where-Object { $_.Vcom0 } | Select-Object -ExpandProperty Port -First 1) if (-not $selectedPort) { - $selectedPort = $ports[0].Port + throw "J-Link probe exposes no VCOM0 interface; discovered: '$($ports.Port -join ', ')'. Reconnect the DK or reinstall the SEGGER CDC driver." } - Write-Host "J-Link $env:HIL_JLINK_SERIAL UART: $selectedPort (from: $($ports.Port -join ', '))" + Write-Host "J-Link UART: $selectedPort (from: $($ports.Port -join ', '))" "HIL_SERIAL_PORT=$selectedPort" >> $env:GITHUB_ENV - "HIL_JLINK_SERIAL=$serial" >> $env:GITHUB_ENV - name: Prepare Windows test app + timeout-minutes: 15 run: | + # Generated runners are not stored in Git, and this runner is + # persistent: drop a generated app and CMake tree from an earlier + # checkout instead of reusing a stale cache. + foreach ($path in @('windows', 'build', '.metadata')) { + if (Test-Path -LiteralPath $path) { + Remove-Item -LiteralPath $path -Recurse -Force + } + } flutter create --platforms=windows --no-pub . if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } flutter pub get exit $LASTEXITCODE + - name: Warm the Windows build + timeout-minutes: 25 + run: | + # The timed groups below no longer pay for a cold CMake/MSVC build of + # the plugin. The test build still relinks its own bundle, so this + # shortens the first group's wall clock rather than eliminating it. + flutter build windows --debug --no-pub + exit $LASTEXITCODE + - name: Clean-flash the nRF52 DK - timeout-minutes: 5 + timeout-minutes: 10 run: | # Java also ships a jlink.exe; do not resolve this tool from PATH. $jlink = Join-Path $env:ProgramFiles 'SEGGER\JLink\JLink.exe' @@ -110,52 +170,78 @@ jobs: if ((Get-FileHash -LiteralPath $hex -Algorithm SHA256).Hash -ne $expectedHash) { throw "Firmware $tag does not match the pinned SHA-256. The fixture was not erased." } - Write-Host "Flashing $tag zephyr.hex (SHA-256: $expectedHash) via J-Link $env:HIL_JLINK_SERIAL" + Write-Host "Flashing $tag zephyr.hex (SHA-256: $expectedHash)" $commands = Join-Path $dir.FullName 'flash.jlink' @('erase', "loadfile `"$hex`"", 'r', 'g', 'exit') | Set-Content -LiteralPath $commands -Encoding ascii $PSNativeCommandUseErrorActionPreference = $false + # HIL_JLINK_SERIAL keeps the configured value here: it is the serial + # SEGGER expects, leading zeros included. + # nRF52832 on a PCA10040 board (the nRF52 DK). & $jlink -USB $env:HIL_JLINK_SERIAL -Device NRF52832_XXAA -If SWD -Speed 4000 ` -AutoConnect 1 -NoGui 1 -ExitOnError 1 -CommandFile $commands 2>&1 | Tee-Object -FilePath (Join-Path $env:HIL_LOG_DIR 'flash-hil.log') exit $LASTEXITCODE - + # Per-group budgets: each one exceeds the sum of that group's declared + # per-test timeouts. timing-sweeps is the largest because its declared + # per-test bounds add up to 34 minutes: four 4-minute sweep bodies (one of + # which four generated tests reuse) plus a 6-minute seed replay. + # baseline 20 min + # connection-discovery 30 min + # gatt-operations 30 min + # notifications-indications 30 min + # mtu-resources 25 min + # timing-sweeps 45 min + # The script budget is the single wall-clock authority; a group that + # exceeds it is killed and reported as a timeout. - name: Baseline id: baseline - if: inputs.test_group == 'all' || inputs.test_group == 'baseline' + if: contains(fromJSON('["all", "baseline"]'), inputs.test_group || 'all') continue-on-error: true - run: ./run_windows_hil_group.ps1 -Group baseline + run: | + pwsh -NoProfile -NonInteractive -ExecutionPolicy Bypass -File ./run_windows_hil_group.ps1 -Group baseline -TimeoutSeconds 1200 + exit $LASTEXITCODE - name: 'Fault insertion tests: connection and discovery' id: connection-discovery - if: inputs.test_group == 'all' || inputs.test_group == 'connection-discovery' + if: contains(fromJSON('["all", "connection-discovery"]'), inputs.test_group || 'all') continue-on-error: true - run: ./run_windows_hil_group.ps1 -Group connection-discovery + run: | + pwsh -NoProfile -NonInteractive -ExecutionPolicy Bypass -File ./run_windows_hil_group.ps1 -Group connection-discovery -TimeoutSeconds 1800 + exit $LASTEXITCODE - name: 'Fault insertion tests: GATT operations' id: gatt-operations - if: inputs.test_group == 'all' || inputs.test_group == 'gatt-operations' + if: contains(fromJSON('["all", "gatt-operations"]'), inputs.test_group || 'all') continue-on-error: true - run: ./run_windows_hil_group.ps1 -Group gatt-operations + run: | + pwsh -NoProfile -NonInteractive -ExecutionPolicy Bypass -File ./run_windows_hil_group.ps1 -Group gatt-operations -TimeoutSeconds 1800 + exit $LASTEXITCODE - name: 'Fault insertion tests: notifications and indications' id: notifications-indications - if: inputs.test_group == 'all' || inputs.test_group == 'notifications-indications' + if: contains(fromJSON('["all", "notifications-indications"]'), inputs.test_group || 'all') continue-on-error: true - run: ./run_windows_hil_group.ps1 -Group notifications-indications + run: | + pwsh -NoProfile -NonInteractive -ExecutionPolicy Bypass -File ./run_windows_hil_group.ps1 -Group notifications-indications -TimeoutSeconds 1800 + exit $LASTEXITCODE - name: 'Fault insertion tests: MTU and resource pressure' id: mtu-resources - if: inputs.test_group == 'all' || inputs.test_group == 'mtu-resources' + if: contains(fromJSON('["all", "mtu-resources"]'), inputs.test_group || 'all') continue-on-error: true - run: ./run_windows_hil_group.ps1 -Group mtu-resources + run: | + pwsh -NoProfile -NonInteractive -ExecutionPolicy Bypass -File ./run_windows_hil_group.ps1 -Group mtu-resources -TimeoutSeconds 1500 + exit $LASTEXITCODE - name: 'Fault insertion tests: timing sweeps' id: timing-sweeps - if: inputs.test_group == 'all' || inputs.test_group == 'timing-sweeps' + if: contains(fromJSON('["all", "timing-sweeps"]'), inputs.test_group || 'all') continue-on-error: true - run: ./run_windows_hil_group.ps1 -Group timing-sweeps + run: | + pwsh -NoProfile -NonInteractive -ExecutionPolicy Bypass -File ./run_windows_hil_group.ps1 -Group timing-sweeps -TimeoutSeconds 2700 + exit $LASTEXITCODE - name: Fail if any selected test group failed if: > @@ -169,9 +255,9 @@ jobs: - name: Upload test logs if: always() - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: windows-hil-logs-${{ github.run_attempt }} path: ${{ runner.temp }}/windows-hil-${{ github.run_id }}-${{ github.run_attempt }}/*-hil.log - if-no-files-found: ignore + if-no-files-found: warn retention-days: 14 From b3e0783dd8679dfb24aeecc674db99330abbc24b Mon Sep 17 00:00:00 2001 From: Foti Dim Date: Thu, 19 Nov 2026 10:47:19 +0100 Subject: [PATCH 06/11] fix(hil): drain the fixture UART continuously and parse replies tolerantly The bridge only read the port while a command was in flight, so 64 KiB of Zephyr log output could fill the buffer and discard a reply, and a single ReadLine timeout threw out of the loop and marked the session failed for good. The helper now reads the port every iteration, forwards whole lines as they arrive, and treats a short read timeout as "nothing yet" instead of a failure. The Dart side keeps the 5 second budget as the only timeout authority: a miss fails that one exchange, the session stays usable, and a late reply is logged as ordinary fixture output. Teardown bounds the wait for the helper process. Reply matching no longer assumes the reply is alone on its line. The `HIL ` marker is located with lastIndexOf, and each call site validates the payload with an anchored, fully specified pattern (handshake address, 72-hex telemetry, single `0` accept token), ignoring any log text that follows it. Timeouts report the port and the last helper error. --- hil/lib/src/hil_serial_io.dart | 179 ++++++++++++++++++++++++++------- 1 file changed, 144 insertions(+), 35 deletions(-) diff --git a/hil/lib/src/hil_serial_io.dart b/hil/lib/src/hil_serial_io.dart index 2841a585..21469c02 100644 --- a/hil/lib/src/hil_serial_io.dart +++ b/hil/lib/src/hil_serial_io.dart @@ -4,35 +4,100 @@ import 'dart:io'; import 'package:flutter/foundation.dart'; -// The helper owns the COM port for one case. A private loopback connection -// carries serial lines and closes automatically if the test app exits. +// The helper owns the COM port for one case. It reads the port continuously so +// fixture output is drained even while no command is in flight: the fixture +// logs on the same UART, and an undrained buffer would otherwise overflow and +// discard a reply. Every complete line is forwarded whole, so a failed exchange +// still leaves the log intact. +// +// A private loopback connection carries command lines and closes automatically +// if the test app exits. const _bridge = r''' $ErrorActionPreference = 'Stop' $port = [IO.Ports.SerialPort]::new($env:HIL_SERIAL_PORT, 115200) $port.DtrEnable = $true $port.WriteTimeout = 2000 -$port.ReadTimeout = 4000 +# A short read timeout lets one thread do both jobs: drain the fixture and +# accept host commands, without a blocking ReadLine that a timeout would abort. +$port.ReadTimeout = 100 $port.ReadBufferSize = 65536 $client = [Net.Sockets.TcpClient]::new() try { $client.Connect('127.0.0.1', [int]$env:HIL_UART_BRIDGE_PORT) $client.NoDelay = $true $stream = $client.GetStream() - $reader = [IO.StreamReader]::new($stream) $writer = [IO.StreamWriter]::new($stream) $writer.AutoFlush = $true $port.Open() $port.DiscardInBuffer() $port.WriteLine('') - while ($true) { - $line = $reader.ReadLine() - if ($null -eq $line) { break } - $prefix = 'HIL ' + $line.Substring(0, 8) + ' ' - $port.WriteLine($line) - do { - $received = $port.ReadLine().TrimEnd([char]13) - $writer.WriteLine($received) - } until ($received.IndexOf($prefix, [StringComparison]::Ordinal) -ge 0) + $buffer = [byte[]]::new(4096) + $fromPort = [Text.StringBuilder]::new() + $fromHost = [Text.StringBuilder]::new() + $open = $true + while ($open) { + try { + $count = $port.Read($buffer, 0, $buffer.Length) + if ($count -gt 0) { + [void]$fromPort.Append([Text.Encoding]::ASCII.GetString($buffer, 0, $count)) + $text = $fromPort.ToString() + $newline = $text.IndexOf("`n") + while ($newline -ge 0) { + $writer.WriteLine($text.Substring(0, $newline).TrimEnd([char]13)) + [void]$fromPort.Remove(0, $newline + 1) + $text = $fromPort.ToString() + $newline = $text.IndexOf("`n") + } + # An unterminated run must still reach the log instead of growing + # without bound. + if ($fromPort.Length -ge 8192) { + $writer.WriteLine($fromPort.ToString()) + [void]$fromPort.Clear() + } + } + } catch { + # A read timeout means only that no fixture output arrived in this + # window: keep draining, and leave the missed reply to the host budget. + # Anything else means the port is gone; the test app owns teardown. + $problem = $_.Exception + if (-not ($problem -is [TimeoutException] -or + $problem.InnerException -is [TimeoutException])) { + [Console]::Error.WriteLine("HIL bridge serial error: $($problem.Message)") + $open = $false + } + } + if (-not $open) { break } + # Accept a command only when the host sent one, so this never blocks the + # port reader. + try { + $socket = $client.Client + if ($socket.Poll(0, [Net.Sockets.SelectMode]::SelectRead) -and + $client.Available -eq 0) { + # The test process closed the loopback connection; stop and release the + # COM port. + $open = $false + break + } + while ($client.Available -gt 0) { + $read = [Math]::Min($client.Available, $buffer.Length) + $count = $stream.Read($buffer, 0, $read) + if ($count -le 0) { $open = $false; break } + [void]$fromHost.Append([Text.Encoding]::ASCII.GetString($buffer, 0, $count)) + $text = $fromHost.ToString() + $newline = $text.IndexOf("`n") + while ($newline -ge 0) { + $line = $text.Substring(0, $newline).TrimEnd([char]13) + if ($line.Length -gt 0) { $port.WriteLine($line) } + [void]$fromHost.Remove(0, $newline + 1) + $text = $fromHost.ToString() + $newline = $text.IndexOf("`n") + } + } + } catch { + # Any socket failure means the test app is gone; stop owning the port. + [Console]::Error.WriteLine("HIL bridge socket error: $($_.Exception.Message)") + $open = $false + } } } finally { $port.Dispose() @@ -40,8 +105,19 @@ try { } '''; +/// Fixture replies are `HIL <8-hex request id> `. Zephyr logging shares +/// the console UART, so the marker is matched with [String.lastIndexOf] and the +/// payload is validated by an anchored pattern at each call site; text after a +/// validated payload is ignored. +final _readyPattern = RegExp( + r'^READY 2 ((?:[0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2})(?![0-9A-Fa-f:])', +); +final _telemetryPattern = + RegExp(r'^TELEMETRY ([0-9a-fA-F]{72})(?![0-9a-fA-F])'); +final _whitespace = RegExp(r'\s+'); + class HilSerial { - HilSerial._(this._process, this._socket, this._nextId) { + HilSerial._(this._process, this._socket, this._port, this._nextId) { _replies = _socket .cast>() .transform(const Utf8Decoder(allowMalformed: true)) @@ -53,14 +129,22 @@ class HilSerial { _stderr = _process.stderr .transform(const Utf8Decoder(allowMalformed: true)) .transform(const LineSplitter()) - .listen((line) => debugPrintSynchronously('HIL UART helper: $line')); + .listen((line) { + _lastHelperError = line; + debugPrintSynchronously('HIL UART helper: $line'); + }); unawaited(_process.exitCode.then((code) { _fail(StateError('HIL UART helper exited ($code)')); })); } + /// The only timeout authority for a single request. The bridge keeps draining + /// the port after this expires, so a late reply cannot wedge the session. + static const _replyBudget = Duration(seconds: 5); + final Process _process; final Socket _socket; + final String _port; late final StreamSubscription _replies; late final StreamSubscription _stderr; late String address; @@ -68,6 +152,7 @@ class HilSerial { String? _pendingId; Completer? _pending; Object? _failure; + String? _lastHelperError; Future _tail = Future.value(); static Future open() async { @@ -103,14 +188,13 @@ class HilSerial { await server.close(); } socket.setOption(SocketOption.tcpNoDelay, true); - final serial = - HilSerial._(process, socket, DateTime.now().microsecondsSinceEpoch); + final serial = HilSerial._( + process, socket, port, DateTime.now().microsecondsSinceEpoch); try { final reply = await serial._exchange([0xff]); - final match = RegExp(r'^READY 2 ((?:[0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2})$') - .firstMatch(reply); + final match = _readyPattern.firstMatch(reply); if (match == null) { - throw StateError('Unexpected HIL UART handshake: $reply'); + throw StateError('Unexpected HIL UART handshake: ${_describe(reply)}'); } serial.address = match[1]!; debugPrintSynchronously('HIL UART $port: fixture ${serial.address}'); @@ -123,18 +207,22 @@ class HilSerial { Future command(List bytes) { return _request(bytes).then((reply) { - if (reply != '0') { - throw StateError('Fixture rejected UART opcode ${bytes.first}: $reply'); + // The accept reply is the single token `0`; anything glued to it is not + // an accept. + if (reply.split(_whitespace).first != '0') { + throw StateError( + 'Fixture rejected UART opcode ${bytes.first}: ${_describe(reply)}'); } }); } Future readTelemetry() async { final reply = await _request([0xfe]); - final match = RegExp(r'^TELEMETRY ([0-9a-fA-F]{72})$').firstMatch(reply); + final match = _telemetryPattern.firstMatch(reply); if (match == null) { throw StateError( - 'Fixture must support UART telemetry; reflash the matching firmware. Reply: $reply'); + 'Fixture must support UART telemetry; reflash the matching firmware. ' + 'Reply: ${_describe(reply)}'); } final hex = match[1]!; return Uint8List.fromList([ @@ -160,12 +248,17 @@ class HilSerial { try { _socket.write('$id $hex\n'); await _socket.flush(); - return await reply.future.timeout(const Duration(seconds: 5)); + return await reply.future.timeout(_replyBudget); } on TimeoutException { - final error = - StateError('HIL UART timed out (request $id, opcode ${bytes.first})'); - _fail(error); - throw error; + // This request failed; the bridge and the port stay usable, so only this + // call is reported. A late reply arrives as ordinary fixture output. + throw StateError( + 'HIL UART timed out after ${_replyBudget.inSeconds} s on $_port ' + '(request $id, opcode ${bytes.first}). ' + '${_lastHelperError == null ? '' : 'Helper error: $_lastHelperError. '}' + 'Check the "HIL UART helper" output for bridge errors and confirm ' + 'nothing else holds the port.', + ); } finally { _pending = null; _pendingId = null; @@ -173,14 +266,21 @@ class HilSerial { } void _onLine(String line) { - final prefix = 'HIL $_pendingId '; final pending = _pending; - final index = line.indexOf(prefix); - if (pending != null && !pending.isCompleted && index >= 0) { - pending.complete(line.substring(index + prefix.length)); - } else { + if (pending == null || pending.isCompleted) { + debugPrintSynchronously('HIL fixture: $line'); + return; + } + final marker = 'HIL $_pendingId '; + // The marker is the last thing a shared log line is guaranteed to contain, + // and the payload follows it. Search from the end so log text before the + // reply cannot hide it. + final index = line.lastIndexOf(marker); + if (index < 0) { debugPrintSynchronously('HIL fixture: $line'); + return; } + pending.complete(line.substring(index + marker.length).trim()); } void _fail(Object error) { @@ -192,8 +292,17 @@ class HilSerial { Future close() async { _socket.destroy(); _process.kill(); - await _process.exitCode; + try { + await _process.exitCode.timeout(const Duration(seconds: 5)); + } on TimeoutException { + // A wedged helper must not stall teardown of the test app. + _process.kill(ProcessSignal.sigkill); + } await _replies.cancel(); await _stderr.cancel(); } } + +/// Keeps a diagnostic message readable when a reply carries a long log tail. +String _describe(String reply) => + reply.length <= 200 ? reply : '${reply.substring(0, 200)}...'; From f0b1a98515b319d12fb5e860328ee3256aea159d Mon Sep 17 00:00:00 2001 From: Foti Dim Date: Thu, 19 Nov 2026 10:47:26 +0100 Subject: [PATCH 07/11] ci(hil): document the group budget and execution policy in the runner script The 480 second default was smaller than the per-test budgets the timing sweeps declare. Raise the default well past that sum and document that the caller owns the budget, that CI passes it per group, and that the warm build keeps a cold CMake/MSVC build out of it. Note the explicit execution policy needed when local scripts are restricted. --- hil/run_windows_hil_group.ps1 | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/hil/run_windows_hil_group.ps1 b/hil/run_windows_hil_group.ps1 index 13b70c8f..b8fc59d6 100644 --- a/hil/run_windows_hil_group.ps1 +++ b/hil/run_windows_hil_group.ps1 @@ -1,10 +1,40 @@ +<# +.SYNOPSIS + Runs one Windows hardware-in-the-loop test group against the nRF52 fixture. + +.DESCRIPTION + Starts a worker copy of this script, enforces a wall-clock budget, and + writes the group log to $env:HIL_LOG_DIR, or next to this script when that + variable is unset. + + -TimeoutSeconds is the single authority for the group budget. The CI + workflow passes an explicit value per group; timing-sweeps needs the largest + budget because its declared per-test timeouts add up to 34 minutes. + +.PARAMETER Group + Test group to run. The worker maps every group except `baseline` to the + fault-injection suite and filters it with --plain-name. + +.PARAMETER TimeoutSeconds + Budget for the whole group, including the Flutter test build of the test + bundle. The CI workflow warms the CMake/MSVC build once before the timed + groups so this budget is not spent on a cold build. + +.PARAMETER Worker + Internal. Runs the test without the outer timeout wrapper. + +.NOTES + Invoke with an explicit execution policy when local scripts are restricted, + for example: + pwsh -NoProfile -ExecutionPolicy Bypass -File ./run_windows_hil_group.ps1 -Group baseline +#> param( [Parameter(Mandatory)] [ValidateSet('baseline', 'connection-discovery', 'gatt-operations', 'notifications-indications', 'mtu-resources', 'timing-sweeps')] [string]$Group, [ValidateRange(1, 3600)] - [int]$TimeoutSeconds = 480, + [int]$TimeoutSeconds = 1800, [switch]$Worker ) From 09c4b08eabe780bef19e64ff8bade69ac194789c Mon Sep 17 00:00:00 2001 From: Foti Dim Date: Thu, 19 Nov 2026 10:47:26 +0100 Subject: [PATCH 08/11] fix(hil): let baseline teardown survive an offline fixture Mirror the fault suite: a failure path may leave the peripheral disconnected, and an error from dispose() during teardown must not replace the real test result. --- hil/integration_test/baseline_hil_test.dart | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/hil/integration_test/baseline_hil_test.dart b/hil/integration_test/baseline_hil_test.dart index 5261a89d..829cd08a 100644 --- a/hil/integration_test/baseline_hil_test.dart +++ b/hil/integration_test/baseline_hil_test.dart @@ -28,7 +28,12 @@ void main() { UniversalBle.onValueChange = null; if (setupSucceeded) { setupSucceeded = false; - await peripheral.dispose(); + try { + await peripheral.dispose(); + } catch (_) { + // A failure scenario may deliberately leave the peripheral offline; + // the test result, not teardown, decides the outcome. + } } }); From 31322ce621eb18963e600ce2b3c4b73bd992e267 Mon Sep 17 00:00:00 2001 From: Foti Dim Date: Thu, 19 Nov 2026 10:47:34 +0100 Subject: [PATCH 09/11] docs(hil): describe the runner, port selection, and UART behaviour as built The maintainer section still described a workflow that no longer exists: the runner group is already selected, and port resolution only fails at zero matches, prefers the &MI_00 interface, and now fails instead of silently falling back to the first port. Rewrite that passage, drop the "before upstreaming, enable runs-on.group" text, and document the group budgets, the warm build, and the execution-policy requirement. Also record what the code now does elsewhere: - the host-side reply framing and its firmware-side durable fix; - that the reader drains continuously and only the per-exchange budget fails; - that Windows has no BLE control path (no HIL_CONTROL=ble escape hatch); - that the firmware is fetched from a personal account while this is a draft. --- hil/COVERAGE.md | 7 +++ hil/README.md | 152 +++++++++++++++++++++++++++++++++++------------- 2 files changed, 117 insertions(+), 42 deletions(-) diff --git a/hil/COVERAGE.md b/hil/COVERAGE.md index e1aba7c2..6406f3b8 100644 --- a/hil/COVERAGE.md +++ b/hil/COVERAGE.md @@ -71,6 +71,13 @@ For immediate disconnects, observation starts before the fixture command. Windows requires both a UART acknowledgement and an observed BLE disconnect. The legacy BLE control path can lose its acknowledgement when the link drops. +Windows therefore runs the whole suite on the wired UART control path. The BLE +control characteristic shares the link whose faults are under test, so a command +sent over it can be lost exactly when the fixture needs to act, and no +`HIL_CONTROL=ble` fallback exists: an acknowledgement would then be +indistinguishable from a fault. Android and the interactive Web runner still use +the BLE control characteristic because neither has a wired path to the fixture. + ### 2.2. Reads | Test | What it does | What it catches | diff --git a/hil/README.md b/hil/README.md index 73caf2e7..a701b460 100644 --- a/hil/README.md +++ b/hil/README.md @@ -49,6 +49,21 @@ The timing happens on the nRF52, where it is predictable. A reset clears fault plans, scheduled disconnects, bursts, values, and counters. It leaves the active connection and CCC state alone. +### UART reply framing + +The fixture logs on the same console UART that carries commands, so a reply can +share a line with log output. The host finds the `HIL ` marker from +the end of the line, validates the payload with an anchored pattern, and ignores +whatever follows it. A line without a reply only goes to the test log. The +bridge behind the port reads continuously, so buffered log output cannot +overflow and discard a pending reply, and a missed reply fails that one exchange +instead of the whole session. + +This is a host-side mitigation, not a protocol guarantee. The durable fix is +firmware-side: prefix every reply with `\r\n` so it always starts a line, or +suppress logging around replies. Only the reset/reboot acknowledgement emits +that prefix today. + ## 3. Execution boundary The automated suite currently runs on Windows. Calls start at the public Dart @@ -121,58 +136,107 @@ device permission. Click **Select device and run**, then select ### Maintainer-triggered Windows CI In Actions, open Windows HIL and fault insertion tests and click Run workflow. -The workflow runs on the protected default branch. Choose `all` (the default) or one -group: `baseline`, `connection-discovery`, `gatt-operations`, -`notifications-indications`, `mtu-resources`, or `timing-sweeps`. Existing -pairing and bonding cases are included in `connection-discovery`. - -The workflow flashes once, then runs the selected groups serially on the same -fixture. Each group has an eight-minute timeout and its own log. A failed or -timed-out group fails the job without preventing later selected groups from -running. Logs are kept separately for each run attempt. The workflow does not run on -pushes or pull requests and does not accept a separate checkout ref. +Choose `all` (the default) or one group: `baseline`, +`connection-discovery`, `gatt-operations`, `notifications-indications`, +`mtu-resources`, or `timing-sweeps`. Existing pairing and bonding cases are +included in `connection-discovery`. + +The job requires the protected default branch and the default-branch copy of +the workflow file. That is an accident guard, not a security boundary; see +[Required organization settings](#required-organization-settings) for the two +organization controls the job actually depends on. The guard names the workflow +reference literally (`Navideck/universal_ble/...@refs/heads/main`), so update +that value if the workflow is renamed, forked, or moved to another default +branch. + +The workflow regenerates the Windows app from scratch, warms the CMake/MSVC +build once outside the timed groups, flashes once, then runs the selected groups +serially on the same fixture. Each group has its own budget and log: + +| Group | Budget | +| ------------------------- | ------ | +| baseline | 20 min | +| connection-discovery | 30 min | +| gatt-operations | 30 min | +| notifications-indications | 30 min | +| mtu-resources | 25 min | +| timing-sweeps | 45 min | + +`timing-sweeps` needs the largest budget because its declared per-test timeouts +alone add up to 34 minutes: four 4-minute sweep bodies (one of which four +generated tests reuse) plus a 6-minute seed replay. Each group budget is above +the sum of that group's per-test bounds and is the single wall-clock authority; +the job timeout covers every selected group plus preparation, the warm build, and +the flash. A failed or timed-out group fails the job without preventing later +selected groups from running. Logs are kept separately for each run attempt. The +workflow does not run on pushes or pull requests and does not accept a separate +checkout ref. To run a single group locally from this directory after preparing the fixture: ```powershell -./run_windows_hil_group.ps1 -Group gatt-operations +pwsh -NoProfile -File ./run_windows_hil_group.ps1 -Group gatt-operations ``` -Before enabling it, configure: +If the machine restricts local scripts, pass the policy explicitly: +`pwsh -NoProfile -ExecutionPolicy Bypass -File ./run_windows_hil_group.ps1 +-Group gatt-operations`. The CI workflow always passes `-ExecutionPolicy +Bypass`. -- A dedicated Windows x64 self-hosted runner with the label - `universal-ble-hil`. The trial workflow selects by label so the maintainer - can test it on their own runner. Before upstreaming, enable - `runs-on.group: windows-hil` and restrict that organization runner group - to this repository and to +### Required organization settings + +The hardware runner is only safe when these are configured. The workflow file +cannot enforce either of them, and its own branch guard is an accident guard +only: `workflow_dispatch` runs the workflow file of the selected ref, so a +branch can dispatch a copy that drops the guard. + +- A dedicated Windows x64 self-hosted runner with the label `universal-ble-hil`, + in the organization runner group `windows-hil`. The workflow already selects + that group; restrict the group's workflow access to this repository and to `Navideck/universal_ble/.github/workflows/windows_hil.yml@refs/heads/main` - (adjust the owner and ref for a different deployment). Do not use a - general-purpose runner or allow pull-request workflows to use this runner. + (adjust owner, repository and ref for another deployment). Do not use a + general-purpose runner and do not allow pull-request workflows to use it. - A repository environment named `windows-hil`, restricted to the protected default branch, with maintainers as required reviewers. Users with write access can request a run; a maintainer must approve the hardware job. -- Flutter and PowerShell 7 on the runner account's PATH, Visual Studio with **Desktop - development with C++**, and an interactive Windows session with a working - Bluetooth adapter. Check `flutter doctor -v` and `flutter devices` from the - same account that runs Actions. -- A dedicated nRF52 DK (nRF52832) connected over USB with no external SWD - target attached. Install SEGGER J-Link Commander (7.92d or newer) at the - default location, `%ProgramFiles%\SEGGER\JLink\JLink.exe`. The workflow - uses this path to avoid picking up Java's `jlink.exe`. In the GitHub environment's - **Variables**, set `HIL_JLINK_SERIAL` to the onboard probe's serial number. - You can copy it from nRF Connect, including any leading zeros. - CI finds that probe's COM port through the Windows USB device tree and - stops before flashing if it can't find exactly one match. Optionally set - `HIL_DEVICE_ID` to assert the expected BLE address. - -Before running the selected groups, CI downloads `zephyr.hex` from the -firmware release pinned by `HIL_FIRMWARE_TAG` in the workflow. It checks the -file against `HIL_FIRMWARE_SHA256` before erasing, programming, verifying, and -resetting the selected DK. This wipes existing target firmware and settings. -When the Flutter harness needs new firmware, publish it under a new release -tag and update both pins in the same change as the harness. The firmware must -support the UART telemetry command (`fe`) used by the timing sweeps. The -flash log is included in the test artifact when J-Link runs. + +### Runner prerequisites + +- Flutter and PowerShell 7 on the runner account's PATH, Visual Studio with + **Desktop development with C++**, and an interactive Windows session with a + working Bluetooth adapter. Check `flutter doctor -v` and `flutter devices` + from the same account that runs Actions. +- A dedicated nRF52 DK (nRF52832 on a PCA10040 board) connected over USB with no + external SWD target attached. Install SEGGER J-Link Commander (7.92d or newer) + at the default location, `%ProgramFiles%\SEGGER\JLink\JLink.exe`. The workflow + uses this path to avoid picking up Java's `jlink.exe`. In the GitHub + environment's **Variables**, set `HIL_JLINK_SERIAL` to the onboard probe's + serial number. You can copy it from nRF Connect, including any leading zeros. + The value is masked in the run log, kept verbatim for the `jlink -USB` + selection, and compared against the PnP instance id with its leading zeros + stripped, because that id drops them. Optionally set `HIL_DEVICE_ID` to assert + the expected BLE address. + +CI resolves the COM port from the J-Link serial by walking the Windows PnP +device tree. It keeps ports whose parent chain contains the DK's +`USB\VID_1366&PID_...\` instance, fails when it finds none, prints the +ports it did find, and otherwise prefers the interface whose instance id +contains `&MI_00` (the fixture's VCOM0). It fails instead of guessing when no +VCOM0 interface exists. + +Before running the selected groups, CI downloads `zephyr.hex` from the firmware +release pinned by `HIL_FIRMWARE_TAG` in the workflow. It checks the file against +`HIL_FIRMWARE_SHA256` before erasing, programming, verifying, and resetting the +selected DK. This wipes existing target firmware and settings. When the Flutter +harness needs new firmware, publish it under a new release tag and update both +pins in the same change as the harness. The firmware must support the UART +telemetry command (`fe`) used by the timing sweeps. The flash log is included in +the test artifact when J-Link runs. + +Those releases live in the personal `usmanmehmood55/universal_ble_hil_firmware` +repository. That is acceptable while this workflow is a draft; before it is +relied on, move the firmware (or a build-from-source step) under the Navideck +organization. The run uploads the test output as a log artifact. Existing test skips still apply; the Apple-only duplicate-UUID suite is not part of Windows CI. @@ -189,7 +253,11 @@ fixture state, and notification bursts through sequence numbers. When a test fails, collect both outputs: - Flutter integration-test output and `universal_ble` debug logs; -- Fixture serial output forwarded into the test log during command exchanges. +- Fixture serial output, forwarded into the test log continuously and in whole + lines, including lines that carry no command reply. + +The host-side UART timeout is per exchange. A late reply, a missed reply, or a +burst of fixture logging does not end the session; the next command still works. If setup cannot find the fixture, confirm that it is advertising and that no other host holds its single connection slot. From 9508f30190c04b730000b7222036c0f0c5e0eac1 Mon Sep 17 00:00:00 2001 From: Foti Dim Date: Thu, 19 Nov 2026 19:15:36 +0100 Subject: [PATCH 10/11] fix(hil): give BLE connect calls a dedicated timeout above WinRT readiness retries --- hil/integration_test/fault_injection_hil_test.dart | 10 +++++----- hil/lib/src/hil_peripheral.dart | 12 +++++++++++- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/hil/integration_test/fault_injection_hil_test.dart b/hil/integration_test/fault_injection_hil_test.dart index 7d03ec19..ba9d726e 100644 --- a/hil/integration_test/fault_injection_hil_test.dart +++ b/hil/integration_test/fault_injection_hil_test.dart @@ -123,11 +123,11 @@ void main() { await Future.wait([ UniversalBle.connect( peripheral.deviceId, - timeout: HilPeripheral.operationTimeout, + timeout: HilPeripheral.connectTimeout, ), UniversalBle.connect( peripheral.deviceId, - timeout: HilPeripheral.operationTimeout, + timeout: HilPeripheral.connectTimeout, ), ]); await Future.delayed(const Duration(seconds: 1)); @@ -264,7 +264,7 @@ void main() { trace('connect begin; queue=none, no retries'); await UniversalBle.connect( peripheral.deviceId, - timeout: HilPeripheral.operationTimeout, + timeout: HilPeripheral.connectTimeout, ); trace('connect returned; immediate read begin'); final value = utf8.decode(await peripheral.read(HilUuid.read)); @@ -381,7 +381,7 @@ void main() { // failed first connection attempt. await UniversalBle.connect( discovered.deviceId, - timeout: HilPeripheral.operationTimeout, + timeout: HilPeripheral.connectTimeout, ); final services = await UniversalBle.discoverServices( @@ -1615,7 +1615,7 @@ void _unsupportedPairing(String description) => _unsupported(description, Future _connectThroughFixtureFault(HilPeripheral peripheral) async { final result = await _captureResult(UniversalBle.connect(peripheral.deviceId, - timeout: HilPeripheral.operationTimeout)); + timeout: HilPeripheral.connectTimeout)); if (result is _AsyncFailure) { expect(result.error, isA()); } diff --git a/hil/lib/src/hil_peripheral.dart b/hil/lib/src/hil_peripheral.dart index d3faaec5..c4b4b04a 100644 --- a/hil/lib/src/hil_peripheral.dart +++ b/hil/lib/src/hil_peripheral.dart @@ -136,6 +136,12 @@ final class HilPeripheral { static const maxWriteLength = 384; static const _configuredDeviceId = String.fromEnvironment('HIL_DEVICE_ID'); static const operationTimeout = Duration(seconds: 10); + // WinRT initiates BLE connections via uncached GATT service discovery, which + // can take ~8s before returning Unreachable on some adapters and then succeed + // on the plugin's readiness retry (~10s total, or longer under injected + // connect/discovery faults). Keep connect bounded without cutting off the + // plugin's own retry loop. + static const connectTimeout = Duration(seconds: 25); static const scanTimeout = Duration(seconds: 30); static BleDevice? _discoveredDevice; @@ -253,10 +259,14 @@ final class HilPeripheral { attempt++; var phase = 'connect'; try { + final remaining = deadline.difference(DateTime.now()); + if (remaining <= Duration.zero) break; + final attemptTimeout = + remaining < connectTimeout ? remaining : connectTimeout; trace?.call('attempt=$attempt connect begin'); await UniversalBle.connect( deviceId, - timeout: const Duration(seconds: 5), + timeout: attemptTimeout, ); trace?.call('attempt=$attempt connect returned'); try { From c972d959dcf9ccbf1a24eb12dd25627078980109 Mon Sep 17 00:00:00 2001 From: Foti Dim Date: Fri, 27 Nov 2026 10:07:32 +0100 Subject: [PATCH 11/11] ci(hil): use Navideck/universal_ble_hil_firmware v0.3 release --- .github/workflows/windows_hil.yml | 6 +++--- hil/README.md | 7 ++----- hil/pubspec.lock | 2 +- 3 files changed, 6 insertions(+), 9 deletions(-) diff --git a/.github/workflows/windows_hil.yml b/.github/workflows/windows_hil.yml index 553788db..e5b44a7d 100644 --- a/.github/workflows/windows_hil.yml +++ b/.github/workflows/windows_hil.yml @@ -70,8 +70,8 @@ jobs: HIL_DEVICE_ID: ${{ vars.HIL_DEVICE_ID }} HIL_JLINK_SERIAL: ${{ vars.HIL_JLINK_SERIAL }} # Update these together when the Flutter harness needs new firmware. - HIL_FIRMWARE_TAG: 'v0.2' - HIL_FIRMWARE_SHA256: '105e6b0a525fd91710633a11b8ee276ff4715979aeba07bdb2294519db5caea1' + HIL_FIRMWARE_TAG: 'v0.3' + HIL_FIRMWARE_SHA256: 'e6cc6de3d1c397a49fce132b65e807f90570aa97f9b7aa1d2e4ea7c8f3da07b3' steps: - name: Create log directory for this attempt @@ -161,7 +161,7 @@ jobs: if (-not (Test-Path -LiteralPath $jlink -PathType Leaf)) { throw "Install SEGGER J-Link Commander at $jlink on the Windows runner." } - $repo = 'usmanmehmood55/universal_ble_hil_firmware' + $repo = 'Navideck/universal_ble_hil_firmware' $tag = [Uri]::EscapeDataString($env:HIL_FIRMWARE_TAG) $expectedHash = $env:HIL_FIRMWARE_SHA256 $dir = New-Item -ItemType Directory -Path (Join-Path $env:RUNNER_TEMP "hil-firmware-$([guid]::NewGuid())") diff --git a/hil/README.md b/hil/README.md index 69ac696b..a70173b3 100644 --- a/hil/README.md +++ b/hil/README.md @@ -4,7 +4,7 @@ This is a standalone Flutter application for testing `universal_ble` against a physical nRF52 DK. It lives outside the normal package tests because it needs the DK and exclusive access to a Bluetooth adapter. -The firmware is in the [`universal_ble_hil_firmware`](https://github.com/usmanmehmood55/universal_ble_hil_firmware) +The firmware is in the [`universal_ble_hil_firmware`](https://github.com/Navideck/universal_ble_hil_firmware) repository. On Windows, fixture commands go over the DK's USB virtual COM port. The BLE operations under test still go over the radio. Android and the interactive Web runner retain the BLE control path. @@ -233,10 +233,7 @@ pins in the same change as the harness. The firmware must support the UART telemetry command (`fe`) used by the timing sweeps. The flash log is included in the test artifact when J-Link runs. -Those releases live in the personal `usmanmehmood55/universal_ble_hil_firmware` -repository. That is acceptable while this workflow is a draft; before it is -relied on, move the firmware (or a build-from-source step) under the Navideck -organization. +Those releases live in the `Navideck/universal_ble_hil_firmware` repository. The run uploads the test output as a log artifact. Existing test skips still apply; the Apple-only duplicate-UUID suite is not part of Windows CI. diff --git a/hil/pubspec.lock b/hil/pubspec.lock index 7c82167b..1275de3e 100644 --- a/hil/pubspec.lock +++ b/hil/pubspec.lock @@ -338,7 +338,7 @@ packages: path: ".." relative: true source: path - version: "3.3.0" + version: "3.4.1" vector_math: dependency: transitive description: