diff --git a/.github/workflows/windows_hil.yml b/.github/workflows/windows_hil.yml new file mode 100644 index 00000000..e5b44a7d --- /dev/null +++ b/.github/workflows/windows_hil.yml @@ -0,0 +1,263 @@ +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: + 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: + # 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] + # 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 + 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.3' + HIL_FIRMWARE_SHA256: 'e6cc6de3d1c397a49fce132b65e807f90570aa97f9b7aa1d2e4ea7c8f3da07b3' + + 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 + + # 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 + + - 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.' + } + # 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 } + $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) { [PSCustomObject]@{ Port = $port; Vcom0 = $isVcom0 } } + break + } + $id = (Get-PnpDeviceProperty -InstanceId $id -KeyName DEVPKEY_Device_Parent -ErrorAction SilentlyContinue).Data + } + }) + if ($ports.Count -eq 0) { + 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) { + 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 UART: $selectedPort (from: $($ports.Port -join ', '))" + "HIL_SERIAL_PORT=$selectedPort" >> $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: 10 + 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 = '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())") + $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)" + $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: contains(fromJSON('["all", "baseline"]'), inputs.test_group || 'all') + continue-on-error: true + 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: contains(fromJSON('["all", "connection-discovery"]'), inputs.test_group || 'all') + continue-on-error: true + 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: contains(fromJSON('["all", "gatt-operations"]'), inputs.test_group || 'all') + continue-on-error: true + 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: contains(fromJSON('["all", "notifications-indications"]'), inputs.test_group || 'all') + continue-on-error: true + 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: contains(fromJSON('["all", "mtu-resources"]'), inputs.test_group || 'all') + continue-on-error: true + 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: contains(fromJSON('["all", "timing-sweeps"]'), inputs.test_group || 'all') + continue-on-error: true + 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: > + 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@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: warn + retention-days: 14 diff --git a/hil/COVERAGE.md b/hil/COVERAGE.md index 0b7e31d3..2f6f210f 100644 --- a/hil/COVERAGE.md +++ b/hil/COVERAGE.md @@ -69,13 +69,20 @@ 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. + +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 diff --git a/hil/README.md b/hil/README.md index 1ed11af8..a70173b3 100644 --- a/hil/README.md +++ b/hil/README.md @@ -4,8 +4,10 @@ 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) -repository. Test commands go over BLE. USB serial is only used for Zephyr logs. +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. ## 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. @@ -46,14 +49,30 @@ 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 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 +95,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 +133,111 @@ 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. +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 +pwsh -NoProfile -File ./run_windows_hil_group.ps1 -Group gatt-operations +``` + +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`. + +### 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 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. + +### 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 `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. + ## 5. Isolation and diagnosis Each Windows test connects, resets the fixture, runs one case, and disconnects. @@ -121,7 +250,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; -- Zephyr serial logs from the nRF52 DK. +- 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. diff --git a/hil/integration_test/baseline_hil_test.dart b/hil/integration_test/baseline_hil_test.dart index 73b94403..064aae81 100644 --- a/hil/integration_test/baseline_hil_test.dart +++ b/hil/integration_test/baseline_hil_test.dart @@ -28,23 +28,68 @@ void main() { UniversalBle.onValueChange = null; if (setupSucceeded) { setupSucceeded = false; - await peripheral.close(); + try { + await peripheral.dispose(); + } catch (_) { + // A failure scenario may deliberately leave the peripheral offline; + // the test result, not teardown, decides the outcome. + } } }); 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 +100,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..ba9d726e 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', ); @@ -114,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)); @@ -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.connectTimeout, + ); + 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,14 +374,14 @@ 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 // failed first connection attempt. await UniversalBle.connect( discovered.deviceId, - timeout: HilPeripheral.operationTimeout, + timeout: HilPeripheral.connectTimeout, ); final services = await UniversalBle.discoverServices( @@ -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); @@ -1556,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()); } @@ -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 7c4cd54b..a9863bdc 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'; @@ -128,48 +130,92 @@ final class HilState { } final class HilPeripheral { - HilPeripheral._(this.device); + HilPeripheral._(this.device, this._serial); static const deviceName = 'UniversalBLE-HIL'; static const contractRevision = 2; 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; 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); } @@ -195,29 +241,59 @@ 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 { + 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 { - 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)); @@ -255,6 +331,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); @@ -274,6 +351,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..21469c02 --- /dev/null +++ b/hil/lib/src/hil_serial_io.dart @@ -0,0 +1,308 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter/foundation.dart'; + +// 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 +# 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() + $writer = [IO.StreamWriter]::new($stream) + $writer.AutoFlush = $true + $port.Open() + $port.DiscardInBuffer() + $port.WriteLine('') + $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() + $client.Dispose() +} +'''; + +/// 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._port, 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) { + _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; + int _nextId; + String? _pendingId; + Completer? _pending; + Object? _failure; + String? _lastHelperError; + 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, port, DateTime.now().microsecondsSinceEpoch); + try { + final reply = await serial._exchange([0xff]); + final match = _readyPattern.firstMatch(reply); + if (match == null) { + throw StateError('Unexpected HIL UART handshake: ${_describe(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) { + // 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 = _telemetryPattern.firstMatch(reply); + if (match == null) { + throw StateError( + 'Fixture must support UART telemetry; reflash the matching firmware. ' + 'Reply: ${_describe(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(_replyBudget); + } on TimeoutException { + // 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; + } + } + + void _onLine(String line) { + final pending = _pending; + 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) { + _failure ??= error; + final pending = _pending; + if (pending != null && !pending.isCompleted) pending.completeError(error); + } + + Future close() async { + _socket.destroy(); + _process.kill(); + 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)}...'; 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/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: diff --git a/hil/run_windows_hil_group.ps1 b/hil/run_windows_hil_group.ps1 new file mode 100644 index 00000000..b8fc59d6 --- /dev/null +++ b/hil/run_windows_hil_group.ps1 @@ -0,0 +1,86 @@ +<# +.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 = 1800, + [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