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
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
5 changes: 5 additions & 0 deletions DSoft.System.BluetoothLe/DSoft.System.BluetoothLe.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@
<PackageTags>BluetoothLe dotnet android ios macos maccatalyst windows wpf netstandard tvos</PackageTags>
<Copyright>Copyright © 2026 DSoft</Copyright>
<PackageReleaseNotes>
Unreleased - 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.

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
38 changes: 36 additions & 2 deletions DSoft.System.BluetoothLe/Devices/Device.android.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);

/// <summary>
/// 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.
/// </summary>
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))
Expand Down Expand Up @@ -223,6 +229,34 @@ 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);
}

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<bool> UpdateRssiNativeAsync(CancellationToken cancellationToken)
{
if (_gatt == null || _gattCallback == null)
Expand Down
4 changes: 4 additions & 0 deletions DSoft.System.BluetoothLe/Devices/Device.ios.mac.tvos.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@

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

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

View workflow job for this annotation

GitHub Actions / build

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

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

View workflow job for this annotation

GitHub Actions / build

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

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

View workflow job for this annotation

GitHub Actions / build

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

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

View workflow job for this annotation

GitHub Actions / build

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

}
Expand Down Expand Up @@ -157,6 +157,10 @@
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;

private DeviceState GetState()
{
switch (NativeDevice.State)
Expand Down Expand Up @@ -196,7 +200,7 @@
// Only overwrite the RSSI when the platform actually gave us one: outside a connection
// CBPeripheral.RSSI is null, and treating that as 0 dBm reports a device as being closer
// than anything real. Read once into a local so this remains a single deprecated call site.
var nativeRssi = nativeDevice.RSSI;

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

View workflow job for this annotation

GitHub Actions / build

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

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

View workflow job for this annotation

GitHub Actions / build

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

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

View workflow job for this annotation

GitHub Actions / build

This call site is reachable on: 'macOS/OSX' 15.0 and later. 'CBPeripheral.RSSI' is obsoleted on: 'macOS/OSX' 10.13 and later. (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1422)
if (nativeRssi != null)
{
Rssi = nativeRssi.Int32Value;
Expand Down
3 changes: 3 additions & 0 deletions DSoft.System.BluetoothLe/Devices/Device.netstandard.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ partial void DisposeNative()

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

// Reported rather than thrown: BondState is documented never to throw.
private DeviceBondState GetBondState() => DeviceBondState.Unknown;

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

private Task<IReadOnlyList<Service>> GetServicesNativeAsync(CancellationToken cancellationToken) => throw new System.PlatformNotSupportedException(NotSupportedMessage);
Expand Down
48 changes: 48 additions & 0 deletions DSoft.System.BluetoothLe/Devices/Device.shared.cs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,48 @@ public DeviceState State
}
}

/// <summary>
/// Gets the bond (pairing) state of the device, as the platform reports it now.
/// </summary>
/// <remarks>
/// <para>
/// Android reads it from the system on every call. Windows reports <see cref="DeviceBondState.Bonded"/>
/// or <see cref="DeviceBondState.NotBonded"/> from the device's pairing information, and never
/// <see cref="DeviceBondState.Bonding"/>. Apple platforms always report
/// <see cref="DeviceBondState.Unknown"/>: CoreBluetooth pairs on demand, the first time an encrypted
/// characteristic is accessed, and does not let an app ask whether a bond exists.
/// </para>
/// <para>
/// <see cref="DeviceBondState.Unknown"/> 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.
/// </para>
/// <para>
/// On Android, <see cref="Adapter.DeviceBondStateChanged"/> reports changes, and
/// <see cref="PropertyChanged"/> is raised for this property on the instance the adapter tracks.
/// </para>
/// </remarks>
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;
}
}
}

/// <summary>
/// Gets whether this instance has ever completed a connection.
/// </summary>
Expand Down Expand Up @@ -339,6 +381,12 @@ protected virtual void Dispose(bool disposing)
/// </summary>
internal void RaiseStateChanged() => NotifyPropertyChanged(nameof(State));

/// <summary>
/// Raises <see cref="PropertyChanged"/> for <see cref="BondState"/>. The platform announces bond
/// changes system-wide, so the adapter has to drive the notification.
/// </summary>
internal void RaiseBondStateChanged() => NotifyPropertyChanged(nameof(BondState));

#endregion

#region Private Methods
Expand Down
13 changes: 13 additions & 0 deletions DSoft.System.BluetoothLe/Devices/Device.uwp.netcore.netf.cs
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,19 @@ private async Task<IReadOnlyList<Service>> GetServicesNativeAsync(CancellationTo
.ToList<Service>();
}

// 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;
}

private DeviceState GetState()
{
if (NativeDevice.IsConnected)
Expand Down
21 changes: 19 additions & 2 deletions DSoft.System.BluetoothLe/Enums/DeviceBondState.shared.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,26 @@
namespace System.BluetoothLe
{
/// <summary>
/// The bond (pairing) state of a device, as the platform reports it.
/// </summary>
public enum DeviceBondState
{
/// <summary>The platform reports that the device is not bonded.</summary>
NotBonded,

/// <summary>Bonding with the device is in progress.</summary>
Bonding,
Bonded

/// <summary>The device is bonded: the platform holds keys for an encrypted link to it.</summary>
Bonded,

/// <summary>
/// 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.
/// </summary>
/// <remarks>Declared last so the values of the existing members are unchanged.</remarks>
Unknown
}
}
}
Loading
Loading