Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions DSoft.System.BluetoothLe/DSoft.System.BluetoothLe.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
120 changes: 120 additions & 0 deletions DSoft.System.BluetoothLe/Devices/Device.android.cs
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,126 @@ private DeviceBondState GetBondState()
return ToBondState(NativeDevice.BondState);
}

private Task<bool> 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<bool> 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);
}

/// <summary>
/// Calls the hidden <c>BluetoothDevice.removeBond()</c>. Any refusal - the method missing, blocked as a
/// non-SDK interface, or denied for lack of a privileged permission - is reported as false.
/// </summary>
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;
}
}

/// <summary>
/// Starts a bond operation and waits for the adapter to report this device reaching
/// <paramref name="success"/> (true) or <paramref name="failure"/> (false).
/// </summary>
private async Task<bool> AwaitBondOutcomeAsync(Func<bool> start, DeviceBondState success, DeviceBondState? failure, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();

var outcome = new TaskCompletionSource<bool>(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)
Expand Down
5 changes: 5 additions & 0 deletions DSoft.System.BluetoothLe/Devices/Device.ios.mac.tvos.cs
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,11 @@ private Task<bool> 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<bool> CreateBondNativeAsync(CancellationToken cancellationToken) => Task.FromResult(false);

private Task<bool> RemoveBondNativeAsync(CancellationToken cancellationToken) => Task.FromResult(false);

private DeviceState GetState()
{
switch (NativeDevice.State)
Expand Down
4 changes: 4 additions & 0 deletions DSoft.System.BluetoothLe/Devices/Device.netstandard.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ partial void DisposeNative()
// Reported rather than thrown: BondState is documented never to throw.
private DeviceBondState GetBondState() => DeviceBondState.Unknown;

private Task<bool> CreateBondNativeAsync(CancellationToken cancellationToken) => throw new System.PlatformNotSupportedException(NotSupportedMessage);

private Task<bool> RemoveBondNativeAsync(CancellationToken cancellationToken) => throw new System.PlatformNotSupportedException(NotSupportedMessage);

private DeviceState GetState() => throw new System.PlatformNotSupportedException(NotSupportedMessage);

private Task<IReadOnlyList<Service>> GetServicesNativeAsync(CancellationToken cancellationToken) => throw new System.PlatformNotSupportedException(NotSupportedMessage);
Expand Down
73 changes: 73 additions & 0 deletions DSoft.System.BluetoothLe/Devices/Device.shared.cs
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,79 @@ public bool UpdateConnectionInterval(ConnectionInterval interval)
/// <summary>
/// Reads the current RSSI from a connected device and updates <see cref="Rssi"/>.
/// </summary>
/// <summary>
/// Asks the platform to bond (pair) with the device, and completes when bonding finishes.
/// </summary>
/// <param name="cancellationToken">
/// Stops waiting for the outcome. It does not abort bonding the system has already started.
/// </param>
/// <returns>
/// <see langword="true"/> when the device is bonded, including when it already was;
/// <see langword="false"/> when bonding failed or was refused, could not be started, or the platform
/// does not support requesting it.
/// </returns>
/// <remarks>
/// <para>
/// Android only. It calls <c>BluetoothDevice.createBond</c>, which shows the system pairing prompt
/// where the peripheral asks for one, and waits for <see cref="BondState"/> to reach
/// <see cref="DeviceBondState.Bonded"/> or return to <see cref="DeviceBondState.NotBonded"/>. 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 <c>Java.Lang.SecurityException</c>
/// without it. The outcome is observed through <see cref="Adapter.DeviceBondStateChanged"/>.
/// </para>
/// <para>
/// Returns <see langword="false"/> on Apple platforms, which pair on demand and offer no way to
/// request it (see <see cref="BondState"/>), on Windows, and for a stand-in device. Throws
/// <see cref="PlatformNotSupportedException"/> on the platform-neutral targets, as other native
/// members do.
/// </para>
/// </remarks>
/// <exception cref="ObjectDisposedException">The device has been disposed.</exception>
/// <exception cref="OperationCanceledException"><paramref name="cancellationToken"/> was cancelled first.</exception>
public async Task<bool> CreateBondAsync(CancellationToken cancellationToken = default)
{
ThrowIfDisposed();

using (var source = this.GetCombinedSource(cancellationToken))
{
return await CreateBondNativeAsync(source.Token);
}
}

/// <summary>
/// Asks the platform to remove the bond with the device, best effort, and completes when it is gone.
/// </summary>
/// <param name="cancellationToken">Stops waiting for the outcome.</param>
/// <returns>
/// <see langword="true"/> when the device is no longer bonded, including when it was not bonded to
/// begin with; <see langword="false"/> when the platform does not allow the app to remove the bond.
/// </returns>
/// <remarks>
/// <para>
/// <b>Best effort, Android only.</b> Android has no public API for this. The method calls the hidden
/// <c>BluetoothDevice.removeBond</c> 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 <see langword="false"/>, never thrown. When it returns
/// <see langword="false"/>, send the user to the system Bluetooth settings to forget the device.
/// </para>
/// <para>
/// Returns <see langword="false"/> on Apple platforms, where only the user can remove a bond (in
/// Settings), on Windows, and for a stand-in device. Throws <see cref="PlatformNotSupportedException"/>
/// on the platform-neutral targets.
/// </para>
/// </remarks>
/// <exception cref="ObjectDisposedException">The device has been disposed.</exception>
/// <exception cref="OperationCanceledException"><paramref name="cancellationToken"/> was cancelled first.</exception>
public async Task<bool> RemoveBondAsync(CancellationToken cancellationToken = default)
{
ThrowIfDisposed();

using (var source = this.GetCombinedSource(cancellationToken))
{
return await RemoveBondNativeAsync(source.Token);
}
}

public async Task<bool> UpdateRssiAsync(CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
Expand Down
5 changes: 5 additions & 0 deletions DSoft.System.BluetoothLe/Devices/Device.uwp.netcore.netf.cs
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,11 @@ private DeviceBondState GetBondState()
return native.IsPaired ? DeviceBondState.Bonded : DeviceBondState.NotBonded;
}

// Not supported on Windows in this release.
private Task<bool> CreateBondNativeAsync(CancellationToken cancellationToken) => Task.FromResult(false);

private Task<bool> RemoveBondNativeAsync(CancellationToken cancellationToken) => Task.FromResult(false);

private DeviceState GetState()
{
if (NativeDevice.IsConnected)
Expand Down
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand Down