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
4 changes: 2 additions & 2 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -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.<run number + 100>, then
# package (with its .snupkg symbols) to nuget.org as 4.1.yyMM.<run number + 100>, 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.
Expand Down Expand Up @@ -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"
Expand Down
86 changes: 76 additions & 10 deletions DSoft.System.BluetoothLe/Adapter/Adapter.android.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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);
}
}

/// <summary>
/// The device for <paramref name="nativeDevice"/>: the instance this adapter already tracks - connected
/// first, then discovered - or a new one when it tracks none.
/// </summary>
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)
Expand Down Expand Up @@ -205,6 +254,23 @@ public IReadOnlyList<Device> 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);
Expand Down
31 changes: 31 additions & 0 deletions DSoft.System.BluetoothLe/Adapter/Adapter.shared.cs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,25 @@ public partial class Adapter : IDisposable
/// </summary>
public event EventHandler<ScanFailedEventArgs> ScanFailed;

/// <summary>
/// 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.
/// </summary>
/// <remarks>
/// <para>
/// 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 <see cref="Device.BondState"/> change is also raised through
/// <see cref="Device.PropertyChanged"/>. On Android 12 and later the system delivers the change only to
/// an app holding the BLUETOOTH_CONNECT permission.
/// </para>
/// <para>
/// Never raised on Apple platforms, which do not expose bonding, or on Windows.
/// </para>
/// </remarks>
public event EventHandler<DeviceBondStateChangedEventArgs> DeviceBondStateChanged;

#endregion

#region Properties
Expand Down Expand Up @@ -567,6 +586,18 @@ internal void HandleDisconnectedDevice(bool disconnectRequested, Device device)
}
}

/// <summary>
/// Reports a bond state change for <paramref name="device"/>: raises <see cref="Device.PropertyChanged"/>
/// for <see cref="Device.BondState"/>, then <see cref="DeviceBondStateChanged"/>.
/// </summary>
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);
Expand Down
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
14 changes: 13 additions & 1 deletion DSoft.System.BluetoothLe/DSoft.System.BluetoothLe.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
<!-- The assembly identity is pinned here rather than stamped by the build server. A strong-named
assembly whose version moves on every CI build forces a binding redirect on net481 for no
benefit; the public key token is what actually establishes identity. -->
<VersionPrefix>4.0.1</VersionPrefix>
<VersionPrefix>4.1.0</VersionPrefix>
<AssemblyVersion>4.0.0.0</AssemblyVersion>
<PackageId>DSoft.System.BluetoothLe</PackageId>
<Title>DSoft.System.BluetoothLe</Title>
Expand All @@ -51,6 +51,18 @@
<PackageTags>BluetoothLe dotnet android ios macos maccatalyst windows wpf netstandard tvos</PackageTags>
<Copyright>Copyright © 2026 DSoft</Copyright>
<PackageReleaseNotes>
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
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
Loading
Loading