diff --git a/DSoft.System.BluetoothLe/Characteristic/Characteristic.android.cs b/DSoft.System.BluetoothLe/Characteristic/Characteristic.android.cs index 28dd219..4257a00 100644 --- a/DSoft.System.BluetoothLe/Characteristic/Characteristic.android.cs +++ b/DSoft.System.BluetoothLe/Characteristic/Characteristic.android.cs @@ -69,7 +69,7 @@ protected async Task 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; } @@ -113,7 +113,7 @@ await TaskBuilder.FromEvent> 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 { @@ -140,7 +140,7 @@ protected Task 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 { @@ -190,7 +190,7 @@ await TaskBuilder.FromEvent, 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); }, @@ -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 { @@ -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 { diff --git a/DSoft.System.BluetoothLe/Characteristic/Characteristic.uwp.netcore.netf.cs b/DSoft.System.BluetoothLe/Characteristic/Characteristic.uwp.netcore.netf.cs index c8065db..4a901d1 100644 --- a/DSoft.System.BluetoothLe/Characteristic/Characteristic.uwp.netcore.netf.cs +++ b/DSoft.System.BluetoothLe/Characteristic/Characteristic.uwp.netcore.netf.cs @@ -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); } diff --git a/DSoft.System.BluetoothLe/DSoft.System.BluetoothLe.csproj b/DSoft.System.BluetoothLe/DSoft.System.BluetoothLe.csproj index 2f51be4..ed4d996 100644 --- a/DSoft.System.BluetoothLe/DSoft.System.BluetoothLe.csproj +++ b/DSoft.System.BluetoothLe/DSoft.System.BluetoothLe.csproj @@ -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 diff --git a/DSoft.System.BluetoothLe/Descriptor/Descriptor.android.cs b/DSoft.System.BluetoothLe/Descriptor/Descriptor.android.cs index 7fda782..d43a758 100644 --- a/DSoft.System.BluetoothLe/Descriptor/Descriptor.android.cs +++ b/DSoft.System.BluetoothLe/Descriptor/Descriptor.android.cs @@ -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); }), @@ -71,7 +71,7 @@ protected async Task 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; } diff --git a/DSoft.System.BluetoothLe/Descriptor/Descriptor.ios.mac.tvos.watchos.cs b/DSoft.System.BluetoothLe/Descriptor/Descriptor.ios.mac.tvos.watchos.cs index c9bfe84..92a1cfe 100644 --- a/DSoft.System.BluetoothLe/Descriptor/Descriptor.ios.mac.tvos.watchos.cs +++ b/DSoft.System.BluetoothLe/Descriptor/Descriptor.ios.mac.tvos.watchos.cs @@ -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 @@ -66,7 +67,7 @@ protected Task 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); }, @@ -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); }, diff --git a/DSoft.System.BluetoothLe/Descriptor/Descriptor.uwp.netcore.netf.cs b/DSoft.System.BluetoothLe/Descriptor/Descriptor.uwp.netcore.netf.cs index a89460d..ed1a64e 100644 --- a/DSoft.System.BluetoothLe/Descriptor/Descriptor.uwp.netcore.netf.cs +++ b/DSoft.System.BluetoothLe/Descriptor/Descriptor.uwp.netcore.netf.cs @@ -38,6 +38,7 @@ protected async Task ReadNativeAsync(CancellationToken cancellationToken throw new DescriptorReadException( $"Read descriptor {Id} failed with status {readResult.Status}{ProtocolErrorDetail(readResult.ProtocolError)}.", Id, + readResult.ProtocolError, readResult.ProtocolError); } @@ -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); } } 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/DSoft.System.BluetoothLe/Enums/GattFailure.shared.cs b/DSoft.System.BluetoothLe/Enums/GattFailure.shared.cs new file mode 100644 index 0000000..8be1bc7 --- /dev/null +++ b/DSoft.System.BluetoothLe/Enums/GattFailure.shared.cs @@ -0,0 +1,80 @@ +namespace System.BluetoothLe +{ + /// + /// What a failed GATT operation's status says went wrong, for the statuses an app needs to act on. + /// + /// + /// The raw code is on . The security failures matter most: a + /// peripheral that requires a bonded, encrypted link answers an unbonded central with one of them, and the + /// app should ask the user to pair - or to forget the device and pair again, if the peripheral has lost its + /// keys - rather than report a generic fault. + /// + public enum GattFailure + { + /// + /// No GATT status was reported: the operation could not be started, the device disconnected, or the + /// platform failed it for a reason of its own. + /// + None, + + /// A GATT status that is none of the others. Inspect . + Other, + + /// ATT error 0x05, Insufficient Authentication: the link must be authenticated (bonded) first. + InsufficientAuthentication, + + /// ATT error 0x08, Insufficient Authorization: the peripheral refuses this central the operation. + InsufficientAuthorization, + + /// ATT error 0x0F, Insufficient Encryption: the link must be encrypted first. + InsufficientEncryption + } + + /// + /// A failed read or write that can carry the GATT status the peripheral or the platform's GATT layer + /// reported. Implemented by , , + /// and , so one catch can recognise a + /// security failure from any of them. + /// + /// + /// + /// catch (BleException ex) when (ex is IGattStatusException { GattFailure: GattFailure.InsufficientAuthentication or GattFailure.InsufficientEncryption }) + /// { + /// // Ask the user to pair. + /// } + /// + /// + public interface IGattStatusException + { + /// + /// The GATT status code, where one was reported: on Android the GattStatus from the callback, on + /// Apple platforms the CBATTError code when the error is in CBATTErrorDomain, and on Windows + /// the protocol error. ATT error codes have the same value on every platform; Android can also report + /// codes of its own GATT layer, such as 0x85. when no status was reported. + /// + int? GattStatus { get; } + + /// , classified. + GattFailure GattFailure { get; } + } + + internal static class GattStatusCodes + { + public static GattFailure Classify(int? gattStatus) + { + switch (gattStatus) + { + case null: + return GattFailure.None; + case 0x05: + return GattFailure.InsufficientAuthentication; + case 0x08: + return GattFailure.InsufficientAuthorization; + case 0x0F: + return GattFailure.InsufficientEncryption; + default: + return GattFailure.Other; + } + } + } +} diff --git a/DSoft.System.BluetoothLe/Exceptions/CharacteristicReadException.shared.cs b/DSoft.System.BluetoothLe/Exceptions/CharacteristicReadException.shared.cs index 9e38400..a7fb399 100644 --- a/DSoft.System.BluetoothLe/Exceptions/CharacteristicReadException.shared.cs +++ b/DSoft.System.BluetoothLe/Exceptions/CharacteristicReadException.shared.cs @@ -5,7 +5,7 @@ namespace System.BluetoothLe /// /// Thrown when reading a characteristic, or enabling notifications on one, fails. /// - public class CharacteristicReadException : BleException + public class CharacteristicReadException : BleException, IGattStatusException { /// The characteristic the operation was attempted on, where it is known. public Guid CharacteristicId { get; } @@ -19,6 +19,14 @@ public class CharacteristicReadException : BleException /// public int? NativeStatus { get; } + /// + /// Separate from , which keeps its earlier meaning: on Apple platforms + /// that is the NSError code whatever its domain, while this is set only for ATT errors. + public int? GattStatus { get; } + + /// + public GattFailure GattFailure => GattStatusCodes.Classify(GattStatus); + /// public CharacteristicReadException(string message) : base(message) { @@ -35,5 +43,19 @@ public CharacteristicReadException(string message, Guid characteristicId, Guid s ServiceId = serviceId; NativeStatus = nativeStatus; } + + /// + /// Creates the exception with the platform status and the GATT status attached. + /// + /// The message, unchanged from the earlier constructors. + /// The characteristic, as . + /// The owning service, as . + /// The raw platform status, as . + /// The GATT status, as . + public CharacteristicReadException(string message, Guid characteristicId, Guid serviceId, int? nativeStatus, int? gattStatus) + : this(message, characteristicId, serviceId, nativeStatus) + { + GattStatus = gattStatus; + } } } diff --git a/DSoft.System.BluetoothLe/Exceptions/CharacteristicWriteException.shared.cs b/DSoft.System.BluetoothLe/Exceptions/CharacteristicWriteException.shared.cs index 5b5caea..d545005 100644 --- a/DSoft.System.BluetoothLe/Exceptions/CharacteristicWriteException.shared.cs +++ b/DSoft.System.BluetoothLe/Exceptions/CharacteristicWriteException.shared.cs @@ -10,7 +10,7 @@ namespace System.BluetoothLe /// WriteAsync with no reason attached, while Android threw /// from the write path. Both are now this type on every platform. /// - public class CharacteristicWriteException : BleException + public class CharacteristicWriteException : BleException, IGattStatusException { /// The characteristic the write was attempted on, where it is known. public Guid CharacteristicId { get; } @@ -24,6 +24,14 @@ public class CharacteristicWriteException : BleException /// public int? NativeStatus { get; } + /// + /// Separate from , which keeps its earlier meaning: on Apple platforms + /// that is the NSError code whatever its domain, while this is set only for ATT errors. + public int? GattStatus { get; } + + /// + public GattFailure GattFailure => GattStatusCodes.Classify(GattStatus); + /// public CharacteristicWriteException(string message) : base(message) { @@ -40,5 +48,19 @@ public CharacteristicWriteException(string message, Guid characteristicId, Guid ServiceId = serviceId; NativeStatus = nativeStatus; } + + /// + /// Creates the exception with the platform status and the GATT status attached. + /// + /// The message, unchanged from the earlier constructors. + /// The characteristic, as . + /// The owning service, as . + /// The raw platform status, as . + /// The GATT status, as . + public CharacteristicWriteException(string message, Guid characteristicId, Guid serviceId, int? nativeStatus, int? gattStatus) + : this(message, characteristicId, serviceId, nativeStatus) + { + GattStatus = gattStatus; + } } } diff --git a/DSoft.System.BluetoothLe/Exceptions/DescriptorReadException.shared.cs b/DSoft.System.BluetoothLe/Exceptions/DescriptorReadException.shared.cs index d05ab3d..139ecbb 100644 --- a/DSoft.System.BluetoothLe/Exceptions/DescriptorReadException.shared.cs +++ b/DSoft.System.BluetoothLe/Exceptions/DescriptorReadException.shared.cs @@ -5,7 +5,7 @@ namespace System.BluetoothLe /// /// Thrown when reading a descriptor fails. /// - public class DescriptorReadException : BleException + public class DescriptorReadException : BleException, IGattStatusException { /// The descriptor the read was attempted on, where it is known. public Guid DescriptorId { get; } @@ -13,6 +13,14 @@ public class DescriptorReadException : BleException /// The raw platform status code, where the platform supplied one. public int? NativeStatus { get; } + /// + /// Separate from , which keeps its earlier meaning: on Apple platforms + /// that is the NSError code whatever its domain, while this is set only for ATT errors. + public int? GattStatus { get; } + + /// + public GattFailure GattFailure => GattStatusCodes.Classify(GattStatus); + /// public DescriptorReadException(string message) : base(message) { @@ -24,5 +32,18 @@ public DescriptorReadException(string message, Guid descriptorId, int? nativeSta DescriptorId = descriptorId; NativeStatus = nativeStatus; } + + /// + /// Creates the exception with the platform status and the GATT status attached. + /// + /// The message, unchanged from the earlier constructors. + /// The descriptor, as . + /// The raw platform status, as . + /// The GATT status, as . + public DescriptorReadException(string message, Guid descriptorId, int? nativeStatus, int? gattStatus) + : this(message, descriptorId, nativeStatus) + { + GattStatus = gattStatus; + } } } diff --git a/DSoft.System.BluetoothLe/Exceptions/DescriptorWriteException.shared.cs b/DSoft.System.BluetoothLe/Exceptions/DescriptorWriteException.shared.cs index 4c2fb7e..1a738f7 100644 --- a/DSoft.System.BluetoothLe/Exceptions/DescriptorWriteException.shared.cs +++ b/DSoft.System.BluetoothLe/Exceptions/DescriptorWriteException.shared.cs @@ -7,7 +7,7 @@ namespace System.BluetoothLe /// characteristic configuration descriptor, so this is the failure a consumer sees when a subscription /// cannot be established. /// - public class DescriptorWriteException : BleException + public class DescriptorWriteException : BleException, IGattStatusException { /// The descriptor the write was attempted on, where it is known. public Guid DescriptorId { get; } @@ -15,6 +15,14 @@ public class DescriptorWriteException : BleException /// The raw platform status code, where the platform supplied one. public int? NativeStatus { get; } + /// + /// Separate from , which keeps its earlier meaning: on Apple platforms + /// that is the NSError code whatever its domain, while this is set only for ATT errors. + public int? GattStatus { get; } + + /// + public GattFailure GattFailure => GattStatusCodes.Classify(GattStatus); + /// public DescriptorWriteException(string message) : base(message) { @@ -26,5 +34,18 @@ public DescriptorWriteException(string message, Guid descriptorId, int? nativeSt DescriptorId = descriptorId; NativeStatus = nativeStatus; } + + /// + /// Creates the exception with the platform status and the GATT status attached. + /// + /// The message, unchanged from the earlier constructors. + /// The descriptor, as . + /// The raw platform status, as . + /// The GATT status, as . + public DescriptorWriteException(string message, Guid descriptorId, int? nativeStatus, int? gattStatus) + : this(message, descriptorId, nativeStatus) + { + GattStatus = gattStatus; + } } } diff --git a/DSoft.System.BluetoothLe/Extensions/GattResultExtensions.uwp.netcore.netf.cs b/DSoft.System.BluetoothLe/Extensions/GattResultExtensions.uwp.netcore.netf.cs index 49d626e..71f7983 100644 --- a/DSoft.System.BluetoothLe/Extensions/GattResultExtensions.uwp.netcore.netf.cs +++ b/DSoft.System.BluetoothLe/Extensions/GattResultExtensions.uwp.netcore.netf.cs @@ -26,7 +26,8 @@ public static byte[] GetValueOrThrowIfError(this GattReadResult result, [CallerM var errorMessage = result.Status.GetErrorMessage(tag, result.ProtocolError); if (!string.IsNullOrEmpty(errorMessage)) { - throw new CharacteristicReadException(errorMessage); + // The message is unchanged; the ATT protocol error, where Windows reported one, is now attached. + throw new CharacteristicReadException(errorMessage, Guid.Empty, Guid.Empty, result.ProtocolError, result.ProtocolError); } return result.Value?.ToArray() ?? Array.Empty(); diff --git a/DSoft.System.BluetoothLe/Extensions/NSErrorExtensions.ios.mac.tvos.watchos.cs b/DSoft.System.BluetoothLe/Extensions/NSErrorExtensions.ios.mac.tvos.watchos.cs new file mode 100644 index 0000000..6ba2414 --- /dev/null +++ b/DSoft.System.BluetoothLe/Extensions/NSErrorExtensions.ios.mac.tvos.watchos.cs @@ -0,0 +1,26 @@ +using Foundation; + +namespace System.BluetoothLe.Extensions +{ + internal static class NSErrorExtensions + { + // The value of CoreBluetooth's CBATTErrorDomain constant. Compared as a string so this does not depend on + // how the binding surfaces the constant. + private const string AttErrorDomain = "CBATTErrorDomain"; + + /// + /// The ATT error code carried by when it is a CBATTError, which shares its + /// values with the ATT specification; for an error in any other domain, such as a + /// CBError, whose codes mean something else. + /// + public static int? GetAttStatus(this NSError error) + { + if (error == null || error.Domain != AttErrorDomain) + { + return null; + } + + return (int)error.Code; + } + } +} diff --git a/README.md b/README.md index 939eef1..dc3894e 100644 --- a/README.md +++ b/README.md @@ -221,6 +221,8 @@ 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. +- `IGattStatusException.GattStatus`, `GattFailure`: the GATT status on a failed read or write. +- `Device.CreateBondAsync`, `RemoveBondAsync`: request or remove a bond on Android. ## Bonding @@ -237,6 +239,30 @@ 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. +} +``` + +**Recognising a security failure.** A peripheral that requires a bonded, encrypted link refuses an unbonded central with ATT error Insufficient Authentication (0x05) or Insufficient Encryption (0x0F). The read and write exceptions (`CharacteristicReadException`, `CharacteristicWriteException`, `DescriptorReadException` and `DescriptorWriteException`) carry that status in `GattStatus`, classified in `GattFailure`, on Android, Apple platforms and Windows. All four implement `IGattStatusException`, so one catch covers them: + +```csharp +try +{ + await characteristic.WriteAsync(data, cancellationToken); +} +catch (BleException ex) when (ex is IGattStatusException { GattFailure: GattFailure.InsufficientAuthentication or GattFailure.InsufficientEncryption }) +{ + // Ask the user to pair, or to forget the device in Settings and pair again. +} +``` + +Subscribing with `StartUpdatesAsync` fails as a `DescriptorWriteException` on Android, where it writes the configuration descriptor itself, and as a `CharacteristicReadException` on Apple platforms. `GattStatus` is `null`, and `GattFailure` is `None`, when no GATT status was reported: the operation could not start, the device disconnected, or on Apple platforms the error was not an ATT error. `NativeStatus` and the exception messages are unchanged. + `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