diff --git a/README.md b/README.md index 22013d1..a917084 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ clearly-labelled add-on. > no Apple logo.

- PodBridge tray menu on Windows: Status Connected, Battery L and R 100%, microphone-mode and noise-control submenus, Pair / Reconnect, Export diagnostics, and About PodBridge + PodBridge tray menu on Windows: Status Connected, Battery L and R 100%, microphone-mode and noise-control submenus, Bluetooth connection entries, Export diagnostics, and About PodBridge
PodBridge lives in the system tray — battery, audio status, microphone & noise-control modes, pairing, and diagnostics, one right-click away.

@@ -33,10 +33,12 @@ single-file `.exe`** — no installer, no admin rights, nothing else to set up. not a sign of a problem. Click **More info → Run anyway**. **Set up in under 2 minutes:** launch PodBridge (a tray icon appears — no window, -no UAC prompt) → right-click the icon and choose **`Pair / Reconnect`** to add -your AirPods in Windows Bluetooth settings → once they connect, the tray +no UAC prompt) → right-click the icon and choose **`Open Bluetooth settings`** to +pair your AirPods in Windows → once they connect, the tray **`Status:`** line reads **`Connected`** and the **`Battery:`** line shows -left/right/case charge. That's it: **paired, playing, battery visible.** +left/right/case charge. That's it: **paired, playing, battery visible.** Later, +reconnect already-paired AirPods in one click with **`Connect AirPods`** (no +driver, no admin). Settings and logs live under `%LOCALAPPDATA%\PodBridge`. To uninstall: quit PodBridge (tray → `Exit`) and delete the exe and the `%LOCALAPPDATA%\PodBridge` diff --git a/docs/architecture-diagrams.md b/docs/architecture-diagrams.md index 6bd1b0a..9763847 100644 --- a/docs/architecture-diagrams.md +++ b/docs/architecture-diagrams.md @@ -20,12 +20,12 @@ flowchart TB end subgraph Core["PodBridge.Core — platform-neutral domain (no OS, no P/Invoke)"] - Domain["Domain logic: AapProtocol · ContinuityParser · DeviceStateTracker · AutoPlayPauseEngine · MicPolicyEngine · AudioGuidanceEngine · ModelRegistry · CapabilityProvider · Diagnostics · NoiseControlController · GestureSettingsController / GestureRepushController"] + Domain["Domain logic: AapProtocol · ContinuityParser · DeviceStateTracker · AutoPlayPauseEngine · MicPolicyEngine · AudioGuidanceEngine · BluetoothAudioLinkController · ModelRegistry · CapabilityProvider · Diagnostics · NoiseControlController · GestureSettingsController / GestureRepushController"] Ifaces["OS-boundary interfaces (abstractions)"] end subgraph Win["PodBridge.Windows — OS adapters (WinRT + P/Invoke, no UI)"] - Adapters["WinRtBleScanner · WinRtConnectionMonitor · WinRtBluetoothRadioSource · WindowsMediaController · WindowsAudioStateReader · WindowsAudioPolicy · WindowsAudioSessionMonitor · RunKeyStartupToggle · DiagnosticsExporter · RollingFileLoggerProvider"] + Adapters["WinRtBleScanner · WinRtConnectionMonitor · WindowsBluetoothAudioConnector · WinRtBluetoothRadioSource · WindowsMediaController · WindowsAudioStateReader · WindowsAudioPolicy · WindowsAudioSessionMonitor · RunKeyStartupToggle · DiagnosticsExporter · RollingFileLoggerProvider"] T2Adapters["Tier 2: DriverAapTransport · AdvancedTierInstaller"] end @@ -65,6 +65,7 @@ flowchart LR I9["IDiagnosticsExporter"] I10["IAapTransport — Tier 2"] I11["IAdvancedTierInstaller — Tier 2"] + I12["IBluetoothAudioConnector"] end subgraph WinImpl["PodBridge.Windows — implementation"] A1["WinRtBleScanner"] @@ -78,6 +79,7 @@ flowchart LR A9["DiagnosticsExporter"] A10["DriverAapTransport"] A11["AdvancedTierInstaller"] + A12["WindowsBluetoothAudioConnector"] end I1 --- A1 I2 --- A2 @@ -90,6 +92,7 @@ flowchart LR I9 --- A9 I10 --- A10 I11 --- A11 + I12 --- A12 ``` ## 3. Key flows @@ -136,7 +139,32 @@ sequenceDiagram Eng->>Pol: restore prior routing ``` -### 3.3 Noise-control switching (Tier 2, opt-in driver) +### 3.3 One-click connect / disconnect (Tier 1, driver-free, no admin) + +```mermaid +sequenceDiagram + autonumber + participant UI as TrayConnectController (App) + participant Link as BluetoothAudioLinkController (Core) + participant Con as WindowsBluetoothAudioConnector (Windows) + participant Drv as Windows Bluetooth audio filters (A2DP + hands-free) + + UI->>Link: Connect AirPods (off the UI thread) + Link->>Con: GetLinkState() + alt no paired AirPods / already connected + Con-->>Link: NotFound / Connected + else paired, disconnected + Link->>Con: SendRequest(Connect) + Con->>Drv: one-shot reconnect (KSPROPSETID_BtAudio) to every filter + loop poll every 500 ms, re-send every 10 s, up to 45 s + Link->>Con: GetLinkState() + end + end + Link-->>UI: outcome + UI->>UI: honest notification; on failure open Bluetooth settings +``` + +### 3.4 Noise-control switching (Tier 2, opt-in driver) ```mermaid sequenceDiagram diff --git a/docs/architecture.md b/docs/architecture.md index bc861fd..c895bc9 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -12,9 +12,9 @@ | Component | Responsibility | | --------- | -------------- | -| `PodBridge.Core` | Platform-neutral domain: the clean-room AAP module (`AapProtocol` frame builders + notification parsers) covering **noise-control** (`BuildSetNoiseControl`/`TryParseNoiseControlNotification` + `NoiseControlController` optimistic-set/echo-confirm/timeout-revert logic over `IAapTransport`, with `DeviceState.NoiseControl`/`NoiseControlAvailable`, `NoiseControlMode`, and the `NoiseControlSupport` Adaptive model gate) and **press-and-hold gesture remap** (`BuildSetPressAndHoldGesture`/`TryParsePressAndHoldGestureNotification` for the per-bud ClickHoldMode `0x16` frame — right=`data1`, left=`data2` — plus the `GestureAction` enum (Noise Control `0x01`/Siri `0x05` only; single/double presses are Apple-fixed and unexposed) and the per-bud `GestureConfiguration` model, the `GestureSupport` model gate (press-and-hold offered on the AirPods Pro 2 reference model only; broad matrix is Phase 8), the `GestureRepushController` re-push-on-reconnect policy, and the `GestureSettingsController`/`GestureAvailability` settings decision+apply logic that resolves the driver-absent/model-unsupported/available states and persists via `IGestureConfigStore` + writes via the re-push policy), Apple-Continuity BLE parser (`ContinuityParser` → `BleAdvertisement` in, `DeviceState` battery/charging/in-ear out), the Phase-8 model registry (`IModelRegistry`/`ModelRegistry`, backed by the clean-room `AppleModelIdentifier` per-model shape mapper) resolving an identified `AirPodsModel` to its `AirPodsModelInfo` shape (dual-bud vs single unit, battery-reporting case, in-ear vs head detection) for the vision's six supported models, with any other model — including Phase-2 `AirPodsModel` values outside that six-model scope — degrading to the labelled generic "Unknown AirPods" `AirPodsModelInfo` fallback (issue #52), the Phase-8 capability provider (`Capabilities/ICapabilityProvider`/`CapabilityProvider`, backed by the static `CapabilityMatrix` keyed by **(model, firmware-major)**) — the single Core authority that decides which features are offered: **Tier-1** features (`Tier1Feature`) gate on the BLE-derived model shape only (never firmware, never driver — e.g. AirPods Max hides case battery), while **Tier-2** features (`Tier2Feature` noise-control/gesture-remap/conversation-awareness) gate on **both** driver presence (via `IAapTransport.IsAvailable`) **and** the (model, firmware-major) capability, returning an honest `CapabilityDecision` (reason "requires the optional driver" / "not supported on this model" / "not supported on this firmware" / "supported"); the firmware-major axis is a documented no-op today (no host-requestable read exists — `0x001D` "Device Information" is a fragile accessory-initiated push — so an unreadable firmware-major falls back to the model-level Tier-2 capability and a Phase-6/7-supported model stays on, no regression; future firmware-varying refinements are `FirmwareRefinement` data edits, of which the shipped set is empty — docs/research/firmware-capabilities.md, issue #53), the connection-gated telemetry pipeline (`IDeviceStateProvider`/`DeviceStateTracker`), the auto play/pause engine (`AutoPlayPauseEngine`), the read-only audio-state surface (`IAudioStateReader` → `AudioState`(`CodecKind`, `MicMode`) + `AudioGuidanceEngine`), mic-policy engine, the branding/disclaimer/license constants (`Branding/ProductInfo` — coined name, "for AirPods" descriptor, not-affiliated disclaimer, Apache-2.0 id, honest audio note, docs link; guarded by the Tier-1 `ProductInfoTests`), the opt-in auto-start toggle contract (`Startup/IStartupToggle` → `StartupToggleState`; default OFF, guarded by the Tier-1 `StartupToggleTests`), the Phase-8 local **diagnostics** model (`Diagnostics/DiagnosticsSnapshot` — model, firmware-major, negotiated codec, tier, driver presence + honest `DriverSigningStatus`, the `ICapabilityProvider`-derived `CapabilityMatrixEntry` matrix, and address-masked `BleParseResult` history; assembled deterministically by `DiagnosticsSnapshotBuilder`/`IDiagnosticsSnapshotFactory` from the existing Core seams — the first real consumer of `ICapabilityProvider` — rendered to plain text by `DiagnosticsSnapshotFormatter`, recorded by the `IBleParseHistory`/`BleParseHistoryRecorder` masking recorder; no secret, no full Bluetooth address — issue #54), and the OS-boundary interfaces (`IBleScanner`, `IConnectionMonitor`, `IMediaController`, `IAudioStateReader`, `IAudioPolicy`, `IAudioSessionMonitor`, `IBluetoothRadioSource`, `IStartupToggle`, `IAapTransport`, the local diagnostics-writer boundary `IDiagnosticsExporter` → `DiagnosticsExportResult` (local file only, no network), and the advanced-tier opt-in install boundary `IAdvancedTierInstaller` → `AdvancedTierActionResult` plus the honest opt-in copy `AdvancedTier/AdvancedTierInfo`, guarded by `AdvancedTierInfoTests`). No OS/UI/P-Invoke. | -| `PodBridge.Windows` | Windows adapters implementing the Core interfaces: `WinRtBleScanner` (BLE advertisement watcher), `WinRtConnectionMonitor` (WinRT paired/connected detection), `WinRtBluetoothRadioSource` (`IBluetoothRadioSource` over `Windows.Devices.Radios`; reports the Bluetooth-radio power state so `BleScannerSupervisor` restarts the watcher on a radio toggle, degrading to "assume on" if radio enumeration faults), `WindowsMediaController` (GSMTC media-session pause/resume), `WindowsAudioStateReader` (read-only Core Audio codec + mic-mode read), `WindowsAudioPolicy` (NAudio + `IPolicyConfig`), `WindowsAudioSessionMonitor` (`IAudioSessionManager2`), `RunKeyStartupToggle` (opt-in auto-start over the per-user `HKCU\...\Run` key, default OFF, self-healing a stale path on launch and honouring a Task-Manager user-disable via `StartupApproved\Run`), the Phase-8 diagnostics/logging adapters `DiagnosticsExporter` (`IDiagnosticsExporter`: renders a `DiagnosticsSnapshot` and writes one timestamped text file under `%LOCALAPPDATA%\PodBridge\diagnostics`; local filesystem only, structurally proven to reference no network-capable type) and `RollingFileLoggerProvider` (a minimal custom `ILoggerProvider`/`ILogger` on `Microsoft.Extensions.Logging.Abstractions` — the app's **only** log sink, a rolling, size/age-capped local file under `%LOCALAPPDATA%\PodBridge\logs` (~10 MB / 7 days) whose runtime-mutable `MinLevel` backs the tray Debug toggle; no network sink), and — Tier 2 only — `DriverAapTransport` (talks to the KMDF driver) and `AdvancedTierInstaller` (implements `IAdvancedTierInstaller`: locates the shipped-separately `install-advanced-tier.ps1` and launches it **elevated** via ShellExecute `runas` on explicit user action — driver `pnputil` install + self-signed test-cert trust in one step; never elevates the app, never runs `bcdedit`). | -| `PodBridge.App` | WPF tray-first UI, view models, notifications, settings, and the composition root (DI, background host). The tray context menu is driven by per-feature controllers (`TrayStatusController`, `TrayBatteryController`, `TrayAudioController`, `TrayMicController`, the Phase-8 `TrayDiagnosticsController` for the "Export diagnostics" action — build snapshot → write local file → copy the same text to the WPF clipboard (the clipboard copy lives here, keeping the Windows adapter UI-framework-free) → honest notification — and the "Debug logging" toggle that flips the local `RollingFileLoggerProvider.MinLevel` at runtime, and — Tier 2, opt-in — `TrayNoiseControlController` for the "Noise control" submenu with the driver-absent honesty UX + Adaptive model gate). The composition root replaces the generic host's default log providers with the single local `RollingFileLoggerProvider` sink (no console, no network sink). Includes the **About window** (`AboutWindow` + `AboutViewModel`) — the app's first non-tray window, opened from the tray "About" entry, which renders the Core `ProductInfo` branding/disclaimer/license/audio constants plus the running app version and the shipped `THIRD-PARTY-NOTICES.md`, and carries the **opt-in auto-start-at-login toggle** (default OFF) that reads/sets `IStartupToggle`. Adds the **gesture-controls window** (`GestureSettingsWindow`, opened from the tray "Gesture controls…" entry) — the Tier-2, opt-in press-and-hold remap surface: it binds the Core `GestureSettingsController` + `IDeviceStateProvider` to per-bud action pickers, and when the driver is absent (Tier-1 default) replaces them with the **reused** Phase-6 driver-absent notice (`TrayNoiseControlController.UnavailableText`, no new signed-driver claim) plus the same explicit "Enable advanced tier" flow — never silently broken. | +| `PodBridge.Core` | Platform-neutral domain: the clean-room AAP module (`AapProtocol` frame builders + notification parsers) covering **noise-control** (`BuildSetNoiseControl`/`TryParseNoiseControlNotification` + `NoiseControlController` optimistic-set/echo-confirm/timeout-revert logic over `IAapTransport`, with `DeviceState.NoiseControl`/`NoiseControlAvailable`, `NoiseControlMode`, and the `NoiseControlSupport` Adaptive model gate) and **press-and-hold gesture remap** (`BuildSetPressAndHoldGesture`/`TryParsePressAndHoldGestureNotification` for the per-bud ClickHoldMode `0x16` frame — right=`data1`, left=`data2` — plus the `GestureAction` enum (Noise Control `0x01`/Siri `0x05` only; single/double presses are Apple-fixed and unexposed) and the per-bud `GestureConfiguration` model, the `GestureSupport` model gate (press-and-hold offered on the AirPods Pro 2 reference model only; broad matrix is Phase 8), the `GestureRepushController` re-push-on-reconnect policy, and the `GestureSettingsController`/`GestureAvailability` settings decision+apply logic that resolves the driver-absent/model-unsupported/available states and persists via `IGestureConfigStore` + writes via the re-push policy), Apple-Continuity BLE parser (`ContinuityParser` → `BleAdvertisement` in, `DeviceState` battery/charging/in-ear out), the Phase-8 model registry (`IModelRegistry`/`ModelRegistry`, backed by the clean-room `AppleModelIdentifier` per-model shape mapper) resolving an identified `AirPodsModel` to its `AirPodsModelInfo` shape (dual-bud vs single unit, battery-reporting case, in-ear vs head detection) for the vision's six supported models, with any other model — including Phase-2 `AirPodsModel` values outside that six-model scope — degrading to the labelled generic "Unknown AirPods" `AirPodsModelInfo` fallback (issue #52), the Phase-8 capability provider (`Capabilities/ICapabilityProvider`/`CapabilityProvider`, backed by the static `CapabilityMatrix` keyed by **(model, firmware-major)**) — the single Core authority that decides which features are offered: **Tier-1** features (`Tier1Feature`) gate on the BLE-derived model shape only (never firmware, never driver — e.g. AirPods Max hides case battery), while **Tier-2** features (`Tier2Feature` noise-control/gesture-remap/conversation-awareness) gate on **both** driver presence (via `IAapTransport.IsAvailable`) **and** the (model, firmware-major) capability, returning an honest `CapabilityDecision` (reason "requires the optional driver" / "not supported on this model" / "not supported on this firmware" / "supported"); the firmware-major axis is a documented no-op today (no host-requestable read exists — `0x001D` "Device Information" is a fragile accessory-initiated push — so an unreadable firmware-major falls back to the model-level Tier-2 capability and a Phase-6/7-supported model stays on, no regression; future firmware-varying refinements are `FirmwareRefinement` data edits, of which the shipped set is empty — docs/research/firmware-capabilities.md, issue #53), the connection-gated telemetry pipeline (`IDeviceStateProvider`/`DeviceStateTracker`), the one-click connect policy (`Bluetooth/BluetoothAudioLinkController` — send / confirm-by-state / re-send / time-out over `IBluetoothAudioConnector`, plus the honest tray copy `BluetoothAudioLinkText`), the auto play/pause engine (`AutoPlayPauseEngine`), the read-only audio-state surface (`IAudioStateReader` → `AudioState`(`CodecKind`, `MicMode`) + `AudioGuidanceEngine`), mic-policy engine, the branding/disclaimer/license constants (`Branding/ProductInfo` — coined name, "for AirPods" descriptor, not-affiliated disclaimer, Apache-2.0 id, honest audio note, docs link; guarded by the Tier-1 `ProductInfoTests`), the opt-in auto-start toggle contract (`Startup/IStartupToggle` → `StartupToggleState`; default OFF, guarded by the Tier-1 `StartupToggleTests`), the Phase-8 local **diagnostics** model (`Diagnostics/DiagnosticsSnapshot` — model, firmware-major, negotiated codec, tier, driver presence + honest `DriverSigningStatus`, the `ICapabilityProvider`-derived `CapabilityMatrixEntry` matrix, and address-masked `BleParseResult` history; assembled deterministically by `DiagnosticsSnapshotBuilder`/`IDiagnosticsSnapshotFactory` from the existing Core seams — the first real consumer of `ICapabilityProvider` — rendered to plain text by `DiagnosticsSnapshotFormatter`, recorded by the `IBleParseHistory`/`BleParseHistoryRecorder` masking recorder; no secret, no full Bluetooth address — issue #54), and the OS-boundary interfaces (`IBleScanner`, `IConnectionMonitor`, `IBluetoothAudioConnector`, `IMediaController`, `IAudioStateReader`, `IAudioPolicy`, `IAudioSessionMonitor`, `IBluetoothRadioSource`, `IStartupToggle`, `IAapTransport`, the local diagnostics-writer boundary `IDiagnosticsExporter` → `DiagnosticsExportResult` (local file only, no network), and the advanced-tier opt-in install boundary `IAdvancedTierInstaller` → `AdvancedTierActionResult` plus the honest opt-in copy `AdvancedTier/AdvancedTierInfo`, guarded by `AdvancedTierInfoTests`). No OS/UI/P-Invoke. | +| `PodBridge.Windows` | Windows adapters implementing the Core interfaces: `WinRtBleScanner` (BLE advertisement watcher), `WinRtConnectionMonitor` (WinRT paired/connected detection), `WindowsBluetoothAudioConnector` (`IBluetoothAudioConnector` over Core Audio device topology + `IKsControl`: sends the Bluetooth-audio one-shot reconnect/disconnect request — the one the Sound control panel's **Connect** uses — to the paired AirPods' A2DP and hands-free filters and reads their endpoint state; driver-free, no admin), `WinRtBluetoothRadioSource` (`IBluetoothRadioSource` over `Windows.Devices.Radios`; reports the Bluetooth-radio power state so `BleScannerSupervisor` restarts the watcher on a radio toggle, degrading to "assume on" if radio enumeration faults), `WindowsMediaController` (GSMTC media-session pause/resume), `WindowsAudioStateReader` (read-only Core Audio codec + mic-mode read), `WindowsAudioPolicy` (NAudio + `IPolicyConfig`), `WindowsAudioSessionMonitor` (`IAudioSessionManager2`), `RunKeyStartupToggle` (opt-in auto-start over the per-user `HKCU\...\Run` key, default OFF, self-healing a stale path on launch and honouring a Task-Manager user-disable via `StartupApproved\Run`), the Phase-8 diagnostics/logging adapters `DiagnosticsExporter` (`IDiagnosticsExporter`: renders a `DiagnosticsSnapshot` and writes one timestamped text file under `%LOCALAPPDATA%\PodBridge\diagnostics`; local filesystem only, structurally proven to reference no network-capable type) and `RollingFileLoggerProvider` (a minimal custom `ILoggerProvider`/`ILogger` on `Microsoft.Extensions.Logging.Abstractions` — the app's **only** log sink, a rolling, size/age-capped local file under `%LOCALAPPDATA%\PodBridge\logs` (~10 MB / 7 days) whose runtime-mutable `MinLevel` backs the tray Debug toggle; no network sink), and — Tier 2 only — `DriverAapTransport` (talks to the KMDF driver) and `AdvancedTierInstaller` (implements `IAdvancedTierInstaller`: locates the shipped-separately `install-advanced-tier.ps1` and launches it **elevated** via ShellExecute `runas` on explicit user action — driver `pnputil` install + self-signed test-cert trust in one step; never elevates the app, never runs `bcdedit`). | +| `PodBridge.App` | WPF tray-first UI, view models, notifications, settings, and the composition root (DI, background host). The tray context menu is driven by per-feature controllers (`TrayStatusController`, `TrayConnectController` for the one-click "Connect AirPods" / "Disconnect AirPods" items, `TrayBatteryController`, `TrayAudioController`, `TrayMicController`, the Phase-8 `TrayDiagnosticsController` for the "Export diagnostics" action — build snapshot → write local file → copy the same text to the WPF clipboard (the clipboard copy lives here, keeping the Windows adapter UI-framework-free) → honest notification — and the "Debug logging" toggle that flips the local `RollingFileLoggerProvider.MinLevel` at runtime, and — Tier 2, opt-in — `TrayNoiseControlController` for the "Noise control" submenu with the driver-absent honesty UX + Adaptive model gate). The composition root replaces the generic host's default log providers with the single local `RollingFileLoggerProvider` sink (no console, no network sink). Includes the **About window** (`AboutWindow` + `AboutViewModel`) — the app's first non-tray window, opened from the tray "About" entry, which renders the Core `ProductInfo` branding/disclaimer/license/audio constants plus the running app version and the shipped `THIRD-PARTY-NOTICES.md`, and carries the **opt-in auto-start-at-login toggle** (default OFF) that reads/sets `IStartupToggle`. Adds the **gesture-controls window** (`GestureSettingsWindow`, opened from the tray "Gesture controls…" entry) — the Tier-2, opt-in press-and-hold remap surface: it binds the Core `GestureSettingsController` + `IDeviceStateProvider` to per-bud action pickers, and when the driver is absent (Tier-1 default) replaces them with the **reused** Phase-6 driver-absent notice (`TrayNoiseControlController.UnavailableText`, no new signed-driver claim) plus the same explicit "Enable advanced tier" flow — never silently broken. | | `driver/PodBridgeAAP` | Optional C / KMDF L2CAP-bridge driver exposing a user-mode device interface for AAP over PSM 0x1001. Ships **separately** (never bundled with the app exe, its own INF + `pnputil` install): `build-testsign.ps1` builds + self-signs it, and `install-advanced-tier.ps1` is the elevated opt-in install/uninstall (`pnputil` + importing/removing the self-signed test cert in Trusted Root CA / Trusted Publishers). It never enables test-signing (`bcdedit`) — that stays a documented manual user step. | | `tests/PodBridge.Core.Tests` | xUnit tests exercising Core via fakes — no physical device required. | | `tests/PodBridge.Windows.Tests` | xUnit tests for the Windows adapters that have a device-independent seam — currently `DriverAapTransport` with a fake at the Win32 driver seam (connect/send/receive-loop/graceful-absence); no driver or hardware required. | @@ -139,6 +139,23 @@ (`Connected` / `Disconnected` / `NoDevice` / `BluetoothUnavailable`) behind `IConnectionMonitor` → `App` renders the tray status and pairing guidance. No Bluetooth radio → `BluetoothUnavailable`, never a crash. +6. **One-click connect / disconnect (Tier 1, driver-free, no admin):** tray + "Connect AirPods" / "Disconnect AirPods" → `TrayConnectController` (`App`) runs + Core's `BluetoothAudioLinkController` off the UI thread → + `WindowsBluetoothAudioConnector` (`IBluetoothAudioConnector`) enumerates the + paired AirPods' render + capture endpoints (AirPods-only name match — Beats are + excluded; active or unplugged; an endpoint that fails mid-enumeration is skipped), + follows each endpoint's device-topology connectors to its Bluetooth audio filters (A2DP and + hands-free), and sends the documented one-shot reconnect/disconnect property + (`KSPROPSETID_BtAudio`, Windows SDK `ksmedia.h`) to every filter — the same request + the Sound control panel's **Connect** sends. A successful send only means the driver + accepted the request, so the controller confirms by polling the endpoint state + (500 ms), re-sends every 10 s (right after a disconnect the first reconnect is often + ignored while the old link winds down) and gives up after 45 s. The outcome becomes + an honest notification (`BluetoothAudioLinkText`); on any failure (no paired AirPods, + no connect control, declined, timed out) `App` opens Windows Bluetooth settings as + the fallback. With several AirPods paired, all receive the request and whichever + pair is in range connects. `IConnectionMonitor` still drives the status line. ## Where new code goes diff --git a/docs/user/README.md b/docs/user/README.md index 89065e0..41e6e7f 100644 --- a/docs/user/README.md +++ b/docs/user/README.md @@ -123,11 +123,12 @@ PodBridge's control. (system tray). There is no main window and **no UAC prompt** — PodBridge lives in the tray. Hover for a tooltip like `PodBridge — … · …`. 2. **Pair your AirPods** if they are not paired yet. Right-click the tray icon and - choose **`Pair / Reconnect`** (this opens Windows **Bluetooth & devices** + choose **`Open Bluetooth settings`** (this opens Windows **Bluetooth & devices** settings). Put the AirPods in pairing mode — lid open, then press and hold the case button until the light blinks white — and add them from **Add device → Bluetooth**. On first run PodBridge also shows a one-time **"Pair your AirPods"** - notification if none are paired. + notification if none are paired. Once paired, later reconnects are one click: + **`Connect AirPods`** (see [the tray menu](#the-tray-menu)). 3. **Confirm battery is visible.** Once the AirPods connect, right-click the tray icon: the **`Status:`** line reads **`Connected`** and the **`Battery:`** line shows the left bud, right bud, and case charge, for example @@ -156,8 +157,24 @@ Right-click the tray icon. The menu (top to bottom): its driver is installed the modes are disabled with an honest explanation and an **`Enable advanced tier…`** entry. - **`Refresh audio status`** — re-reads the codec and mic lines on demand. -- **`Pair / Reconnect`** — opens Windows Bluetooth settings to add or reconnect AirPods. -- **`Open Bluetooth settings`** — opens Windows Bluetooth settings. +- **`Connect AirPods`** — connects your **already-paired** AirPods in one click, + the same request Windows' Sound control panel sends for **Connect** (no driver, + no admin). Take the AirPods out of the case (or open the lid) near the PC first. + The item shows **`Connecting…`** while PodBridge waits for the link to come up — + usually a few seconds; right after a disconnect it can take longer, so PodBridge + repeats the request and waits up to about 45 seconds. If no paired AirPods are + found, Windows declines, or they don't connect in time, PodBridge says so and + opens Windows Bluetooth settings instead. Disabled while the AirPods are + `Connected`. PodBridge recognises AirPods by name (the name must contain + "AirPods"), so a paired **Beats** device is never connected or disconnected by + these items. If several AirPods are paired to this PC, the request goes to all of + them and whichever pair is nearby connects. +- **`Disconnect AirPods`** — disconnects the AirPods from this PC (shown as + **`Disconnecting…`** while it waits). They **stay paired**: use `Connect AirPods` + to bring them back. Enabled while they are `Connected`. With several AirPods paired, + every connected pair is disconnected. +- **`Open Bluetooth settings`** — opens Windows Bluetooth settings (to pair new + AirPods, or to connect manually). - **`About PodBridge`** — opens the About window (disclaimer, license, version, docs link). - **`Exit`** — quits PodBridge. @@ -325,9 +342,11 @@ local-only. ## Troubleshooting - **`Status: No AirPods paired`** — no AirPods are paired to this PC yet. Use - `Pair / Reconnect` and add them in Windows Bluetooth settings. + `Open Bluetooth settings` and add them in Windows Bluetooth settings. - **`Status: Disconnected`** — the AirPods are paired but not connected. Take them - out of the case / near the PC, or use `Pair / Reconnect`. + out of the case / near the PC and use `Connect AirPods`. If they still don't + connect (for example they are connected to your phone right now, or out of + range), PodBridge opens Windows Bluetooth settings so you can connect manually. - **`Status: Bluetooth unavailable`** — the PC's Bluetooth radio is off or missing. Turn Bluetooth on in Windows settings. - **`Battery: unknown / out of range`** — no live reading (disconnected or the diff --git a/src/PodBridge.App/App.xaml.cs b/src/PodBridge.App/App.xaml.cs index 08d63c9..c9c9260 100644 --- a/src/PodBridge.App/App.xaml.cs +++ b/src/PodBridge.App/App.xaml.cs @@ -31,6 +31,7 @@ public partial class App : Application private GestureSettingsWindow? _gestureSettingsWindow; private AudioRecoveryWindow? _audioRecoveryWindow; private TrayStatusController? _trayStatusController; + private TrayConnectController? _trayConnectController; private TrayBatteryController? _trayBatteryController; private TrayAudioController? _trayAudioController; private TrayMicController? _trayMicController; @@ -78,6 +79,10 @@ protected override void OnStartup(StartupEventArgs e) _trayIcon, audioReader, monitor, Dispatcher); _trayAudioController.Start(); + // Started before the status controller (which starts the monitor) so its + // StatusChanged subscription sees the initial status. + StartConnectController(monitor); + // Drive the tray from live connection status and show first-run pairing // guidance. StatusChanged is marshalled to this (UI) dispatcher inside // the controller. @@ -91,6 +96,19 @@ protected override void OnStartup(StartupEventArgs e) StartDiagnostics(); } + // Wires the one-click "Connect AirPods" / "Disconnect AirPods" items for the + // already-paired AirPods (driver-free, no admin; the Core link controller falls back to + // Windows Bluetooth settings on failure via the tray controller). + private void StartConnectController(IConnectionMonitor monitor) + { + _trayConnectController = TrayConnectController.Create( + _trayIcon!, + _host!.Services.GetRequiredService(), + monitor, + Dispatcher); + _trayConnectController.Start(); + } + // Wires the tray "Export diagnostics" action and the "Debug logging" toggle (issue #54). // The snapshot factory reads the live Core state on demand; the exporter writes a local, // address-masked, secret-free file (constitution: local-only); the same @@ -350,6 +368,11 @@ protected override void OnExit(ExitEventArgs e) _trayStatusController?.Dispose(); _trayStatusController = null; + // Unsubscribe the connect controller and cancel any in-flight connect/disconnect + // wait so no late outcome touches a disposed tray. + _trayConnectController?.Dispose(); + _trayConnectController = null; + // The diagnostics controller owns no subscription (it only wired tray handlers), so // dropping the reference is enough; the container disposes its resolved services. _trayDiagnosticsController = null; diff --git a/src/PodBridge.App/CompositionRoot.cs b/src/PodBridge.App/CompositionRoot.cs index d70368f..b7a1aeb 100644 --- a/src/PodBridge.App/CompositionRoot.cs +++ b/src/PodBridge.App/CompositionRoot.cs @@ -75,6 +75,16 @@ private static void ConfigureServices(IServiceCollection services) // container disposes it (IDisposable) on shutdown, unsubscribing it. services.AddSingleton(); + // One-click connect / disconnect of already-paired AirPods (follow-up to issue #7). + // Core policy driving the driver-free IBluetoothAudioConnector: it confirms an + // accepted request via the link state, re-sends a request the driver silently + // dropped (common right after a disconnect) and gives up after a generous timeout. + // A singleton so its single-operation guard spans the whole app; the tray + // (TrayConnectController) is its only consumer. Built via a factory so the connector + // is bound explicitly and the poll / re-send / timeout / clock defaults apply. + services.AddSingleton(sp => new BluetoothAudioLinkController( + sp.GetRequiredService())); + // Phase 4 mic-profile policy engine (issue #30). A singleton holding live event // subscriptions to IAudioSessionMonitor for the app's lifetime (disposed by the // container on shutdown). Constructed at startup so it runs on the background diff --git a/src/PodBridge.App/TrayConnectController.cs b/src/PodBridge.App/TrayConnectController.cs new file mode 100644 index 0000000..1b43aa6 --- /dev/null +++ b/src/PodBridge.App/TrayConnectController.cs @@ -0,0 +1,178 @@ +using System.Windows.Threading; +using PodBridge.Core.Bluetooth; +using PodBridge.Core.Models; + +namespace PodBridge.App; + +/// +/// Binds the Core (one-click connect / +/// disconnect of the already-paired AirPods) and the live +/// status to the "Connect AirPods" / "Disconnect AirPods" items. +/// The Core controller owns the send / confirm / re-send / timeout policy; this controller +/// only renders it and forwards clicks: +/// +/// Each item is enabled per / +/// for the current status, and both are +/// disabled — with "Connecting…" / "Disconnecting…" — while an operation runs. +/// The operation runs on the thread pool (short synchronous COM calls plus a +/// confirmation wait of up to 45 s), so the UI thread is never blocked. +/// The outcome is shown as a notification; on any failure (no paired AirPods, no +/// connect control, declined, timed out) Windows Bluetooth settings are opened as the +/// fallback. +/// +/// Owns only its subscription, handler wiring and the shutdown cancellation; the Core +/// controller's lifetime belongs to the DI container. Must be started on the UI thread. +/// +public sealed class TrayConnectController : IDisposable +{ + private readonly TrayIcon _tray; + private readonly BluetoothAudioLinkController _link; + private readonly IConnectionMonitor _monitor; + private readonly Dispatcher _dispatcher; + private readonly CancellationTokenSource _shutdown = new(); + + private ConnectionStatus _status; + private BluetoothAudioRequest? _pending; + private bool _disposed; + + private TrayConnectController( + TrayIcon tray, + BluetoothAudioLinkController link, + IConnectionMonitor monitor, + Dispatcher dispatcher) + { + _tray = tray; + _link = link; + _monitor = monitor; + _dispatcher = dispatcher; + } + + /// + /// Creates a controller binding and + /// to . Call to wire the menu items. + /// + public static TrayConnectController Create( + TrayIcon tray, + BluetoothAudioLinkController link, + IConnectionMonitor monitor, + Dispatcher dispatcher) + => new(tray, link, monitor, dispatcher); + + /// + /// Wires the menu actions, subscribes to status changes and renders the items for the + /// current status. Must be called on the UI thread. + /// + public void Start() + { + _tray.SetConnectionHandlers(OnConnect, OnDisconnect); + _monitor.StatusChanged += OnStatusChanged; + _status = _monitor.CurrentStatus; + Render(); + } + + /// + /// Unsubscribes and cancels an in-flight operation so no late result touches a + /// disposed tray. + /// + public void Dispose() + { + if (_disposed) + { + return; + } + + _disposed = true; + _monitor.StatusChanged -= OnStatusChanged; + _shutdown.Cancel(); + _shutdown.Dispose(); + } + + private void OnConnect() => _ = RunAsync(BluetoothAudioRequest.Connect); + + private void OnDisconnect() => _ = RunAsync(BluetoothAudioRequest.Disconnect); + + private void OnStatusChanged(object? sender, ConnectionStatus status) + => _dispatcher.InvokeAsync(() => + { + _status = status; + if (!_disposed) + { + Render(); + } + }); + + // Starts on the UI thread (a menu click) and resumes there after the thread-pool + // work, so the tray is only touched from the UI thread. + private async Task RunAsync(BluetoothAudioRequest request) + { + if (_pending is not null || _disposed) + { + return; + } + + _pending = request; + Render(); + var outcome = await ExecuteAsync(request).ConfigureAwait(true); + _pending = null; + if (_disposed || outcome is null) + { + return; + } + + Render(); + ShowOutcome(request, outcome.Value); + } + + private async Task ExecuteAsync(BluetoothAudioRequest request) + { + var token = _shutdown.Token; + try + { + return await Task.Run( + () => request == BluetoothAudioRequest.Connect + ? _link.ConnectAsync(token) + : _link.DisconnectAsync(token), + token).ConfigureAwait(true); + } + catch (OperationCanceledException) + { + return null; // the app is shutting down + } + catch (Exception) + { + // Best-effort: a failure must never crash the tray; report it as declined, + // which falls back to Windows Bluetooth settings. + return BluetoothAudioLinkOutcome.Rejected; + } + } + + private void ShowOutcome(BluetoothAudioRequest request, BluetoothAudioLinkOutcome outcome) + { + var notice = BluetoothAudioLinkText.ForOutcome(request, outcome); + if (notice is null) + { + return; + } + + _tray.ShowNotification(notice.Title, notice.Message); + if (notice.OpenBluetoothSettings) + { + TrayIcon.OpenBluetoothSettings(); + } + } + + private void Render() + { + var idle = _pending is null; + _tray.SetConnectItem( + _pending == BluetoothAudioRequest.Connect + ? BluetoothAudioLinkText.ConnectingLabel + : BluetoothAudioLinkText.ConnectLabel, + idle && BluetoothAudioLinkText.CanConnect(_status)); + _tray.SetDisconnectItem( + _pending == BluetoothAudioRequest.Disconnect + ? BluetoothAudioLinkText.DisconnectingLabel + : BluetoothAudioLinkText.DisconnectLabel, + idle && BluetoothAudioLinkText.CanDisconnect(_status)); + } +} diff --git a/src/PodBridge.App/TrayIcon.cs b/src/PodBridge.App/TrayIcon.cs index 91bcbcb..5658265 100644 --- a/src/PodBridge.App/TrayIcon.cs +++ b/src/PodBridge.App/TrayIcon.cs @@ -6,6 +6,7 @@ using H.NotifyIcon; using H.NotifyIcon.Core; using PodBridge.Core.Audio; +using PodBridge.Core.Bluetooth; using PodBridge.Core.Branding; using PodBridge.Core.Models; @@ -13,10 +14,14 @@ namespace PodBridge.App; /// /// Owns the system-tray icon and its context menu: a status line, a battery line, -/// a codec line, a mic-mode line, "Refresh audio status", "Pair / Reconnect", -/// "Open Bluetooth settings", and "Exit". The status line is driven live from +/// a codec line, a mic-mode line, "Refresh audio status", "Connect AirPods", +/// "Disconnect AirPods", "Open Bluetooth settings", and "Exit". The status line is driven live from /// IConnectionMonitor via -/// (); the battery line from IDeviceStateProvider via +/// (); the connect / disconnect items (one-click connect of the +/// already-paired AirPods) via +/// (, , +/// ; with no handler wired, "Connect AirPods" falls back +/// to Windows Bluetooth settings); the battery line from IDeviceStateProvider via /// (); the codec and /// mic-mode lines from the read-only audio reader via /// (/, with the on-demand read wired via @@ -68,9 +73,13 @@ public sealed class TrayIcon : IDisposable private readonly MenuItem _ncUnavailableItem; private readonly MenuItem _ncEnableTierItem; private readonly MenuItem _debugLoggingItem; + private readonly MenuItem _connectItem; + private readonly MenuItem _disconnectItem; private string _statusText = Placeholder; private string _batteryText = Placeholder; + private Action? _connectHandler; + private Action? _disconnectHandler; private Action? _refreshAudioHandler; private Action? _micModeHandler; private Action? _callModeToggleHandler; @@ -112,6 +121,8 @@ private TrayIcon() _noiseControlMenu = BuildNoiseControlMenu(); _debugLoggingItem = new MenuItem { Header = "Debug logging", IsCheckable = true }; _debugLoggingItem.Click += OnDebugLoggingToggle; + _connectItem = CreateItem(BluetoothAudioLinkText.ConnectLabel, OnConnect); + _disconnectItem = CreateItem(BluetoothAudioLinkText.DisconnectLabel, OnDisconnect); _icon = new TaskbarIcon { ToolTipText = "PodBridge", @@ -164,6 +175,43 @@ public void SetBattery(string batteryText) /// public void SetMicMode(string micLine) => _micItem.Header = micLine; + /// + /// Wires the callbacks invoked by the "Connect AirPods" / "Disconnect AirPods" menu + /// actions (one-click connect of the already-paired AirPods). Call on the UI thread. + /// + public void SetConnectionHandlers(Action onConnect, Action onDisconnect) + { + _connectHandler = onConnect; + _disconnectHandler = onDisconnect; + } + + /// + /// Sets the connect item's label (e.g. "Connect AirPods" / "Connecting…") and whether + /// it can be clicked. Call on the UI thread. + /// + public void SetConnectItem(string header, bool enabled) + { + _connectItem.Header = header; + _connectItem.IsEnabled = enabled; + } + + /// + /// Sets the disconnect item's label (e.g. "Disconnect AirPods" / "Disconnecting…") and + /// whether it can be clicked. Call on the UI thread. + /// + public void SetDisconnectItem(string header, bool enabled) + { + _disconnectItem.Header = header; + _disconnectItem.IsEnabled = enabled; + } + + /// + /// Opens Windows Bluetooth settings (the pairing / manual-connect fallback), showing a + /// non-fatal warning if the shell cannot open it. Call on the UI thread. + /// + public static void OpenBluetoothSettings() + => OpenUri(BluetoothSettingsUri, "Could not open Windows Bluetooth settings."); + /// /// Wires the callback invoked by the "Refresh audio status" menu action (an /// on-demand audio re-read). Call on the UI thread. @@ -358,9 +406,8 @@ private ContextMenu BuildContextMenu() menu.Items.Add(_micPolicyMenu); menu.Items.Add(_noiseControlMenu); menu.Items.Add(CreateItem("Refresh audio status", OnRefreshAudio)); - // Phase 1: "Pair / Reconnect" deep-links to Bluetooth settings like - // "Open Bluetooth settings"; issue #7 gives it live reconnect behaviour. - menu.Items.Add(CreateItem("Pair / Reconnect", OnOpenBluetoothSettings)); + menu.Items.Add(_connectItem); + menu.Items.Add(_disconnectItem); menu.Items.Add(CreateItem("Open Bluetooth settings", OnOpenBluetoothSettings)); menu.Items.Add(new Separator()); menu.Items.Add(CreateItem("Gesture controls…", OnGestureSettings)); @@ -482,16 +529,32 @@ private void OnDebugLoggingToggle(object sender, RoutedEventArgs e) private void OnAbout(object sender, RoutedEventArgs e) => _aboutHandler?.Invoke(); + // With no handler wired, "Connect AirPods" behaves like the Phase-1 deep link and + // opens Windows Bluetooth settings, so the item is never a dead end. + private void OnConnect(object sender, RoutedEventArgs e) + { + if (_connectHandler is not null) + { + _connectHandler(); + return; + } + + OpenBluetoothSettings(); + } + + private void OnDisconnect(object sender, RoutedEventArgs e) + => _disconnectHandler?.Invoke(); + private static void OnOpenBluetoothSettings(object sender, RoutedEventArgs e) - => OpenUri(BluetoothSettingsUri, "Could not open Windows Bluetooth settings."); + => OpenBluetoothSettings(); private static void OnExit(object sender, RoutedEventArgs e) => Application.Current.Shutdown(); // Shell-launches a URI (a Bluetooth-settings deep link or an https docs page), // surfacing a non-fatal warning if the shell cannot handle it. Used for the - // "Open Bluetooth settings" / "Pair / Reconnect" entries and the noise-control - // "Enable advanced tier…" affordance. + // "Open Bluetooth settings" entry, the "Connect AirPods" / "Disconnect AirPods" + // fallback, and the noise-control "Enable advanced tier…" affordance. private static void OpenUri(string uri, string failMessage) { try diff --git a/src/PodBridge.App/TrayStatusController.cs b/src/PodBridge.App/TrayStatusController.cs index 957315c..4a368eb 100644 --- a/src/PodBridge.App/TrayStatusController.cs +++ b/src/PodBridge.App/TrayStatusController.cs @@ -17,7 +17,7 @@ public sealed class TrayStatusController : IDisposable private const string GuidanceTitle = "Pair your AirPods"; private const string GuidanceMessage = - "No AirPods are paired yet. Use \"Pair / Reconnect\" to add them in Windows Bluetooth settings."; + "No AirPods are paired yet. Use \"Open Bluetooth settings\" to add them in Windows Bluetooth settings."; private readonly TrayIcon _tray; private readonly IConnectionMonitor _monitor; diff --git a/src/PodBridge.Core/Bluetooth/AirPodsNameHeuristic.cs b/src/PodBridge.Core/Bluetooth/AirPodsNameHeuristic.cs index 0a2dffa..5d80a5c 100644 --- a/src/PodBridge.Core/Bluetooth/AirPodsNameHeuristic.cs +++ b/src/PodBridge.Core/Bluetooth/AirPodsNameHeuristic.cs @@ -5,10 +5,14 @@ namespace PodBridge.Core.Bluetooth; /// AirPods/Beats accessory when its friendly name contains "AirPods" or "Beats" /// (case-insensitive). Company-id based matching from the BLE-advertisement path /// replaces this in Phase 2 (see docs/specs/archive/spec-foundation-pairing.md). +/// is the stricter AirPods-only variant for actions whose +/// label names AirPods specifically. /// public static class AirPodsNameHeuristic { - private static readonly string[] Needles = ["AirPods", "Beats"]; + private const string AirPodsNeedle = "AirPods"; + + private static readonly string[] Needles = [AirPodsNeedle, "Beats"]; /// True when names an AirPods/Beats device. public static bool IsMatch(string? deviceName) @@ -28,4 +32,13 @@ public static bool IsMatch(string? deviceName) return false; } + + /// + /// True when names AirPods specifically (Beats excluded) — + /// used by actions labelled "AirPods", such as one-click Connect / Disconnect, so they + /// never act on a paired Beats device. + /// + public static bool IsAirPodsName(string? deviceName) + => !string.IsNullOrWhiteSpace(deviceName) + && deviceName.Contains(AirPodsNeedle, StringComparison.OrdinalIgnoreCase); } diff --git a/src/PodBridge.Core/Bluetooth/BluetoothAudioLinkController.cs b/src/PodBridge.Core/Bluetooth/BluetoothAudioLinkController.cs new file mode 100644 index 0000000..8b21187 --- /dev/null +++ b/src/PodBridge.Core/Bluetooth/BluetoothAudioLinkController.cs @@ -0,0 +1,144 @@ +namespace PodBridge.Core.Bluetooth; + +/// +/// Device-independent one-click connect / disconnect policy for already-paired AirPods, +/// driving an (Tier 1: driver-free, admin-free). +/// +/// It reads the link state first: no paired AirPods → +/// (the caller falls back to Windows Bluetooth settings); already in the requested state → +/// , sending nothing. +/// An accepted request only means the driver took it, so the outcome is +/// confirmed by polling the link state (every ). +/// A request sent while a previous link is still winding down (e.g. right after a +/// disconnect) is often silently ignored, so it is re-sent every +/// until the link changes or +/// elapses (). +/// Only one operation runs at a time; a concurrent call returns +/// and sends nothing. +/// +/// The connector does short synchronous OS calls, so UI callers should invoke this off +/// the UI thread (the tray does); the waits themselves are asynchronous. +/// +public sealed class BluetoothAudioLinkController +{ + /// Default interval between link-state checks while waiting for the link to change. + public static readonly TimeSpan DefaultPollInterval = TimeSpan.FromMilliseconds(500); + + /// Default interval after which an accepted-but-unanswered request is re-sent. + public static readonly TimeSpan DefaultResendInterval = TimeSpan.FromSeconds(10); + + /// + /// Default overall wait before giving up. Right after a disconnect the first reconnect + /// can take well over 15 s on real AirPods, so the window is generous. + /// + public static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(45); + + private readonly IBluetoothAudioConnector _connector; + private readonly TimeProvider _timeProvider; + private readonly TimeSpan _pollInterval; + private readonly TimeSpan _resendInterval; + private readonly TimeSpan _timeout; + private int _busy; + + /// Wires the controller to its connector. + /// The OS connect/disconnect boundary. + /// Clock for the poll/resend/timeout waits; defaults to . + /// Link-state poll interval; defaults to . + /// Request re-send interval; defaults to . + /// Overall wait; defaults to . + public BluetoothAudioLinkController( + IBluetoothAudioConnector connector, + TimeProvider? timeProvider = null, + TimeSpan? pollInterval = null, + TimeSpan? resendInterval = null, + TimeSpan? timeout = null) + { + ArgumentNullException.ThrowIfNull(connector); + _connector = connector; + _timeProvider = timeProvider ?? TimeProvider.System; + _pollInterval = pollInterval ?? DefaultPollInterval; + _resendInterval = resendInterval ?? DefaultResendInterval; + _timeout = timeout ?? DefaultTimeout; + } + + /// True while a connect or disconnect is in progress. + public bool IsBusy => Volatile.Read(ref _busy) != 0; + + /// Connects the already-paired AirPods and confirms the link came up. + public Task ConnectAsync(CancellationToken cancellationToken = default) + => RunAsync(BluetoothAudioRequest.Connect, cancellationToken); + + /// Disconnects the AirPods (they stay paired) and confirms the link went down. + public Task DisconnectAsync(CancellationToken cancellationToken = default) + => RunAsync(BluetoothAudioRequest.Disconnect, cancellationToken); + + private async Task RunAsync( + BluetoothAudioRequest request, CancellationToken cancellationToken) + { + if (Interlocked.Exchange(ref _busy, 1) != 0) + { + return BluetoothAudioLinkOutcome.Busy; + } + + try + { + var target = request == BluetoothAudioRequest.Connect + ? BluetoothAudioLinkState.Connected + : BluetoothAudioLinkState.Disconnected; + var state = _connector.GetLinkState(); + if (state == BluetoothAudioLinkState.NotFound) + { + return BluetoothAudioLinkOutcome.NotFound; + } + + if (state == target) + { + return BluetoothAudioLinkOutcome.AlreadyInState; + } + + var result = _connector.SendRequest(request); + return result == BluetoothAudioRequestResult.Accepted + ? await WaitForStateAsync(request, target, cancellationToken).ConfigureAwait(false) + : ToOutcome(result); + } + finally + { + Volatile.Write(ref _busy, 0); + } + } + + // Polls until the link reaches the target, re-sending the request periodically because + // the driver silently drops a request that arrives while the old link is winding down. + private async Task WaitForStateAsync( + BluetoothAudioRequest request, BluetoothAudioLinkState target, CancellationToken cancellationToken) + { + var started = _timeProvider.GetTimestamp(); + var lastSent = started; + while (true) + { + await Task.Delay(_pollInterval, _timeProvider, cancellationToken).ConfigureAwait(false); + if (_connector.GetLinkState() == target) + { + return BluetoothAudioLinkOutcome.Succeeded; + } + + if (_timeProvider.GetElapsedTime(started) >= _timeout) + { + return BluetoothAudioLinkOutcome.TimedOut; + } + + if (_timeProvider.GetElapsedTime(lastSent) >= _resendInterval) + { + _ = _connector.SendRequest(request); + lastSent = _timeProvider.GetTimestamp(); + } + } + } + + private static BluetoothAudioLinkOutcome ToOutcome(BluetoothAudioRequestResult result) => result switch + { + BluetoothAudioRequestResult.NotFound => BluetoothAudioLinkOutcome.NotFound, + BluetoothAudioRequestResult.Unsupported => BluetoothAudioLinkOutcome.Unsupported, + _ => BluetoothAudioLinkOutcome.Rejected, + }; +} diff --git a/src/PodBridge.Core/Bluetooth/BluetoothAudioLinkNotice.cs b/src/PodBridge.Core/Bluetooth/BluetoothAudioLinkNotice.cs new file mode 100644 index 0000000..2df95b4 --- /dev/null +++ b/src/PodBridge.Core/Bluetooth/BluetoothAudioLinkNotice.cs @@ -0,0 +1,11 @@ +namespace PodBridge.Core.Bluetooth; + +/// +/// A user-facing result of a one-click connect/disconnect: the notification to show and +/// whether the tray should fall back to opening Windows Bluetooth settings. +/// +/// Short notification title. +/// Honest notification body. +/// True when the action failed or found nothing to act on, +/// so the user is sent to Windows Bluetooth settings to finish it there. +public sealed record BluetoothAudioLinkNotice(string Title, string Message, bool OpenBluetoothSettings); diff --git a/src/PodBridge.Core/Bluetooth/BluetoothAudioLinkOutcome.cs b/src/PodBridge.Core/Bluetooth/BluetoothAudioLinkOutcome.cs new file mode 100644 index 0000000..4a7a071 --- /dev/null +++ b/src/PodBridge.Core/Bluetooth/BluetoothAudioLinkOutcome.cs @@ -0,0 +1,26 @@ +namespace PodBridge.Core.Bluetooth; + +/// The final outcome of a connect or disconnect. +public enum BluetoothAudioLinkOutcome +{ + /// The link reached the requested state (confirmed by the link state, not the request). + Succeeded = 0, + + /// The link was already in the requested state; nothing was sent. + AlreadyInState = 1, + + /// No paired AirPods were found; pairing happens in Windows Bluetooth settings. + NotFound = 2, + + /// The AirPods expose no Bluetooth audio connection control. + Unsupported = 3, + + /// The Bluetooth audio driver rejected the request. + Rejected = 4, + + /// The request was accepted but the link did not change before the timeout. + TimedOut = 5, + + /// Another connect/disconnect is already in progress; nothing was sent. + Busy = 6, +} diff --git a/src/PodBridge.Core/Bluetooth/BluetoothAudioLinkState.cs b/src/PodBridge.Core/Bluetooth/BluetoothAudioLinkState.cs new file mode 100644 index 0000000..5aa2799 --- /dev/null +++ b/src/PodBridge.Core/Bluetooth/BluetoothAudioLinkState.cs @@ -0,0 +1,17 @@ +namespace PodBridge.Core.Bluetooth; + +/// +/// The Bluetooth audio link state of the paired AirPods as reported by an +/// . +/// +public enum BluetoothAudioLinkState +{ + /// No paired AirPods audio device is known to Windows. + NotFound = 0, + + /// The AirPods are paired but their audio link is down. + Disconnected = 1, + + /// The AirPods audio link is up (an AirPods audio endpoint is active). + Connected = 2, +} diff --git a/src/PodBridge.Core/Bluetooth/BluetoothAudioLinkText.cs b/src/PodBridge.Core/Bluetooth/BluetoothAudioLinkText.cs new file mode 100644 index 0000000..19f6d83 --- /dev/null +++ b/src/PodBridge.Core/Bluetooth/BluetoothAudioLinkText.cs @@ -0,0 +1,85 @@ +using PodBridge.Core.Models; + +namespace PodBridge.Core.Bluetooth; + +/// +/// Pure, device-independent presentation for the tray's one-click "Connect AirPods" / +/// "Disconnect AirPods" actions: the menu labels, when each action is offered for a given +/// , and the honest notification (plus the Bluetooth-settings +/// fallback decision) for every . Kept in Core so the +/// Tier-1 test gate covers it (BluetoothAudioLinkTextTests). +/// +public static class BluetoothAudioLinkText +{ + /// Tray menu label for the connect action. + public const string ConnectLabel = "Connect AirPods"; + + /// Tray menu label shown (disabled) while a connect is in progress. + public const string ConnectingLabel = "Connecting…"; + + /// Tray menu label for the disconnect action. + public const string DisconnectLabel = "Disconnect AirPods"; + + /// Tray menu label shown (disabled) while a disconnect is in progress. + public const string DisconnectingLabel = "Disconnecting…"; + + private const string SettingsFallback = " Opening Windows Bluetooth settings."; + + /// + /// Connect is offered unless the AirPods are known to be connected. With no AirPods + /// paired it stays offered and falls back to Bluetooth settings, the pairing path. + /// + public static bool CanConnect(ConnectionStatus status) => status != ConnectionStatus.Connected; + + /// Disconnect is offered when the AirPods are connected (or the status is not yet known). + public static bool CanDisconnect(ConnectionStatus status) + => status is ConnectionStatus.Connected or ConnectionStatus.Unknown; + + /// + /// The notification for of , or + /// when nothing should be shown (). + /// + public static BluetoothAudioLinkNotice? ForOutcome( + BluetoothAudioRequest request, BluetoothAudioLinkOutcome outcome) + => request == BluetoothAudioRequest.Connect ? ForConnect(outcome) : ForDisconnect(outcome); + + private static BluetoothAudioLinkNotice? ForConnect(BluetoothAudioLinkOutcome outcome) => outcome switch + { + BluetoothAudioLinkOutcome.Succeeded => Done("AirPods connected", "Your AirPods are connected to this PC."), + BluetoothAudioLinkOutcome.AlreadyInState => Done("AirPods connected", "Your AirPods were already connected."), + BluetoothAudioLinkOutcome.NotFound => NotFound(), + BluetoothAudioLinkOutcome.Unsupported => Fallback( + "Couldn't connect", "Windows offers no connect control for these AirPods."), + BluetoothAudioLinkOutcome.Rejected => Fallback( + "Couldn't connect", "Windows declined the connect request."), + BluetoothAudioLinkOutcome.TimedOut => Fallback( + "Couldn't connect", + "Your AirPods didn't connect. Take them out of the case (or open the lid) and try again."), + _ => null, + }; + + private static BluetoothAudioLinkNotice? ForDisconnect(BluetoothAudioLinkOutcome outcome) => outcome switch + { + BluetoothAudioLinkOutcome.Succeeded => Done( + "AirPods disconnected", + $"Your AirPods are disconnected from this PC and stay paired. Use \"{ConnectLabel}\" to reconnect."), + BluetoothAudioLinkOutcome.AlreadyInState => Done( + "AirPods disconnected", "Your AirPods were already disconnected."), + BluetoothAudioLinkOutcome.NotFound => NotFound(), + BluetoothAudioLinkOutcome.Unsupported => Fallback( + "Couldn't disconnect", "Windows offers no disconnect control for these AirPods."), + BluetoothAudioLinkOutcome.Rejected => Fallback( + "Couldn't disconnect", "Windows declined the disconnect request."), + BluetoothAudioLinkOutcome.TimedOut => Fallback( + "Couldn't disconnect", "Your AirPods are still connected."), + _ => null, + }; + + private static BluetoothAudioLinkNotice NotFound() => Fallback( + "No paired AirPods found", "Pair your AirPods in Windows Bluetooth settings first."); + + private static BluetoothAudioLinkNotice Done(string title, string message) => new(title, message, false); + + private static BluetoothAudioLinkNotice Fallback(string title, string message) + => new(title, message + SettingsFallback, true); +} diff --git a/src/PodBridge.Core/Bluetooth/BluetoothAudioRequest.cs b/src/PodBridge.Core/Bluetooth/BluetoothAudioRequest.cs new file mode 100644 index 0000000..9bb57a3 --- /dev/null +++ b/src/PodBridge.Core/Bluetooth/BluetoothAudioRequest.cs @@ -0,0 +1,11 @@ +namespace PodBridge.Core.Bluetooth; + +/// A one-shot request to bring the paired AirPods' audio link up or down. +public enum BluetoothAudioRequest +{ + /// Connect the already-paired AirPods. + Connect = 0, + + /// Disconnect the AirPods (they stay paired). + Disconnect = 1, +} diff --git a/src/PodBridge.Core/Bluetooth/BluetoothAudioRequestResult.cs b/src/PodBridge.Core/Bluetooth/BluetoothAudioRequestResult.cs new file mode 100644 index 0000000..f03f6cd --- /dev/null +++ b/src/PodBridge.Core/Bluetooth/BluetoothAudioRequestResult.cs @@ -0,0 +1,21 @@ +namespace PodBridge.Core.Bluetooth; + +/// +/// What the OS did with a single . +/// only means the Bluetooth audio driver took the request — not that the link changed; +/// callers confirm the outcome through . +/// +public enum BluetoothAudioRequestResult +{ + /// At least one Bluetooth audio driver accepted the request. + Accepted = 0, + + /// No paired AirPods audio device was found to send the request to. + NotFound = 1, + + /// The AirPods expose no Bluetooth audio connection control. + Unsupported = 2, + + /// Every Bluetooth audio driver rejected the request (or the OS call failed). + Rejected = 3, +} diff --git a/src/PodBridge.Core/Bluetooth/IBluetoothAudioConnector.cs b/src/PodBridge.Core/Bluetooth/IBluetoothAudioConnector.cs new file mode 100644 index 0000000..f305031 --- /dev/null +++ b/src/PodBridge.Core/Bluetooth/IBluetoothAudioConnector.cs @@ -0,0 +1,22 @@ +namespace PodBridge.Core.Bluetooth; + +/// +/// OS boundary for bringing the already-paired AirPods' Bluetooth audio link up or down +/// driver-free and admin-free (Tier 1). The Windows adapter sends the same one-shot +/// request the Windows Sound control panel "Connect" / "Disconnect" uses to the AirPods' +/// Bluetooth audio drivers (A2DP and hands-free). Both members are synchronous, +/// short OS calls that never throw: failures degrade to +/// or a non- result. The retry/timeout +/// policy lives in Core (), not here. +/// +public interface IBluetoothAudioConnector +{ + /// Reads the current audio link state of the paired AirPods. + BluetoothAudioLinkState GetLinkState(); + + /// + /// Sends one to the AirPods' Bluetooth audio drivers. + /// does not mean the link changed. + /// + BluetoothAudioRequestResult SendRequest(BluetoothAudioRequest request); +} diff --git a/src/PodBridge.Windows/Interop/BluetoothAudioInterop.cs b/src/PodBridge.Windows/Interop/BluetoothAudioInterop.cs new file mode 100644 index 0000000..682a537 --- /dev/null +++ b/src/PodBridge.Windows/Interop/BluetoothAudioInterop.cs @@ -0,0 +1,131 @@ +using System.Runtime.InteropServices; + +namespace PodBridge.Windows.Interop; + +// COM interop for the one-click connect / disconnect of already-paired AirPods, isolated +// to the WindowsBluetoothAudioConnector adapter. Tier 1: driver-free, admin-free. It sends +// the same one-shot request the Windows Sound control panel's "Connect" / "Disconnect" +// uses: a KS property GET on the Bluetooth audio filter behind an AirPods endpoint. Every +// IID, vtable order and constant here is from the public Windows SDK headers +// (mmdeviceapi.h, devicetopology.h, ks.h, ksmedia.h); nothing is copied from other +// projects. Only the methods actually invoked carry full signatures; earlier vtable slots +// that are never called are declared purely to preserve slot order. Reuses EDataFlow / +// IMMDevice / IMMDeviceCollection from CoreAudioInterop.cs and +// IMMDeviceEnumeratorForActivation from AudioClientInterop.cs. + +/// Constants for the Bluetooth audio one-shot connect / disconnect request. +internal static class BluetoothAudioInterop +{ + // DEVICE_STATE_UNPLUGGED (mmdeviceapi.h): a paired Bluetooth audio device whose link is + // down reports its endpoints as unplugged; connected ones are DEVICE_STATE_ACTIVE. + internal const uint DeviceStateUnplugged = 0x00000008; + + // Enumerate only endpoints of devices that are still installed (active or unplugged), + // so a removed / unpaired device is reported as "not found" rather than "disconnected". + internal const uint PairedEndpointStateMask = NativeMethods.DeviceStateActive | DeviceStateUnplugged; + + // KSPROPERTY_TYPE_GET (ks.h). The one-shot requests are issued as GETs with no data. + internal const uint KsPropertyTypeGet = 0x00000001; + + // KSPROPERTY_ONESHOT_RECONNECT / KSPROPERTY_ONESHOT_DISCONNECT (ksmedia.h, + // KSPROPERTY_BTAUDIO enumeration): ask the Bluetooth audio driver to bring the link + // up / down once. S_OK means the request was accepted, not that the link changed. + internal const uint KsPropertyOneShotReconnect = 0; + internal const uint KsPropertyOneShotDisconnect = 1; + + // Device-topology filter ids of Bluetooth audio drivers start with this prefix + // (BTHENUM = A2DP stereo, BTHHFENUM = hands-free); other filters are ignored. + internal const string BluetoothFilterIdPrefix = @"{2}.\\?\bth"; + + // KSPROPSETID_BtAudio (ksmedia.h): the Bluetooth audio property set. + internal static readonly Guid KsPropSetIdBtAudio = new("7FA06C40-B8F6-4C7E-8556-E8C33A12E54D"); +} + +/// +/// The KSPROPERTY identifier (ks.h): property set, id and flags (24 bytes). Named +/// …Header to keep it distinct from the method. +/// +[StructLayout(LayoutKind.Sequential)] +internal struct KsPropertyHeader +{ + public Guid Set; + public uint Id; + public uint Flags; +} + +/// +/// The IMMDevice surface extended through GetState (vtable slot 3), which the +/// read-only in CoreAudioInterop.cs does not declare. Same IID; +/// slots 0–2 mirror the real signatures purely to place GetState at slot 3. +/// +[ComImport] +[Guid("D666063F-1587-4E43-81F1-B948E807363F")] +[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +internal interface IMMDeviceWithState +{ + void Activate( + ref Guid iid, + uint dwClsCtx, + IntPtr pActivationParams, + [MarshalAs(UnmanagedType.IUnknown)] out object ppInterface); + + void OpenPropertyStore(uint stgmAccess, out IPropertyStore ppProperties); + + void GetId([MarshalAs(UnmanagedType.LPWStr)] out string ppstrId); + + void GetState(out uint pdwState); +} + +/// IDeviceTopology (devicetopology.h) — the endpoint's device topology. +[ComImport] +[Guid("2A07407E-6497-4A18-9787-32F79BD0D98F")] +[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +internal interface IDeviceTopology +{ + void GetConnectorCount(out uint pCount); + + void GetConnector(uint nIndex, out IConnector ppConnector); +} + +/// IConnector (devicetopology.h) — a connection point between two topologies. +[ComImport] +[Guid("9C2C4058-23F5-41DE-877A-DF3AF236A09E")] +[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +internal interface IConnector +{ + // Slots 0–6 (unused) — declared only to place GetDeviceIdConnectedTo at slot 7. + void GetConnectorType(out int pType); + + void GetDataFlow(out int pFlow); + + void ConnectTo(IntPtr pConnectTo); + + void Disconnect(); + + void IsConnected(out int pbConnected); + + void GetConnectedTo(out IntPtr ppConTo); + + void GetConnectorIdConnectedTo(out IntPtr ppwstrConnectorId); + + // The device id of the topology on the other side — for an AirPods endpoint, the + // Bluetooth audio driver's KS filter. An unconnected connector returns E_NOTFOUND; + // PreserveSig lets the caller skip it. + [PreserveSig] + int GetDeviceIdConnectedTo([MarshalAs(UnmanagedType.LPWStr)] out string? ppwstrDeviceId); +} + +/// IKsControl (ks.h) — sends a KS property request to a driver filter. +[ComImport] +[Guid("28F54685-06FD-11D2-B27A-00A0C9223196")] +[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] +internal interface IKsControl +{ + [PreserveSig] + int KsProperty( + ref KsPropertyHeader property, + uint propertyLength, + IntPtr propertyData, + uint dataLength, + out uint bytesReturned); +} diff --git a/src/PodBridge.Windows/ServiceCollectionExtensions.cs b/src/PodBridge.Windows/ServiceCollectionExtensions.cs index 277274d..53090da 100644 --- a/src/PodBridge.Windows/ServiceCollectionExtensions.cs +++ b/src/PodBridge.Windows/ServiceCollectionExtensions.cs @@ -19,7 +19,8 @@ namespace PodBridge.Windows; /// read-only audio-state reader; Phase 4 adds the mic-profile policy lever /// () and the comms-capture session monitor /// (); Phase 5 adds the opt-in auto-start toggle -/// (). +/// (). The one-click connect adds the paired-AirPods +/// connect / disconnect lever (). /// public static class ServiceCollectionExtensions { @@ -54,6 +55,13 @@ public static IServiceCollection AddWindowsAdapters(this IServiceCollection serv // needs no shared lifetime and is registered transient (no IDisposable). services.AddTransient(); + // One-click connect / disconnect of already-paired AirPods (follow-up to issue #7). + // Stateless like the audio-state reader: it creates and releases short-lived Core + // Audio / device-topology COM objects per call and holds nothing between calls, so it + // is transient. Driver-free and admin-free — it sends the public one-shot KS request + // the Windows Sound control panel uses; any COM failure degrades, never throws. + services.AddTransient(); + // Phase 4 mic-profile policy (issue #30). Both are singletons: the session // monitor owns a background MTA COM thread + IAudioSessionManager2 notification // registrations that must live for the app's lifetime, and the container diff --git a/src/PodBridge.Windows/WindowsBluetoothAudioConnector.cs b/src/PodBridge.Windows/WindowsBluetoothAudioConnector.cs new file mode 100644 index 0000000..32c00af --- /dev/null +++ b/src/PodBridge.Windows/WindowsBluetoothAudioConnector.cs @@ -0,0 +1,268 @@ +using System.Runtime.InteropServices; +using PodBridge.Core.Bluetooth; +using PodBridge.Windows.Interop; + +namespace PodBridge.Windows; + +/// +/// Windows implementation of — connects or +/// disconnects already-paired AirPods the way the Windows Sound control panel's +/// "Connect" / "Disconnect" does. Tier 1: driver-free, admin-free (asInvoker); it +/// never pairs, unpairs or installs anything. +/// +/// +/// Finding the AirPods. Audio endpoints of installed devices (active or +/// unplugged, render and capture) are matched by friendly name with +/// — AirPods only, so a paired Beats +/// device is never connected or disconnected by an "AirPods" action. An endpoint is +/// DEVICE_STATE_ACTIVE while the Bluetooth link is up and +/// DEVICE_STATE_UNPLUGGED while a paired device is disconnected, which is how +/// reports the link. An endpoint that fails mid-enumeration +/// (e.g. it is removed meanwhile) is skipped rather than failing the whole result. +/// The request. For every matched endpoint the device topology's connectors +/// are followed (IConnector::GetDeviceIdConnectedTo) to the +/// Bluetooth audio driver's filter (id prefix {2}.\\?\bth: the A2DP stereo and the +/// hands-free filter). Each distinct filter receives the public one-shot +/// KSPROPERTY_ONESHOT_RECONNECT / KSPROPERTY_ONESHOT_DISCONNECT request +/// (KSPROPSETID_BtAudio, ksmedia.h) via IKsControl — both profiles, like +/// Windows does. The driver accepting it only means the request was taken; the caller +/// () confirms via the link state. +/// Several paired AirPods. Every matched device receives the request; the +/// one in range connects. Every COM failure degrades to +/// / — this adapter never throws. +/// +public sealed class WindowsBluetoothAudioConnector : IBluetoothAudioConnector +{ + /// + public BluetoothAudioLinkState GetLinkState() + => WithEnumerator(ReadLinkState, BluetoothAudioLinkState.NotFound); + + /// + public BluetoothAudioRequestResult SendRequest(BluetoothAudioRequest request) + => WithEnumerator(enumerator => Send(enumerator, request), BluetoothAudioRequestResult.Rejected); + + private static T WithEnumerator(Func action, T fallback) + { + object? comObject = null; + try + { + var comType = Type.GetTypeFromCLSID(NativeMethods.MMDeviceEnumeratorClsid); + comObject = comType is null ? null : Activator.CreateInstance(comType); + return comObject is IMMDeviceEnumeratorForActivation enumerator ? action(enumerator) : fallback; + } + catch (Exception) + { + // Any COM / enumeration failure degrades to the fallback (constitution: + // graceful degradation) — the connector never throws out. + return fallback; + } + finally + { + if (comObject is not null) + { + Marshal.ReleaseComObject(comObject); + } + } + } + + private static BluetoothAudioLinkState ReadLinkState(IMMDeviceEnumeratorForActivation enumerator) + { + var state = BluetoothAudioLinkState.NotFound; + ForEachAirPodsEndpoint(enumerator, device => + { + ((IMMDeviceWithState)device).GetState(out var endpointState); + if (endpointState == NativeMethods.DeviceStateActive) + { + state = BluetoothAudioLinkState.Connected; + } + else if (state == BluetoothAudioLinkState.NotFound) + { + state = BluetoothAudioLinkState.Disconnected; + } + }); + return state; + } + + private static BluetoothAudioRequestResult Send( + IMMDeviceEnumeratorForActivation enumerator, BluetoothAudioRequest request) + { + var endpoints = 0; + var filterIds = new HashSet(StringComparer.OrdinalIgnoreCase); + ForEachAirPodsEndpoint(enumerator, device => + { + endpoints++; + CollectBluetoothFilterIds(device, filterIds); + }); + + if (endpoints == 0) + { + return BluetoothAudioRequestResult.NotFound; + } + + if (filterIds.Count == 0) + { + return BluetoothAudioRequestResult.Unsupported; + } + + var accepted = false; + foreach (var filterId in filterIds) + { + // Non-short-circuiting: every filter (A2DP and hands-free) gets the request. + accepted |= TrySendToFilter(enumerator, filterId, request); + } + + return accepted ? BluetoothAudioRequestResult.Accepted : BluetoothAudioRequestResult.Rejected; + } + + private static void ForEachAirPodsEndpoint( + IMMDeviceEnumeratorForActivation enumerator, Action visit) + { + enumerator.EnumAudioEndpoints(EDataFlow.All, BluetoothAudioInterop.PairedEndpointStateMask, out var collection); + try + { + collection.GetCount(out var count); + for (uint i = 0; i < count; i++) + { + TryVisitEndpoint(collection, i, visit); + } + } + finally + { + Marshal.ReleaseComObject(collection); + } + } + + // One endpoint failing (e.g. removed during enumeration, or its property store / state + // unreadable) must not degrade the whole result into NotFound / Rejected — and with it + // a confirmation poll into a false timeout — so it is skipped and the loop continues. + private static void TryVisitEndpoint(IMMDeviceCollection collection, uint index, Action visit) + { + IMMDevice? device = null; + try + { + collection.Item(index, out device); + if (IsAirPodsEndpoint(device)) + { + visit(device); + } + } + catch (Exception) + { + // Skip this endpoint; the others are still read. + } + finally + { + if (device is not null) + { + Marshal.ReleaseComObject(device); + } + } + } + + private static bool IsAirPodsEndpoint(IMMDevice device) + { + device.OpenPropertyStore(NativeMethods.StgmRead, out var store); + try + { + return AirPodsNameHeuristic.IsAirPodsName( + NativeMethods.GetStringProperty(store, PropertyKeys.DeviceFriendlyName)); + } + finally + { + Marshal.ReleaseComObject(store); + } + } + + // Walks the endpoint's topology to the driver filters it is connected to and keeps + // the Bluetooth audio ones. An endpoint whose topology cannot be read is skipped. + private static void CollectBluetoothFilterIds(IMMDevice device, HashSet filterIds) + { + object? raw = null; + try + { + var iid = typeof(IDeviceTopology).GUID; + device.Activate(ref iid, NativeMethods.ClsCtxAll, IntPtr.Zero, out raw); + var topology = (IDeviceTopology)raw; + topology.GetConnectorCount(out var count); + for (uint i = 0; i < count; i++) + { + var filterId = TryGetConnectedFilterId(topology, i); + if (filterId is not null + && filterId.StartsWith(BluetoothAudioInterop.BluetoothFilterIdPrefix, StringComparison.OrdinalIgnoreCase)) + { + filterIds.Add(filterId); + } + } + } + catch (Exception) + { + // Skip this endpoint; the others may still reach the driver. + } + finally + { + if (raw is not null) + { + Marshal.ReleaseComObject(raw); + } + } + } + + private static string? TryGetConnectedFilterId(IDeviceTopology topology, uint index) + { + topology.GetConnector(index, out var connector); + try + { + // An unconnected connector fails (E_NOTFOUND): nothing behind it. + return connector.GetDeviceIdConnectedTo(out var filterId) < 0 ? null : filterId; + } + finally + { + Marshal.ReleaseComObject(connector); + } + } + + // Sends the one-shot request to one filter. True when the driver accepted it (which + // does not yet mean the link changed — the caller confirms via the link state). + private static bool TrySendToFilter( + IMMDeviceEnumeratorForActivation enumerator, string filterId, BluetoothAudioRequest request) + { + IMMDevice? filter = null; + object? raw = null; + try + { + enumerator.GetDevice(filterId, out filter); + var iid = typeof(IKsControl).GUID; + filter.Activate(ref iid, NativeMethods.ClsCtxAll, IntPtr.Zero, out raw); + var property = new KsPropertyHeader + { + Set = BluetoothAudioInterop.KsPropSetIdBtAudio, + Id = request == BluetoothAudioRequest.Connect + ? BluetoothAudioInterop.KsPropertyOneShotReconnect + : BluetoothAudioInterop.KsPropertyOneShotDisconnect, + Flags = BluetoothAudioInterop.KsPropertyTypeGet, + }; + var hr = ((IKsControl)raw).KsProperty( + ref property, (uint)Marshal.SizeOf(), IntPtr.Zero, 0, out _); + return hr >= 0; + } + catch (Exception) + { + return false; + } + finally + { + ReleaseAll(raw, filter); + } + } + + private static void ReleaseAll(params object?[] comObjects) + { + foreach (var comObject in comObjects) + { + if (comObject is not null) + { + Marshal.ReleaseComObject(comObject); + } + } + } +} diff --git a/tests/PodBridge.Core.Tests/Bluetooth/AirPodsNameHeuristicTests.cs b/tests/PodBridge.Core.Tests/Bluetooth/AirPodsNameHeuristicTests.cs index 4b614f9..474b1db 100644 --- a/tests/PodBridge.Core.Tests/Bluetooth/AirPodsNameHeuristicTests.cs +++ b/tests/PodBridge.Core.Tests/Bluetooth/AirPodsNameHeuristicTests.cs @@ -22,4 +22,21 @@ public void KnownAirPodsOrBeatsNames_Match(string name) [InlineData("Galaxy Buds")] public void OtherOrEmptyNames_DoNotMatch(string? name) => Assert.False(AirPodsNameHeuristic.IsMatch(name)); + + [Theory] + [InlineData("AirPods Pro")] + [InlineData("Headphones (AirPods Pro (Anton))")] // an audio endpoint's friendly name + [InlineData("airpods max")] // case-insensitive + public void AirPodsNames_AreAirPodsNames(string name) + => Assert.True(AirPodsNameHeuristic.IsAirPodsName(name)); + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + [InlineData("Beats Fit Pro")] + [InlineData("Headphones (Powerbeats Pro)")] + [InlineData("Sony WH-1000XM5")] + public void BeatsOtherOrEmptyNames_AreNotAirPodsNames(string? name) + => Assert.False(AirPodsNameHeuristic.IsAirPodsName(name)); } diff --git a/tests/PodBridge.Core.Tests/Bluetooth/BluetoothAudioLinkControllerTests.cs b/tests/PodBridge.Core.Tests/Bluetooth/BluetoothAudioLinkControllerTests.cs new file mode 100644 index 0000000..34110f2 --- /dev/null +++ b/tests/PodBridge.Core.Tests/Bluetooth/BluetoothAudioLinkControllerTests.cs @@ -0,0 +1,188 @@ +using PodBridge.Core.Bluetooth; +using Xunit; + +namespace PodBridge.Core.Tests.Bluetooth; + +/// +/// Tier-1 (device-independent) tests for the one-click connect/disconnect policy: the +/// state pre-check, confirmation via the link state, the re-send of a silently ignored +/// request, the timeout, the request-result mapping, and the single in-flight guard. +/// +public class BluetoothAudioLinkControllerTests +{ + private static readonly TimeSpan Poll = BluetoothAudioLinkController.DefaultPollInterval; + + [Fact] + public async Task Connect_AlreadyConnected_SendsNothing() + { + var connector = new FakeBluetoothAudioConnector { State = BluetoothAudioLinkState.Connected }; + var controller = new BluetoothAudioLinkController(connector, new TimerCountingTimeProvider()); + + var outcome = await controller.ConnectAsync(); + + Assert.Equal(BluetoothAudioLinkOutcome.AlreadyInState, outcome); + Assert.Empty(connector.Requests); + } + + [Fact] + public async Task Connect_NoPairedAirPods_ReturnsNotFoundAndSendsNothing() + { + var connector = new FakeBluetoothAudioConnector { State = BluetoothAudioLinkState.NotFound }; + var controller = new BluetoothAudioLinkController(connector, new TimerCountingTimeProvider()); + + var outcome = await controller.ConnectAsync(); + + Assert.Equal(BluetoothAudioLinkOutcome.NotFound, outcome); + Assert.Empty(connector.Requests); + } + + [Fact] + public async Task Connect_Accepted_IsConfirmedByLinkStateOnNextPoll() + { + var connector = new FakeBluetoothAudioConnector(); + var time = new TimerCountingTimeProvider(); + var controller = new BluetoothAudioLinkController(connector, time); + + var pending = controller.ConnectAsync(); + Assert.False(pending.IsCompleted); // accepted is not connected: it waits to confirm + + var outcome = await RunToCompletionAsync(pending, time); + + Assert.Equal(BluetoothAudioLinkOutcome.Succeeded, outcome); + Assert.Equal([BluetoothAudioRequest.Connect], connector.Requests); + } + + [Fact] + public async Task Connect_FirstRequestIgnored_ResendsAfterTenSecondsAndSucceeds() + { + // Real hardware: right after a disconnect the first reconnect is silently dropped. + var connector = new FakeBluetoothAudioConnector { IgnoredRequests = 1 }; + var time = new TimerCountingTimeProvider(); + var controller = new BluetoothAudioLinkController(connector, time); + + var pending = controller.ConnectAsync(); + Advance(time, pending, BluetoothAudioLinkController.DefaultResendInterval - Poll); + Assert.False(pending.IsCompleted); + Assert.Single(connector.Requests); + + var outcome = await RunToCompletionAsync(pending, time); + + Assert.Equal(BluetoothAudioLinkOutcome.Succeeded, outcome); + Assert.Equal(2, connector.Requests.Count); + } + + [Fact] + public async Task Connect_DeviceNeverAnswers_TimesOutAfter45Seconds_ResendingEvery10() + { + var connector = new FakeBluetoothAudioConnector { Responds = false }; + var time = new TimerCountingTimeProvider(); + var controller = new BluetoothAudioLinkController(connector, time); + + var pending = controller.ConnectAsync(); + Advance(time, pending, BluetoothAudioLinkController.DefaultTimeout - Poll); + Assert.False(pending.IsCompleted); // a 15 s window proved too short on hardware + + var outcome = await RunToCompletionAsync(pending, time); + + Assert.Equal(BluetoothAudioLinkOutcome.TimedOut, outcome); + Assert.Equal(5, connector.Requests.Count); // t = 0, 10, 20, 30, 40 s + Assert.False(controller.IsBusy); + } + + [Theory] + [InlineData(BluetoothAudioRequestResult.NotFound, BluetoothAudioLinkOutcome.NotFound)] + [InlineData(BluetoothAudioRequestResult.Unsupported, BluetoothAudioLinkOutcome.Unsupported)] + [InlineData(BluetoothAudioRequestResult.Rejected, BluetoothAudioLinkOutcome.Rejected)] + public async Task Connect_RequestNotAccepted_ReturnsMappedOutcomeWithoutWaiting( + BluetoothAudioRequestResult result, BluetoothAudioLinkOutcome expected) + { + var connector = new FakeBluetoothAudioConnector { RequestResult = result }; + var controller = new BluetoothAudioLinkController(connector, new TimerCountingTimeProvider()); + + var pending = controller.ConnectAsync(); + + Assert.True(pending.IsCompleted); + Assert.Equal(expected, await pending); + Assert.Single(connector.Requests); + } + + [Fact] + public async Task Disconnect_Accepted_IsConfirmedByLinkStateGoingDown() + { + var connector = new FakeBluetoothAudioConnector { State = BluetoothAudioLinkState.Connected }; + var time = new TimerCountingTimeProvider(); + var controller = new BluetoothAudioLinkController(connector, time); + + var outcome = await RunToCompletionAsync(controller.DisconnectAsync(), time); + + Assert.Equal(BluetoothAudioLinkOutcome.Succeeded, outcome); + Assert.Equal([BluetoothAudioRequest.Disconnect], connector.Requests); + Assert.Equal(BluetoothAudioLinkState.Disconnected, connector.State); + } + + [Fact] + public async Task Disconnect_AlreadyDisconnected_SendsNothing() + { + var connector = new FakeBluetoothAudioConnector(); + var controller = new BluetoothAudioLinkController(connector, new TimerCountingTimeProvider()); + + var outcome = await controller.DisconnectAsync(); + + Assert.Equal(BluetoothAudioLinkOutcome.AlreadyInState, outcome); + Assert.Empty(connector.Requests); + } + + [Fact] + public async Task ConcurrentCall_WhileInProgress_ReturnsBusyAndSendsNothing() + { + var connector = new FakeBluetoothAudioConnector { Responds = false }; + var time = new TimerCountingTimeProvider(); + var controller = new BluetoothAudioLinkController(connector, time); + + var pending = controller.ConnectAsync(); + var second = await controller.DisconnectAsync(); + + Assert.Equal(BluetoothAudioLinkOutcome.Busy, second); + Assert.True(controller.IsBusy); + Assert.Equal([BluetoothAudioRequest.Connect], connector.Requests); + await RunToCompletionAsync(pending, time); + Assert.False(controller.IsBusy); + } + + [Fact] + public async Task Cancellation_StopsWaitingAndReleasesTheBusyGuard() + { + var connector = new FakeBluetoothAudioConnector { Responds = false }; + var controller = new BluetoothAudioLinkController(connector, new TimerCountingTimeProvider()); + using var cts = new CancellationTokenSource(); + + var pending = controller.ConnectAsync(cts.Token); + await cts.CancelAsync(); + + await Assert.ThrowsAnyAsync(() => pending); + Assert.False(controller.IsBusy); + } + + [Fact] + public void Constructor_NullConnector_Throws() + => Assert.Throws(() => new BluetoothAudioLinkController(null!)); + + private static void Advance(TimerCountingTimeProvider time, Task pending, TimeSpan total) + { + for (var elapsed = TimeSpan.Zero; elapsed < total; elapsed += Poll) + { + time.Step(pending, Poll); + } + } + + private static async Task RunToCompletionAsync( + Task pending, TimerCountingTimeProvider time) + { + for (var step = 0; step < 1000 && !pending.IsCompleted; step++) + { + time.Step(pending, Poll); + } + + return await pending; + } +} diff --git a/tests/PodBridge.Core.Tests/Bluetooth/BluetoothAudioLinkTextTests.cs b/tests/PodBridge.Core.Tests/Bluetooth/BluetoothAudioLinkTextTests.cs new file mode 100644 index 0000000..4f23889 --- /dev/null +++ b/tests/PodBridge.Core.Tests/Bluetooth/BluetoothAudioLinkTextTests.cs @@ -0,0 +1,93 @@ +using PodBridge.Core.Bluetooth; +using PodBridge.Core.Models; +using Xunit; + +namespace PodBridge.Core.Tests.Bluetooth; + +/// +/// Tier-1 tests for the tray's connect/disconnect presentation: when each action is +/// offered, that every failure falls back to Windows Bluetooth settings, and that +/// success messages stay honest. +/// +public class BluetoothAudioLinkTextTests +{ + [Theory] + [InlineData(ConnectionStatus.Unknown, true)] + [InlineData(ConnectionStatus.BluetoothUnavailable, true)] + [InlineData(ConnectionStatus.NoDevice, true)] + [InlineData(ConnectionStatus.Disconnected, true)] + [InlineData(ConnectionStatus.Connected, false)] + public void CanConnect_OfferedUnlessConnected(ConnectionStatus status, bool expected) + => Assert.Equal(expected, BluetoothAudioLinkText.CanConnect(status)); + + [Theory] + [InlineData(ConnectionStatus.Unknown, true)] + [InlineData(ConnectionStatus.BluetoothUnavailable, false)] + [InlineData(ConnectionStatus.NoDevice, false)] + [InlineData(ConnectionStatus.Disconnected, false)] + [InlineData(ConnectionStatus.Connected, true)] + public void CanDisconnect_OfferedWhenConnectedOrUnknown(ConnectionStatus status, bool expected) + => Assert.Equal(expected, BluetoothAudioLinkText.CanDisconnect(status)); + + [Theory] + [InlineData(BluetoothAudioRequest.Connect, BluetoothAudioLinkOutcome.NotFound)] + [InlineData(BluetoothAudioRequest.Connect, BluetoothAudioLinkOutcome.Unsupported)] + [InlineData(BluetoothAudioRequest.Connect, BluetoothAudioLinkOutcome.Rejected)] + [InlineData(BluetoothAudioRequest.Connect, BluetoothAudioLinkOutcome.TimedOut)] + [InlineData(BluetoothAudioRequest.Disconnect, BluetoothAudioLinkOutcome.NotFound)] + [InlineData(BluetoothAudioRequest.Disconnect, BluetoothAudioLinkOutcome.Unsupported)] + [InlineData(BluetoothAudioRequest.Disconnect, BluetoothAudioLinkOutcome.Rejected)] + [InlineData(BluetoothAudioRequest.Disconnect, BluetoothAudioLinkOutcome.TimedOut)] + public void ForOutcome_Failure_FallsBackToBluetoothSettings( + BluetoothAudioRequest request, BluetoothAudioLinkOutcome outcome) + { + var notice = BluetoothAudioLinkText.ForOutcome(request, outcome); + + Assert.NotNull(notice); + Assert.True(notice.OpenBluetoothSettings); + Assert.Contains("Bluetooth settings", notice.Message, StringComparison.Ordinal); + } + + [Theory] + [InlineData(BluetoothAudioRequest.Connect, BluetoothAudioLinkOutcome.Succeeded)] + [InlineData(BluetoothAudioRequest.Connect, BluetoothAudioLinkOutcome.AlreadyInState)] + [InlineData(BluetoothAudioRequest.Disconnect, BluetoothAudioLinkOutcome.Succeeded)] + [InlineData(BluetoothAudioRequest.Disconnect, BluetoothAudioLinkOutcome.AlreadyInState)] + public void ForOutcome_Success_DoesNotOpenSettings( + BluetoothAudioRequest request, BluetoothAudioLinkOutcome outcome) + { + var notice = BluetoothAudioLinkText.ForOutcome(request, outcome); + + Assert.NotNull(notice); + Assert.False(notice.OpenBluetoothSettings); + Assert.False(string.IsNullOrWhiteSpace(notice.Title)); + Assert.False(string.IsNullOrWhiteSpace(notice.Message)); + } + + [Theory] + [InlineData(BluetoothAudioRequest.Connect)] + [InlineData(BluetoothAudioRequest.Disconnect)] + public void ForOutcome_Busy_ShowsNothing(BluetoothAudioRequest request) + => Assert.Null(BluetoothAudioLinkText.ForOutcome(request, BluetoothAudioLinkOutcome.Busy)); + + [Fact] + public void ForOutcome_DisconnectSucceeded_SaysTheyStayPairedAndHowToReconnect() + { + var notice = BluetoothAudioLinkText.ForOutcome( + BluetoothAudioRequest.Disconnect, BluetoothAudioLinkOutcome.Succeeded); + + Assert.NotNull(notice); + Assert.Contains("stay paired", notice.Message, StringComparison.Ordinal); + Assert.Contains(BluetoothAudioLinkText.ConnectLabel, notice.Message, StringComparison.Ordinal); + } + + [Fact] + public void ForOutcome_ConnectTimedOut_GivesAnActionableHint() + { + var notice = BluetoothAudioLinkText.ForOutcome( + BluetoothAudioRequest.Connect, BluetoothAudioLinkOutcome.TimedOut); + + Assert.NotNull(notice); + Assert.Contains("case", notice.Message, StringComparison.Ordinal); + } +} diff --git a/tests/PodBridge.Core.Tests/Bluetooth/FakeBluetoothAudioConnector.cs b/tests/PodBridge.Core.Tests/Bluetooth/FakeBluetoothAudioConnector.cs new file mode 100644 index 0000000..11a95dc --- /dev/null +++ b/tests/PodBridge.Core.Tests/Bluetooth/FakeBluetoothAudioConnector.cs @@ -0,0 +1,46 @@ +using PodBridge.Core.Bluetooth; + +namespace PodBridge.Core.Tests.Bluetooth; + +/// +/// Device-independent stand-in for the Windows Bluetooth audio connector. It records every +/// request and simulates the real driver's behaviour seen on hardware: an accepted request +/// may be silently ignored while a previous link winds down (), +/// or never answered at all ( false, e.g. AirPods still in the closed +/// case). Lets the Tier-1 test gate run with no physical AirPods. +/// +internal sealed class FakeBluetoothAudioConnector : IBluetoothAudioConnector +{ + public BluetoothAudioLinkState State { get; set; } = BluetoothAudioLinkState.Disconnected; + + /// What every returns. + public BluetoothAudioRequestResult RequestResult { get; set; } = BluetoothAudioRequestResult.Accepted; + + /// How many accepted requests are dropped before one changes the link. + public int IgnoredRequests { get; set; } + + /// When false, accepted requests never change the link. + public bool Responds { get; set; } = true; + + public List Requests { get; } = []; + + public BluetoothAudioLinkState GetLinkState() => State; + + public BluetoothAudioRequestResult SendRequest(BluetoothAudioRequest request) + { + Requests.Add(request); + if (RequestResult != BluetoothAudioRequestResult.Accepted) + { + return RequestResult; + } + + if (Responds && Requests.Count > IgnoredRequests) + { + State = request == BluetoothAudioRequest.Connect + ? BluetoothAudioLinkState.Connected + : BluetoothAudioLinkState.Disconnected; + } + + return BluetoothAudioRequestResult.Accepted; + } +} diff --git a/tests/PodBridge.Core.Tests/Bluetooth/TimerCountingTimeProvider.cs b/tests/PodBridge.Core.Tests/Bluetooth/TimerCountingTimeProvider.cs new file mode 100644 index 0000000..8ae5362 --- /dev/null +++ b/tests/PodBridge.Core.Tests/Bluetooth/TimerCountingTimeProvider.cs @@ -0,0 +1,48 @@ +using Microsoft.Extensions.Time.Testing; + +namespace PodBridge.Core.Tests.Bluetooth; + +/// +/// A wrapper that counts the timers the code under test +/// creates. A Task.Delay continuation may resume on the thread pool, so a test that +/// advances the clock in a tight loop could outrun it; waiting for the next timer lets +/// the test advance only once the code is parked on its next delay (exact lock-step). +/// +internal sealed class TimerCountingTimeProvider : TimeProvider +{ + private readonly FakeTimeProvider _inner = new(); + private int _timersCreated; + + public int TimersCreated => Volatile.Read(ref _timersCreated); + + public override long TimestampFrequency => _inner.TimestampFrequency; + + public override TimeZoneInfo LocalTimeZone => _inner.LocalTimeZone; + + public override DateTimeOffset GetUtcNow() => _inner.GetUtcNow(); + + public override long GetTimestamp() => _inner.GetTimestamp(); + + public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period) + { + var timer = _inner.CreateTimer(callback, state, dueTime, period); + Interlocked.Increment(ref _timersCreated); + return timer; + } + + /// + /// Advances by and waits until has + /// either completed or parked on a new timer. + /// + public void Step(Task pending, TimeSpan step) + { + var parked = TimersCreated; + _inner.Advance(step); + var settled = SpinWait.SpinUntil( + () => pending.IsCompleted || TimersCreated != parked, TimeSpan.FromSeconds(10)); + if (!settled) + { + throw new TimeoutException("The code under test neither completed nor parked on a new timer."); + } + } +} diff --git a/tests/PodBridge.Core.Tests/Docs/UserDocsTests.cs b/tests/PodBridge.Core.Tests/Docs/UserDocsTests.cs index fc73a53..659d4f7 100644 --- a/tests/PodBridge.Core.Tests/Docs/UserDocsTests.cs +++ b/tests/PodBridge.Core.Tests/Docs/UserDocsTests.cs @@ -1,4 +1,5 @@ using PodBridge.Core.Audio; +using PodBridge.Core.Bluetooth; using PodBridge.Core.Branding; using Xunit; @@ -103,6 +104,16 @@ public void UserGuide_DocumentsDownloadAndRunPlusVerificationAndAutoStartDefault Assert.Contains("off by default", UserGuide, StringComparison.OrdinalIgnoreCase); } + [Fact] + public void UserGuide_DocumentsOneClickConnectAndDisconnect() + { + Assert.Contains(BluetoothAudioLinkText.ConnectLabel, UserGuide, StringComparison.Ordinal); + Assert.Contains(BluetoothAudioLinkText.DisconnectLabel, UserGuide, StringComparison.Ordinal); + Assert.Contains(BluetoothAudioLinkText.ConnectLabel, Readme, StringComparison.Ordinal); + Assert.DoesNotContain("Pair / Reconnect", UserGuide, StringComparison.Ordinal); + Assert.DoesNotContain("Pair / Reconnect", Readme, StringComparison.Ordinal); + } + [Fact] public void Docs_NeverClaimAppleParitySound() {