Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ protected async Task<byte[]> ReadNativeAsync(CancellationToken cancellationToken

if (args.Status != GattStatus.Success)
{
reject(new CharacteristicReadException($"Read characteristic {Id} failed with GATT status {args.Status}.", Id, Service.Id, (int)args.Status));
reject(new CharacteristicReadException($"Read characteristic {Id} failed with GATT status {args.Status}.", Id, Service.Id, (int)args.Status, (int)args.Status));
return;
}

Expand Down Expand Up @@ -113,7 +113,7 @@ await TaskBuilder.FromEvent<bool, EventHandler<CharacteristicWriteCallbackEventA

if (args.Exception != null)
{
reject(new CharacteristicWriteException($"Write characteristic {Id} failed with GATT status {args.Status}.", Id, Service.Id, (int)args.Status));
reject(new CharacteristicWriteException($"Write characteristic {Id} failed with GATT status {args.Status}.", Id, Service.Id, (int)args.Status, (int)args.Status));
return;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ protected Task<IReadOnlyList<Descriptor>> GetDescriptorsNativeAsync(Cancellation

if (args.Error != null)
{
reject(new CharacteristicReadException($"Discover descriptors error: {args.Error.Description}", Id, Service.Id, (int)args.Error.Code));
reject(new CharacteristicReadException($"Discover descriptors error: {args.Error.Description}", Id, Service.Id, (int)args.Error.Code, args.Error.GetAttStatus()));
}
else
{
Expand Down Expand Up @@ -140,7 +140,7 @@ protected Task<byte[]> ReadNativeAsync(CancellationToken cancellationToken)

if (args.Error != null)
{
reject(new CharacteristicReadException($"Read async error: {args.Error.Description}", Id, Service.Id, (int)args.Error.Code));
reject(new CharacteristicReadException($"Read async error: {args.Error.Description}", Id, Service.Id, (int)args.Error.Code, args.Error.GetAttStatus()));
}
else
{
Expand Down Expand Up @@ -190,7 +190,7 @@ await TaskBuilder.FromEvent<bool, EventHandler<CBCharacteristicEventArgs>, Event
return;

if (args.Error != null)
reject(new CharacteristicWriteException($"Write async error: {args.Error.Description}", Id, Service.Id, (int)args.Error.Code));
reject(new CharacteristicWriteException($"Write async error: {args.Error.Description}", Id, Service.Id, (int)args.Error.Code, args.Error.GetAttStatus()));
else
complete(true);
},
Expand Down Expand Up @@ -295,7 +295,7 @@ protected Task StartUpdatesNativeAsync(CharacteristicUpdateMode mode, Cancellati

if (args.Error != null)
{
reject(new CharacteristicReadException($"Start Notifications: Error {args.Error.Description}", Id, Service.Id, (int)args.Error.Code));
reject(new CharacteristicReadException($"Start Notifications: Error {args.Error.Description}", Id, Service.Id, (int)args.Error.Code, args.Error.GetAttStatus()));
}
else
{
Expand Down Expand Up @@ -338,7 +338,7 @@ protected Task StopUpdatesNativeAsync(CancellationToken cancellationToken)

if (args.Error != null)
{
reject(new CharacteristicReadException($"Stop Notifications: Error {args.Error.Description}", Id, Service.Id, (int)args.Error.Code));
reject(new CharacteristicReadException($"Stop Notifications: Error {args.Error.Description}", Id, Service.Id, (int)args.Error.Code, args.Error.GetAttStatus()));
}
else
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ private void ThrowIfWriteFailed(GattWriteResult result)
$"Write characteristic {Id} failed with status {result.Status}{detail}.",
Id,
Service.Id,
result.ProtocolError,
result.ProtocolError);
}

Expand Down
7 changes: 7 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,13 @@
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.
CharacteristicReadException, CharacteristicWriteException, DescriptorReadException and
DescriptorWriteException carry the GATT status in GattStatus, classified as GattFailure, so an app can
recognise Insufficient Authentication (0x05) and Insufficient Encryption (0x0F) on Android, Apple
platforms and Windows. All four implement IGattStatusException. NativeStatus and messages are unchanged.

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
4 changes: 2 additions & 2 deletions DSoft.System.BluetoothLe/Descriptor/Descriptor.android.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ protected Task WriteNativeAsync(byte[] data, CancellationToken cancellationToken
return;

if (args.Exception != null)
reject(new DescriptorWriteException($"Write descriptor {Id} failed with GATT status {args.Status}.", Id, (int)args.Status));
reject(new DescriptorWriteException($"Write descriptor {Id} failed with GATT status {args.Status}.", Id, (int)args.Status, (int)args.Status));
else
complete(true);
}),
Expand Down Expand Up @@ -71,7 +71,7 @@ protected async Task<byte[]> ReadNativeAsync(CancellationToken cancellationToken

if (args.Exception != null)
{
reject(new DescriptorReadException($"Read descriptor {Id} failed with GATT status {args.Status}.", Id, (int)args.Status));
reject(new DescriptorReadException($"Read descriptor {Id} failed with GATT status {args.Status}.", Id, (int)args.Status, (int)args.Status));
return;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
using System;
using System;
using System.Threading;
using System.Threading.Tasks;
using CoreBluetooth;
using System.BluetoothLe;
using Foundation;
using System.BluetoothLe.Extensions;
using System.BluetoothLe.Utils;

namespace System.BluetoothLe
Expand Down Expand Up @@ -66,7 +67,7 @@ protected Task<byte[]> ReadNativeAsync(CancellationToken cancellationToken)
return;

if (args.Error != null)
reject(new DescriptorReadException($"Read descriptor async error: {args.Error.Description}", Id, (int)args.Error.Code));
reject(new DescriptorReadException($"Read descriptor async error: {args.Error.Description}", Id, (int)args.Error.Code, args.Error.GetAttStatus()));
else
complete(Value);
},
Expand Down Expand Up @@ -102,7 +103,7 @@ protected Task WriteNativeAsync(byte[] data, CancellationToken cancellationToken
return;

if (args.Error != null)
reject(new DescriptorWriteException(args.Error.Description, Id, (int)args.Error.Code));
reject(new DescriptorWriteException(args.Error.Description, Id, (int)args.Error.Code, args.Error.GetAttStatus()));
else
complete(true);
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ protected async Task<byte[]> ReadNativeAsync(CancellationToken cancellationToken
throw new DescriptorReadException(
$"Read descriptor {Id} failed with status {readResult.Status}{ProtocolErrorDetail(readResult.ProtocolError)}.",
Id,
readResult.ProtocolError,
readResult.ProtocolError);
}

Expand All @@ -55,6 +56,7 @@ protected async Task WriteNativeAsync(byte[] data, CancellationToken cancellatio
throw new DescriptorWriteException(
$"Write descriptor {Id} failed with status {result.Status}{ProtocolErrorDetail(result.ProtocolError)}.",
Id,
result.ProtocolError,
result.ProtocolError);
}
}
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 @@ -22,7 +22,7 @@

#region Constructors
internal Device(Adapter adapter, CBPeripheral nativeDevice, IBleCentralManagerDelegate bleCentralManagerDelegate)
: this(adapter, nativeDevice, bleCentralManagerDelegate, nativeDevice.Name, nativeDevice.RSSI?.Int32Value ?? 0, new List<AdvertisementRecord>())

Check warning on line 25 in DSoft.System.BluetoothLe/Devices/Device.ios.mac.tvos.cs

View workflow job for this annotation

GitHub Actions / build

This call site is reachable on: 'tvOS' 15.0 and later. 'CBPeripheral.RSSI' is obsoleted on: 'tvos' 9.0 and later. (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1422)

Check warning on line 25 in DSoft.System.BluetoothLe/Devices/Device.ios.mac.tvos.cs

View workflow job for this annotation

GitHub Actions / build

This call site is reachable on: 'macOS/OSX' 15.0 and later. 'CBPeripheral.RSSI' is obsoleted on: 'macOS/OSX' 10.13 and later. (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1422)

Check warning on line 25 in DSoft.System.BluetoothLe/Devices/Device.ios.mac.tvos.cs

View workflow job for this annotation

GitHub Actions / build

This call site is reachable on: 'MacCatalyst' 15.0 and later. 'CBPeripheral.RSSI' is obsoleted on: 'maccatalyst' 8.0 and later. (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1422)

Check warning on line 25 in DSoft.System.BluetoothLe/Devices/Device.ios.mac.tvos.cs

View workflow job for this annotation

GitHub Actions / build

This call site is reachable on: 'iOS' 15.0 and later, 'maccatalyst' 15.0 and later. 'CBPeripheral.RSSI' is obsoleted on: 'ios' 8.0 and later, 'maccatalyst' 8.0 and later. (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1422)
{

}
Expand Down Expand Up @@ -161,6 +161,11 @@
// 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 Expand Up @@ -200,7 +205,7 @@
// Only overwrite the RSSI when the platform actually gave us one: outside a connection
// CBPeripheral.RSSI is null, and treating that as 0 dBm reports a device as being closer
// than anything real. Read once into a local so this remains a single deprecated call site.
var nativeRssi = nativeDevice.RSSI;

Check warning on line 208 in DSoft.System.BluetoothLe/Devices/Device.ios.mac.tvos.cs

View workflow job for this annotation

GitHub Actions / build

This call site is reachable on: 'macOS/OSX' 15.0 and later. 'CBPeripheral.RSSI' is obsoleted on: 'macOS/OSX' 10.13 and later. (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1422)

Check warning on line 208 in DSoft.System.BluetoothLe/Devices/Device.ios.mac.tvos.cs

View workflow job for this annotation

GitHub Actions / build

This call site is reachable on: 'MacCatalyst' 15.0 and later. 'CBPeripheral.RSSI' is obsoleted on: 'maccatalyst' 8.0 and later. (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1422)

Check warning on line 208 in DSoft.System.BluetoothLe/Devices/Device.ios.mac.tvos.cs

View workflow job for this annotation

GitHub Actions / build

This call site is reachable on: 'iOS' 15.0 and later, 'maccatalyst' 15.0 and later. 'CBPeripheral.RSSI' is obsoleted on: 'ios' 8.0 and later, 'maccatalyst' 8.0 and later. (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1422)
if (nativeRssi != null)
{
Rssi = nativeRssi.Int32Value;
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
Loading
Loading