diff --git a/DSoft.System.BluetoothLe/DSoft.System.BluetoothLe.csproj b/DSoft.System.BluetoothLe/DSoft.System.BluetoothLe.csproj index 2f51be4..463afd9 100644 --- a/DSoft.System.BluetoothLe/DSoft.System.BluetoothLe.csproj +++ b/DSoft.System.BluetoothLe/DSoft.System.BluetoothLe.csproj @@ -55,6 +55,9 @@ Adapter.DeviceBondStateChanged is raised when it changes. DeviceBondState gains Unknown, declared last so existing values are unchanged, which Apple platforms always report because CoreBluetooth does not expose bonding. BondStatusBroadcastReceiver is now registered by the Android adapter. + Device.CreateBondAsync and Device.RemoveBondAsync request and remove a bond on Android; removal is + best effort, through a hidden platform method, and reports false where Android refuses it. Both + return false on Apple platforms and Windows. 4.0.1 - restores the stand-in seam that 4.0 removed. Device and Service can again be derived outside the library: protected Device(Guid id, string name, int rssi = 0) replaces the parameterless diff --git a/DSoft.System.BluetoothLe/Devices/Device.android.cs b/DSoft.System.BluetoothLe/Devices/Device.android.cs index 8ce07e8..6ee6281 100644 --- a/DSoft.System.BluetoothLe/Devices/Device.android.cs +++ b/DSoft.System.BluetoothLe/Devices/Device.android.cs @@ -242,6 +242,126 @@ private DeviceBondState GetBondState() return ToBondState(NativeDevice.BondState); } + private Task CreateBondNativeAsync(CancellationToken cancellationToken) + { + if (NativeDevice == null || Adapter == null) + { + return Task.FromResult(false); + } + + var current = ToBondState(NativeDevice.BondState); + + if (current == DeviceBondState.Bonded) + { + return Task.FromResult(true); + } + + // Already bonding - started by the system on access to a protected characteristic, or by an earlier + // call: wait for that rather than asking again, which Android refuses while one is in progress. + var alreadyBonding = current == DeviceBondState.Bonding; + + return AwaitBondOutcomeAsync( + start: () => alreadyBonding || NativeDevice.CreateBond(), + success: DeviceBondState.Bonded, + failure: DeviceBondState.NotBonded, + cancellationToken); + } + + private Task RemoveBondNativeAsync(CancellationToken cancellationToken) + { + if (NativeDevice == null || Adapter == null) + { + return Task.FromResult(false); + } + + if (ToBondState(NativeDevice.BondState) == DeviceBondState.NotBonded) + { + return Task.FromResult(true); + } + + return AwaitBondOutcomeAsync( + start: InvokeRemoveBond, + success: DeviceBondState.NotBonded, + failure: null, + cancellationToken); + } + + /// + /// Calls the hidden BluetoothDevice.removeBond(). Any refusal - the method missing, blocked as a + /// non-SDK interface, or denied for lack of a privileged permission - is reported as false. + /// + private bool InvokeRemoveBond() + { + try + { + var method = NativeDevice.Class.GetMethod("removeBond"); + var result = method.Invoke(NativeDevice); + + return result is Java.Lang.Boolean started && started.BooleanValue(); + } + catch (Exception ex) + { + Trace.Message("Device: removeBond is not available for {0}: {1}", NameOrId, ex.Message); + return false; + } + } + + /// + /// Starts a bond operation and waits for the adapter to report this device reaching + /// (true) or (false). + /// + private async Task AwaitBondOutcomeAsync(Func start, DeviceBondState success, DeviceBondState? failure, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + + var outcome = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + void OnBondStateChanged(object sender, DeviceBondStateChangedEventArgs args) + { + if (args.Device.Id != Id) + { + return; + } + + if (args.State == success) + { + outcome.TrySetResult(true); + } + else if (args.State == failure) + { + outcome.TrySetResult(false); + } + } + + // Subscribed before starting, so a fast outcome cannot be missed. + Adapter.DeviceBondStateChanged += OnBondStateChanged; + + try + { + if (!start()) + { + return false; + } + + // The outcome may already have been reached between reading the state and subscribing. Only the + // success state is checked here: straight after createBond the system can still report NotBonded + // for a moment, and taking that as a failure would end the wait before bonding has begun. + if (ToBondState(NativeDevice.BondState) == success) + { + return true; + } + + using (cancellationToken.Register(() => outcome.TrySetCanceled(cancellationToken))) + { + return await outcome.Task; + } + } + finally + { + Adapter.DeviceBondStateChanged -= OnBondStateChanged; + } + } + internal static DeviceBondState ToBondState(Bond bond) { switch (bond) diff --git a/DSoft.System.BluetoothLe/Devices/Device.ios.mac.tvos.cs b/DSoft.System.BluetoothLe/Devices/Device.ios.mac.tvos.cs index 6e80e7d..886c39b 100644 --- a/DSoft.System.BluetoothLe/Devices/Device.ios.mac.tvos.cs +++ b/DSoft.System.BluetoothLe/Devices/Device.ios.mac.tvos.cs @@ -161,6 +161,11 @@ private Task UpdateRssiNativeAsync(CancellationToken cancellationToken) // time an encrypted characteristic is accessed. private DeviceBondState GetBondState() => DeviceBondState.Unknown; + // Nor can an app request or remove a bond: the OS pairs on demand, and only the user can forget a device. + private Task CreateBondNativeAsync(CancellationToken cancellationToken) => Task.FromResult(false); + + private Task RemoveBondNativeAsync(CancellationToken cancellationToken) => Task.FromResult(false); + private DeviceState GetState() { switch (NativeDevice.State) diff --git a/DSoft.System.BluetoothLe/Devices/Device.netstandard.cs b/DSoft.System.BluetoothLe/Devices/Device.netstandard.cs index e8c0213..5325d02 100644 --- a/DSoft.System.BluetoothLe/Devices/Device.netstandard.cs +++ b/DSoft.System.BluetoothLe/Devices/Device.netstandard.cs @@ -29,6 +29,10 @@ partial void DisposeNative() // Reported rather than thrown: BondState is documented never to throw. private DeviceBondState GetBondState() => DeviceBondState.Unknown; + private Task CreateBondNativeAsync(CancellationToken cancellationToken) => throw new System.PlatformNotSupportedException(NotSupportedMessage); + + private Task RemoveBondNativeAsync(CancellationToken cancellationToken) => throw new System.PlatformNotSupportedException(NotSupportedMessage); + private DeviceState GetState() => throw new System.PlatformNotSupportedException(NotSupportedMessage); private Task> GetServicesNativeAsync(CancellationToken cancellationToken) => throw new System.PlatformNotSupportedException(NotSupportedMessage); diff --git a/DSoft.System.BluetoothLe/Devices/Device.shared.cs b/DSoft.System.BluetoothLe/Devices/Device.shared.cs index 2a5233e..57c56ff 100644 --- a/DSoft.System.BluetoothLe/Devices/Device.shared.cs +++ b/DSoft.System.BluetoothLe/Devices/Device.shared.cs @@ -271,6 +271,79 @@ public bool UpdateConnectionInterval(ConnectionInterval interval) /// /// Reads the current RSSI from a connected device and updates . /// + /// + /// Asks the platform to bond (pair) with the device, and completes when bonding finishes. + /// + /// + /// Stops waiting for the outcome. It does not abort bonding the system has already started. + /// + /// + /// when the device is bonded, including when it already was; + /// when bonding failed or was refused, could not be started, or the platform + /// does not support requesting it. + /// + /// + /// + /// Android only. It calls BluetoothDevice.createBond, which shows the system pairing prompt + /// where the peripheral asks for one, and waits for to reach + /// or return to . If + /// bonding is already in progress it waits for that instead of starting another. On Android 12 and + /// later it needs the BLUETOOTH_CONNECT permission, and throws Java.Lang.SecurityException + /// without it. The outcome is observed through . + /// + /// + /// Returns on Apple platforms, which pair on demand and offer no way to + /// request it (see ), on Windows, and for a stand-in device. Throws + /// on the platform-neutral targets, as other native + /// members do. + /// + /// + /// The device has been disposed. + /// was cancelled first. + public async Task CreateBondAsync(CancellationToken cancellationToken = default) + { + ThrowIfDisposed(); + + using (var source = this.GetCombinedSource(cancellationToken)) + { + return await CreateBondNativeAsync(source.Token); + } + } + + /// + /// Asks the platform to remove the bond with the device, best effort, and completes when it is gone. + /// + /// Stops waiting for the outcome. + /// + /// when the device is no longer bonded, including when it was not bonded to + /// begin with; when the platform does not allow the app to remove the bond. + /// + /// + /// + /// Best effort, Android only. Android has no public API for this. The method calls the hidden + /// BluetoothDevice.removeBond by reflection, which the platform may refuse - newer Android + /// versions restrict it to system apps - and which may stop working in any Android release. Every + /// such refusal is reported as , never thrown. When it returns + /// , send the user to the system Bluetooth settings to forget the device. + /// + /// + /// Returns on Apple platforms, where only the user can remove a bond (in + /// Settings), on Windows, and for a stand-in device. Throws + /// on the platform-neutral targets. + /// + /// + /// The device has been disposed. + /// was cancelled first. + public async Task RemoveBondAsync(CancellationToken cancellationToken = default) + { + ThrowIfDisposed(); + + using (var source = this.GetCombinedSource(cancellationToken)) + { + return await RemoveBondNativeAsync(source.Token); + } + } + public async Task UpdateRssiAsync(CancellationToken cancellationToken = default) { ThrowIfDisposed(); diff --git a/DSoft.System.BluetoothLe/Devices/Device.uwp.netcore.netf.cs b/DSoft.System.BluetoothLe/Devices/Device.uwp.netcore.netf.cs index 3ff527a..262f3c7 100644 --- a/DSoft.System.BluetoothLe/Devices/Device.uwp.netcore.netf.cs +++ b/DSoft.System.BluetoothLe/Devices/Device.uwp.netcore.netf.cs @@ -105,6 +105,11 @@ private DeviceBondState GetBondState() return native.IsPaired ? DeviceBondState.Bonded : DeviceBondState.NotBonded; } + // Not supported on Windows in this release. + private Task CreateBondNativeAsync(CancellationToken cancellationToken) => Task.FromResult(false); + + private Task RemoveBondNativeAsync(CancellationToken cancellationToken) => Task.FromResult(false); + private DeviceState GetState() { if (NativeDevice.IsConnected) diff --git a/README.md b/README.md index 939eef1..d9e2cb3 100644 --- a/README.md +++ b/README.md @@ -221,6 +221,7 @@ await adapter.DisconnectDeviceAsync(device); - `Descriptor.ReadAsync`, `WriteAsync`: interact with descriptors. - `Device.BondState`: the device's bond (pairing) state, as the platform reports it. - `Adapter.DeviceBondStateChanged`: raised on Android when a device's bond state changes. +- `Device.CreateBondAsync`, `RemoveBondAsync`: request or remove a bond on Android. ## Bonding @@ -237,6 +238,15 @@ A peripheral that requires an encrypted link only answers a central it is bonded **Android.** On Android 12 and later, reading the bond state and receiving bond changes both need the `BLUETOOTH_CONNECT` permission. Without it `BondState` reports `Unknown` and the event is not raised. Android, like Apple platforms, normally starts bonding by itself the first time a protected characteristic is accessed; `DeviceBondStateChanged` reports the outcome. +**Requesting and removing a bond (Android).** `Device.CreateBondAsync` starts bonding, showing the system pairing prompt where the peripheral asks for one, and completes with `true` once the device is bonded or `false` if bonding fails or is refused. Use it for an explicit "Pair" action instead of waiting for the first protected operation. `Device.RemoveBondAsync` forgets a stale bond, for example after the peripheral has been factory reset. Android has no public API for removal, so it is **best effort**: it calls a hidden platform method that newer Android versions may refuse, and returns `false` when it cannot remove the bond. In that case, send the user to the system Bluetooth settings. Both methods return `false` on Apple platforms and Windows. A cancellation token stops the wait, but not bonding the system has already started. + +```csharp +if (device.BondState != DeviceBondState.Bonded && !await device.CreateBondAsync(cancellationToken)) +{ + // Not bonded: tell the user to pair, or to forget the device in Settings and try again. +} +``` + `BondState` never throws: it reports `Unknown` wherever the state cannot be read, including for a stand-in device and after the device has been disposed. ## Notes