diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 5dd5fe9..0a7284e 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,5 +1,5 @@ # Release: on every push to main, builds Release and pushes the DSoft.*.nupkg -# package (with its .snupkg symbols) to nuget.org as 4.0.yyMM., then +# package (with its .snupkg symbols) to nuget.org as 4.1.yyMM., then # tags the commit and creates a GitHub release with the package attached. # RELEASE_SUFFIX is empty for a stable version; set it to a suffix such as # '-prerelease' to publish a prerelease. @@ -45,7 +45,7 @@ jobs: # The run number is offset by 100 so the first GitHub release sorts above 4.0.2610.91, the # last version Azure Pipelines published. The run number never resets, so the offset is # permanent and harmless. - version="4.0.$(date -u +%y%m).$(( ${{ github.run_number }} + 100 ))" + version="4.1.$(date -u +%y%m).$(( ${{ github.run_number }} + 100 ))" echo "version=$version" >> "$GITHUB_OUTPUT" echo "package=$version$RELEASE_SUFFIX" >> "$GITHUB_OUTPUT" echo "Version: $version$RELEASE_SUFFIX" diff --git a/DSoft.System.BluetoothLe/Adapter/Adapter.android.cs b/DSoft.System.BluetoothLe/Adapter/Adapter.android.cs index 0db5be8..1d4a607 100644 --- a/DSoft.System.BluetoothLe/Adapter/Adapter.android.cs +++ b/DSoft.System.BluetoothLe/Adapter/Adapter.android.cs @@ -5,7 +5,9 @@ using System.Threading.Tasks; using Android.Bluetooth; using Android.Bluetooth.LE; +using Android.Content; using Android.OS; +using System.BluetoothLe.BroadcastReceivers; using System.BluetoothLe.Extensions; using Trace = System.BluetoothLe.Trace; @@ -24,18 +26,65 @@ internal Adapter(BluetoothManager bluetoothManager) _bluetoothManager = bluetoothManager; _bluetoothAdapter = bluetoothManager?.Adapter; - // TODO: bonding - //var bondStatusBroadcastReceiver = new BondStatusBroadcastReceiver(); - //Application.Context.RegisterReceiver(bondStatusBroadcastReceiver, - // new IntentFilter(BluetoothDevice.ActionBondStateChanged)); + _api21ScanCallback = new Api21BleScanCallback(this); - ////forward events from broadcast receiver - //bondStatusBroadcastReceiver.BondStateChanged += (s, args) => - //{ - // //DeviceBondStateChanged(this, args); - //}; + RegisterBondStateReceiver(); + } - _api21ScanCallback = new Api21BleScanCallback(this); + private BondStatusBroadcastReceiver _bondStatusReceiver; + + private void RegisterBondStateReceiver() + { + // No adapter means no Bluetooth hardware: there will be no bond changes to report. + if (_bluetoothAdapter == null) + { + return; + } + + try + { + var receiver = new BondStatusBroadcastReceiver(this); + var filter = new IntentFilter(BluetoothDevice.ActionBondStateChanged); + + // From API 33 a context-registered receiver must say whether other apps may send to it. This one + // receives only a protected system broadcast, which is delivered to a non-exported receiver. + if (OperatingSystem.IsAndroidVersionAtLeast(33)) + { + Android.App.Application.Context.RegisterReceiver(receiver, filter, ReceiverFlags.NotExported); + } + else + { + Android.App.Application.Context.RegisterReceiver(receiver, filter); + } + + _bondStatusReceiver = receiver; + } + catch (Exception ex) + { + // Bond state changes are an addition to the adapter, not a condition of it working. + Trace.Message("Adapter: Registering for bond state changes failed: {0}", ex.Message); + } + } + + /// + /// The device for : the instance this adapter already tracks - connected + /// first, then discovered - or a new one when it tracks none. + /// + internal Device ResolveDevice(BluetoothDevice nativeDevice) + { + var id = Device.ParseDeviceId(nativeDevice.Address); + + if (TryGetConnectedDevice(id, out var connected)) + { + return connected; + } + + if (DiscoveredDevicesRegistry.TryGetValue(id, out var discovered)) + { + return discovered; + } + + return new Device(this, nativeDevice, null, 0); } protected Task StartScanningForDevicesNativeAsync(Guid[] serviceUuids, bool allowDuplicatesKey, CancellationToken scanCancellationToken) @@ -205,6 +254,23 @@ public IReadOnlyList GetSystemConnectedOrPairedDevices(Guid[] services = partial void DisposeNative() { + var bondStatusReceiver = _bondStatusReceiver; + _bondStatusReceiver = null; + + if (bondStatusReceiver != null) + { + try + { + Android.App.Application.Context.UnregisterReceiver(bondStatusReceiver); + } + catch (Exception ex) + { + Trace.Message("Adapter: Unregistering the bond state receiver failed: {0}", ex.Message); + } + + bondStatusReceiver.Dispose(); + } + try { _bluetoothAdapter?.BluetoothLeScanner?.StopScan(_api21ScanCallback); diff --git a/DSoft.System.BluetoothLe/Adapter/Adapter.shared.cs b/DSoft.System.BluetoothLe/Adapter/Adapter.shared.cs index edf5db3..e16f1ed 100644 --- a/DSoft.System.BluetoothLe/Adapter/Adapter.shared.cs +++ b/DSoft.System.BluetoothLe/Adapter/Adapter.shared.cs @@ -96,6 +96,25 @@ public partial class Adapter : IDisposable /// public event EventHandler ScanFailed; + /// + /// Raised when the system reports that a device's bond (pairing) state has changed: bonding started, + /// the device bonded, or the bond was removed or failed. + /// + /// + /// + /// Raised on Android only, on the main thread, for every Bluetooth device the system reports - including + /// devices this adapter has not discovered, and changes made outside the app, for example in the system + /// Bluetooth settings. The device in the arguments is the instance this adapter already tracks where + /// there is one, so its change is also raised through + /// . On Android 12 and later the system delivers the change only to + /// an app holding the BLUETOOTH_CONNECT permission. + /// + /// + /// Never raised on Apple platforms, which do not expose bonding, or on Windows. + /// + /// + public event EventHandler DeviceBondStateChanged; + #endregion #region Properties @@ -567,6 +586,18 @@ internal void HandleDisconnectedDevice(bool disconnectRequested, Device device) } } + /// + /// Reports a bond state change for : raises + /// for , then . + /// + internal void HandleBondStateChanged(Device device, DeviceBondState state) + { + Trace.Message("Adapter: Bond state of {0} changed to {1}", device.NameOrId, state); + + device.RaiseBondStateChanged(); + Raise(DeviceBondStateChanged, new DeviceBondStateChangedEventArgs(device, state), nameof(DeviceBondStateChanged)); + } + internal void HandleConnectionFail(Device device, string errorMessage) { Trace.Message("Failed to connect peripheral {0}: {1}", device.Id, device.NameOrId); 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 b101dab..ad3e74b 100644 --- a/DSoft.System.BluetoothLe/DSoft.System.BluetoothLe.csproj +++ b/DSoft.System.BluetoothLe/DSoft.System.BluetoothLe.csproj @@ -33,7 +33,7 @@ - 4.0.1 + 4.1.0 4.0.0.0 DSoft.System.BluetoothLe DSoft.System.BluetoothLe @@ -51,6 +51,18 @@ BluetoothLe dotnet android ios macos maccatalyst windows wpf netstandard tvos Copyright © 2026 DSoft + 4.1 - adds bonding and the GATT status on failures. Device.BondState reports a device's bond (pairing) state, and on Android + 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 protected Device() that 3.x exposed, and Service(Device) is protected again. Device.Id stays 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 ace76a4..6ee6281 100644 --- a/DSoft.System.BluetoothLe/Devices/Device.android.cs +++ b/DSoft.System.BluetoothLe/Devices/Device.android.cs @@ -61,10 +61,16 @@ internal Device(Adapter adapter, BluetoothDevice nativeDevice, BluetoothGatt gat #region Methods #region Private - private Guid ParseDeviceId() + private Guid ParseDeviceId() => ParseDeviceId(NativeDevice.Address); + + /// + /// The id a device with this MAC address is given: the address in the last six bytes of an otherwise + /// zero GUID. Shared with the adapter, which has only an address when the system reports a bond change. + /// + internal static Guid ParseDeviceId(string address) { var deviceGuid = new byte[16]; - var macWithoutColons = NativeDevice.Address.Replace(":", ""); + var macWithoutColons = address.Replace(":", ""); var macBytes = Enumerable.Range(0, macWithoutColons.Length) .Where(x => x % 2 == 0) .Select(x => Convert.ToByte(macWithoutColons.Substring(x, 2), 16)) @@ -223,6 +229,154 @@ private DeviceState GetState() } } + private DeviceBondState GetBondState() + { + // No native device: a stand-in built through the protected constructor. + if (NativeDevice == null) + { + return DeviceBondState.Unknown; + } + + // Throws SecurityException on Android 12 and later without BLUETOOTH_CONNECT; BondState reports + // that as Unknown. + 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) + { + case Bond.None: + return DeviceBondState.NotBonded; + case Bond.Bonding: + return DeviceBondState.Bonding; + case Bond.Bonded: + return DeviceBondState.Bonded; + default: + return DeviceBondState.Unknown; + } + } + private async Task UpdateRssiNativeAsync(CancellationToken cancellationToken) { if (_gatt == null || _gattCallback == null) diff --git a/DSoft.System.BluetoothLe/Devices/Device.ios.mac.tvos.cs b/DSoft.System.BluetoothLe/Devices/Device.ios.mac.tvos.cs index a236f08..886c39b 100644 --- a/DSoft.System.BluetoothLe/Devices/Device.ios.mac.tvos.cs +++ b/DSoft.System.BluetoothLe/Devices/Device.ios.mac.tvos.cs @@ -157,6 +157,15 @@ private Task UpdateRssiNativeAsync(CancellationToken cancellationToken) token: cancellationToken); } + // CoreBluetooth has no API for the bond state: pairing happens on demand, driven by the OS, the first + // 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 88db689..5325d02 100644 --- a/DSoft.System.BluetoothLe/Devices/Device.netstandard.cs +++ b/DSoft.System.BluetoothLe/Devices/Device.netstandard.cs @@ -26,6 +26,13 @@ partial void DisposeNative() private Task UpdateRssiNativeAsync(CancellationToken cancellationToken) => throw new System.PlatformNotSupportedException(NotSupportedMessage); + // 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 609b7d8..57c56ff 100644 --- a/DSoft.System.BluetoothLe/Devices/Device.shared.cs +++ b/DSoft.System.BluetoothLe/Devices/Device.shared.cs @@ -91,6 +91,48 @@ public DeviceState State } } + /// + /// Gets the bond (pairing) state of the device, as the platform reports it now. + /// + /// + /// + /// Android reads it from the system on every call. Windows reports + /// or from the device's pairing information, and never + /// . Apple platforms always report + /// : CoreBluetooth pairs on demand, the first time an encrypted + /// characteristic is accessed, and does not let an app ask whether a bond exists. + /// + /// + /// is also reported where the state cannot be read - on Android 12 + /// and later without the BLUETOOTH_CONNECT permission, on a target without Bluetooth, for a stand-in + /// device, and once the device has been disposed. Reading this property never throws. + /// + /// + /// On Android, reports changes, and + /// is raised for this property on the instance the adapter tracks. + /// + /// + public DeviceBondState BondState + { + get + { + if (_isDisposed) + { + return DeviceBondState.Unknown; + } + + try + { + return GetBondState(); + } + catch (Exception ex) + { + Trace.Message("Device: Reading the bond state of {0} failed: {1}", NameOrId, ex.Message); + return DeviceBondState.Unknown; + } + } + } + /// /// Gets whether this instance has ever completed a connection. /// @@ -229,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(); @@ -339,6 +454,12 @@ protected virtual void Dispose(bool disposing) /// internal void RaiseStateChanged() => NotifyPropertyChanged(nameof(State)); + /// + /// Raises for . The platform announces bond + /// changes system-wide, so the adapter has to drive the notification. + /// + internal void RaiseBondStateChanged() => NotifyPropertyChanged(nameof(BondState)); + #endregion #region Private Methods diff --git a/DSoft.System.BluetoothLe/Devices/Device.uwp.netcore.netf.cs b/DSoft.System.BluetoothLe/Devices/Device.uwp.netcore.netf.cs index 3272d0e..262f3c7 100644 --- a/DSoft.System.BluetoothLe/Devices/Device.uwp.netcore.netf.cs +++ b/DSoft.System.BluetoothLe/Devices/Device.uwp.netcore.netf.cs @@ -92,6 +92,24 @@ private async Task> GetServicesNativeAsync(CancellationTo .ToList(); } + // Windows exposes whether the device is paired, but not a pairing in progress. + private DeviceBondState GetBondState() + { + var native = NativeDevice; + + if (native == null) + { + return DeviceBondState.Unknown; + } + + 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/DeviceBondState.shared.cs b/DSoft.System.BluetoothLe/Enums/DeviceBondState.shared.cs index bab5f85..723afd2 100644 --- a/DSoft.System.BluetoothLe/Enums/DeviceBondState.shared.cs +++ b/DSoft.System.BluetoothLe/Enums/DeviceBondState.shared.cs @@ -1,9 +1,26 @@ namespace System.BluetoothLe { + /// + /// The bond (pairing) state of a device, as the platform reports it. + /// public enum DeviceBondState { + /// The platform reports that the device is not bonded. NotBonded, + + /// Bonding with the device is in progress. Bonding, - Bonded + + /// The device is bonded: the platform holds keys for an encrypted link to it. + Bonded, + + /// + /// The platform does not expose the bond state. Apple platforms always report this: CoreBluetooth + /// pairs on demand, the first time an encrypted characteristic is accessed, and offers no way to ask + /// whether a bond exists. Also reported where the state cannot be read, for example on Android 12 and + /// later without the BLUETOOTH_CONNECT permission, and for a stand-in device. + /// + /// Declared last so the values of the existing members are unchanged. + Unknown } -} \ No newline at end of file +} 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/DSoft.System.BluetoothLe/Platform/Android/BondStatusBroadcastReceiver.android.cs b/DSoft.System.BluetoothLe/Platform/Android/BondStatusBroadcastReceiver.android.cs index 791c33d..331de17 100644 --- a/DSoft.System.BluetoothLe/Platform/Android/BondStatusBroadcastReceiver.android.cs +++ b/DSoft.System.BluetoothLe/Platform/Android/BondStatusBroadcastReceiver.android.cs @@ -3,38 +3,87 @@ using Android.Content; using System.BluetoothLe; using System.BluetoothLe.EventArgs; +using Trace = System.BluetoothLe.Trace; namespace System.BluetoothLe.BroadcastReceivers { - //[BroadcastReceiver] + /// + /// Receives the system's broadcast and reports it as a + /// . + /// + /// + /// The registers one of these for its lifetime and raises + /// from it, so an app does not need to register its own. + /// public class BondStatusBroadcastReceiver : BroadcastReceiver { + private readonly Adapter _adapter; + + /// + /// Raised for every bond state change the system broadcasts, on the main thread. + /// public event EventHandler BondStateChanged; - public override void OnReceive(Context context, Intent intent) + /// + /// Creates a receiver that resolves devices through 's adapter. + /// + public BondStatusBroadcastReceiver() { - var bondState = (Bond)intent.GetIntExtra(BluetoothDevice.ExtraBondState, (int)Bond.None); - //ToDo - var device = new Device(null, (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice), null, 0); - Console.WriteLine(bondState.ToString()); + } - if (BondStateChanged == null) return; + /// + /// Creates a receiver that resolves devices through and reports each change to it. + /// + internal BondStatusBroadcastReceiver(Adapter adapter) + { + _adapter = adapter ?? throw new ArgumentNullException(nameof(adapter)); + } - switch (bondState) + /// + public override void OnReceive(Context context, Intent intent) + { + // OnReceive is called from the main looper: an exception escaping it terminates the process. + try { - case Bond.None: - BondStateChanged(this, new DeviceBondStateChangedEventArgs(device, DeviceBondState.NotBonded)); - break; + if (intent?.Action != BluetoothDevice.ActionBondStateChanged) + { + return; + } - case Bond.Bonding: - BondStateChanged(this, new DeviceBondStateChangedEventArgs(device, DeviceBondState.Bonding)); - break; +#pragma warning disable CA1422 // The typed overload is API 33+; the untyped one is the only one available below that. + var nativeDevice = OperatingSystem.IsAndroidVersionAtLeast(33) + ? (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice, Java.Lang.Class.FromType(typeof(BluetoothDevice))) + : (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice); +#pragma warning restore CA1422 - case Bond.Bonded: - BondStateChanged(this, new DeviceBondStateChangedEventArgs(device, DeviceBondState.Bonded)); - break; + if (nativeDevice == null) + { + return; + } + var bond = (Bond)intent.GetIntExtra(BluetoothDevice.ExtraBondState, (int)Bond.None); + var state = Device.ToBondState(bond); + + var adapter = _adapter ?? BluetoothLE.Current.Adapter; + if (adapter == null) + { + Trace.Message("BondStatusBroadcastReceiver: No adapter is available to report the bond state change for {0}.", nativeDevice.Address); + return; + } + + var device = adapter.ResolveDevice(nativeDevice); + + if (_adapter != null) + { + _adapter.HandleBondStateChanged(device, state); + } + + BondStateChanged?.Invoke(this, new DeviceBondStateChangedEventArgs(device, state)); + } + catch (Exception ex) + { + Trace.Message("BondStatusBroadcastReceiver: Handling a bond state change failed: {0}", ex); } } } -} \ No newline at end of file +} diff --git a/README.md b/README.md index 05071ea..b0bf55a 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ The library started as a fork/repackage of [Plugin.BLE](https://github.com/dotne Reference the package from your app project: ```xml - + ``` When working from source, reference the project: @@ -219,6 +219,51 @@ await adapter.DisconnectDeviceAsync(device); - `Service.GetCharacteristicsAsync`: discover GATT characteristics. - `Characteristic.ReadAsync`, `WriteAsync`, `StartUpdatesAsync`, `StopUpdatesAsync`: interact with characteristic values. - `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 + +A peripheral that requires an encrypted link only answers a central it is bonded (paired) with. What an app can see of that bond depends on the platform. + +| Platform | `Device.BondState` | `Adapter.DeviceBondStateChanged` | +| --- | --- | --- | +| Android | `NotBonded`, `Bonding` or `Bonded`, read from the system on every call | Raised on the main thread for every bond change the system broadcasts, including changes made in the system Bluetooth settings | +| iOS, macOS, Mac Catalyst, tvOS | Always `Unknown` | Never raised | +| Windows | `Bonded` or `NotBonded`, from the device's pairing information | Never raised | +| `net10.0` / `netstandard2.0` | Always `Unknown` | Never raised | + +**Apple platforms.** CoreBluetooth gives an app no way to read or request a bond. The operating system pairs on demand: the first time the app reads, writes or subscribes to a characteristic the peripheral protects, iOS shows the pairing prompt itself, and once the user accepts the link is encrypted for that and later operations. If the user declines, or the peripheral has lost its keys (for example after a factory reset), the operation fails, and the user has to remove the device in Settings > Bluetooth before pairing again. Design the app around attempting the protected operation and handling its failure, not around checking the bond first. + +**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 @@ -248,7 +293,7 @@ remaining seven target frameworks build and the two Windows ones are skipped. GitHub Actions (`.github/workflows/`): - `ci.yml`: runs on pull requests to `main` and `development`. Builds Release for every target framework. Publishes nothing. -- `release.yml`: runs on every push to `main` (changes only to Markdown or workflow files are skipped; run it by hand to test a workflow change). Builds Release as `4.0.yyMM.` plus `RELEASE_SUFFIX` (empty for a stable version; set it to `-prerelease` in the workflow to publish a prerelease), uploads the package as the `drop` artifact and pushes it to nuget.org with Trusted Publishing (OIDC, `NUGET_USER` secret, `nuget` environment), then tags the commit `v` and creates a GitHub release with the package attached. `AssemblyVersion` is not stamped by CI: it stays pinned in the project file (see "Strong naming"). +- `release.yml`: runs on every push to `main` (changes only to Markdown or workflow files are skipped; run it by hand to test a workflow change). Builds Release as `4.1.yyMM.` plus `RELEASE_SUFFIX` (empty for a stable version; set it to `-prerelease` in the workflow to publish a prerelease), uploads the package as the `drop` artifact and pushes it to nuget.org with Trusted Publishing (OIDC, `NUGET_USER` secret, `nuget` environment), then tags the commit `v` and creates a GitHub release with the package attached. `AssemblyVersion` is not stamped by CI: it stays pinned in the project file (see "Strong naming"). ### Strong naming