Table of Contents

Class BaseBluetoothRemoteDevice

Namespace
Bluetooth.Core.Scanning
Assembly
Bluetooth.Core.Scanning.dll

Interface representing a Bluetooth device, providing properties and methods for interacting with it.

public abstract class BaseBluetoothRemoteDevice : BaseBindableObject, IBluetoothRemoteDevice, INotifyPropertyChanged, IAsyncDisposable
Inheritance
BaseBluetoothRemoteDevice
Implements
Derived
Inherited Members

Constructors

BaseBluetoothRemoteDevice(IBluetoothScanner, IBluetoothAdvertisement, SignalStrengthSmoothingOptions, IBluetoothRssiToSignalStrengthConverter, ILogger<IBluetoothRemoteDevice>?)

Initializes a new instance of the BaseBluetoothRemoteDevice class using the provided Bluetooth advertisement and parent scanner.

protected BaseBluetoothRemoteDevice(IBluetoothScanner parentScanner, IBluetoothAdvertisement advertisement, SignalStrengthSmoothingOptions signalStrengthSmoothingOptions, IBluetoothRssiToSignalStrengthConverter rssiToSignalStrengthConverter, ILogger<IBluetoothRemoteDevice>? logger = null)

Parameters

parentScanner IBluetoothScanner

The Bluetooth scanner associated with this remote device.

advertisement IBluetoothAdvertisement

The Bluetooth advertisement containing information about the remote device.

signalStrengthSmoothingOptions SignalStrengthSmoothingOptions

The options for smoothing signal strength jitter.

rssiToSignalStrengthConverter IBluetoothRssiToSignalStrengthConverter

The converter for RSSI to signal strength.

logger ILogger<IBluetoothRemoteDevice>

Optional logger instance for logging purposes.

BaseBluetoothRemoteDevice(IBluetoothScanner, BluetoothRemoteDeviceFactorySpec, IBluetoothRemoteServiceFactory, IBluetoothRssiToSignalStrengthConverter, ILogger<IBluetoothRemoteDevice>?)

Initializes a new instance using a factory spec, enabling the spec-based creation pattern.

protected BaseBluetoothRemoteDevice(IBluetoothScanner parentScanner, IBluetoothRemoteDeviceFactory.BluetoothRemoteDeviceFactorySpec spec, IBluetoothRemoteServiceFactory serviceFactory, IBluetoothRssiToSignalStrengthConverter rssiToSignalStrengthConverter, ILogger<IBluetoothRemoteDevice>? logger = null)

Parameters

parentScanner IBluetoothScanner

The Bluetooth scanner associated with this device.

spec IBluetoothRemoteDeviceFactory.BluetoothRemoteDeviceFactorySpec

The factory spec containing device information (ID, manufacturer).

serviceFactory IBluetoothRemoteServiceFactory

The factory for creating Bluetooth remote services.

rssiToSignalStrengthConverter IBluetoothRssiToSignalStrengthConverter

The converter for RSSI to signal strength.

logger ILogger<IBluetoothRemoteDevice>

Optional logger instance for logging purposes.

BaseBluetoothRemoteDevice(IBluetoothScanner, string, Manufacturer, SignalStrengthSmoothingOptions, IBluetoothRssiToSignalStrengthConverter, ILogger<IBluetoothRemoteDevice>?)

Initializes a new instance of the BaseBluetoothRemoteDevice class.

protected BaseBluetoothRemoteDevice(IBluetoothScanner parentScanner, string id, Manufacturer manufacturer, SignalStrengthSmoothingOptions signalStrengthSmoothingOptions, IBluetoothRssiToSignalStrengthConverter rssiToSignalStrengthConverter, ILogger<IBluetoothRemoteDevice>? logger = null)

Parameters

parentScanner IBluetoothScanner

The Bluetooth scanner associated with this device.

id string

The unique identifier of the Bluetooth device, typically a UUID or MAC address.

manufacturer Manufacturer

The manufacturer information for the Bluetooth device.

signalStrengthSmoothingOptions SignalStrengthSmoothingOptions

The options for smoothing signal strength jitter.

rssiToSignalStrengthConverter IBluetoothRssiToSignalStrengthConverter

The converter for RSSI to signal strength.

logger ILogger<IBluetoothRemoteDevice>

The logger instance to use for logging.

Properties

AdvertisedName

Gets the name advertised by the device in its advertisement data.

public string AdvertisedName { get; }

Property Value

string

BatteryLevelPercent

Gets the battery level as a value between 0 and 1.

public double? BatteryLevelPercent { get; }

Property Value

double?

CachedName

Gets the cached name of the device, typically stored from previous connections or GATT reads.

public string CachedName { get; protected set; }

Property Value

string

CurrentRxPhy

Gets the current receive PHY mode.

public PhyMode CurrentRxPhy { get; }

Property Value

PhyMode

CurrentTxPhy

Gets the current transmit PHY mode.

public PhyMode CurrentTxPhy { get; }

Property Value

PhyMode

DebugName

Gets the debug-friendly name of the device, including both advertised and cached names for logging purposes.

public string DebugName { get; }

Property Value

string

FirmwareVersion

Gets the firmware version of the device.

public Version? FirmwareVersion { get; }

Property Value

Version

HardwareVersion

Gets the hardware version of the device.

public string? HardwareVersion { get; }

Property Value

string

Id

Gets the unique identifier of the device.

public string Id { get; }

Property Value

string

IgnoreNextUnexpectedDisconnection

Gets or sets a value indicating whether the next unexpected disconnection should be ignored.

public bool IgnoreNextUnexpectedDisconnection { get; set; }

Property Value

bool

IntervalBetweenAdvertisement

Gets the interval between advertisement information.

public TimeSpan IntervalBetweenAdvertisement { get; }

Property Value

TimeSpan

IsConnected

Gets a value indicating whether the device is connected.

public bool IsConnected { get; protected set; }

Property Value

bool

IsConnecting

Gets a value indicating whether a connection operation is currently in progress.

public bool IsConnecting { get; }

Property Value

bool

IsDisconnecting

Gets a value indicating whether a disconnection operation is currently in progress.

public bool IsDisconnecting { get; }

Property Value

bool

IsExploringServices

Gets a value indicating whether service exploration is currently in progress.

public bool IsExploringServices { get; }

Property Value

bool

IsSignalStrengthProbingEnabled

Gets or sets a value indicating whether this device may be probed for its signal strength. Defaults to true. When set to false, ReadSignalStrengthAsync(TimeSpan?, CancellationToken) stops issuing native RSSI reads and returns the last known SignalStrengthInDbm instead.

public bool IsSignalStrengthProbingEnabled { get; set; }

Property Value

bool

Remarks

Set this to false before starting a firmware update. Nordic's DFU bootloader tends to drop the connection when it is spammed with RSSI reads, which is particularly dangerous while an update is in flight. A read that is already in flight when this is set to false still completes normally.

Signal strengths carried by advertisements are unaffected — those are passive and cost the device nothing.

IsStale

Gets a value indicating whether the device is stale (not seen for the configured inactivity timeout).

public bool IsStale { get; }

Property Value

bool

LastAdvertisement

Gets the latest advertisement information received.

public IBluetoothAdvertisement? LastAdvertisement { get; }

Property Value

IBluetoothAdvertisement

LastSeen

Gets the last time the device was seen, either by scanning or by connection.

public DateTimeOffset LastSeen { get; }

Property Value

DateTimeOffset

Manufacturer

Gets the manufacturer of the device.

public Manufacturer Manufacturer { get; }

Property Value

Manufacturer

Mtu

Gets the current Maximum Transmission Unit (MTU) for this connection. The MTU determines the maximum size of a single packet that can be sent.

public int Mtu { get; }

Property Value

int

Name

Gets the name of the device, using the advertised name first, if empty it will use the cached name.

public string Name { get; }

Property Value

string

RssiToSignalStrengthConverter

Gets the converter used to convert RSSI values to signal strength levels. This allows for consistent interpretation of signal strength across different platforms and devices, as RSSI values can vary in scale and meaning depending on the underlying Bluetooth implementation.

protected IBluetoothRssiToSignalStrengthConverter RssiToSignalStrengthConverter { get; }

Property Value

IBluetoothRssiToSignalStrengthConverter

Scanner

Gets the Bluetooth scanner associated with this device.

public IBluetoothScanner Scanner { get; }

Property Value

IBluetoothScanner

ServiceFactory

Gets the factory for creating Bluetooth remote services.

protected IBluetoothRemoteServiceFactory? ServiceFactory { get; }

Property Value

IBluetoothRemoteServiceFactory

SignalStrengthInDbm

Gets the signal strength in dBm.

public int SignalStrengthInDbm { get; }

Property Value

int

SignalStrengthInPercent

Gets the signal strength as a percentage (between 0.00 and 1.00).

public double SignalStrengthInPercent { get; }

Property Value

double

SignalStrengthSmoothingOptions

Gets the options for smoothing signal strength jitter. This allows for configuring how the signal strength readings are averaged over time to provide a more stable and accurate representation of the device's signal strength, especially in environments with fluctuating signal conditions.

public SignalStrengthSmoothingOptions SignalStrengthSmoothingOptions { get; }

Property Value

SignalStrengthSmoothingOptions

SoftwareVersion

Gets the software version of the device.

public Version? SoftwareVersion { get; }

Property Value

Version

Methods

ClearServicesAsync()

Clears all services and their characteristics, disposing of them properly.

public ValueTask ClearServicesAsync()

Returns

ValueTask

A task that completes when all services have been cleared and disposed.

ConnectAsync(ConnectionOptions?, TimeSpan?, CancellationToken)

Connects to the device asynchronously.

public virtual ValueTask ConnectAsync(ConnectionOptions? connectionOptions = null, TimeSpan? timeout = null, CancellationToken cancellationToken = default)

Parameters

connectionOptions ConnectionOptions

The connection options to use. If null, default options will be used.

timeout TimeSpan?

The timeout for this operation

cancellationToken CancellationToken

A cancellation token to cancel this operation.

Returns

ValueTask

A task that represents the asynchronous operation.

Exceptions

InvalidOperationException

Thrown when the device is already connected.

TimeoutException

Thrown if the connection attempt times out.

OperationCanceledException

Thrown when the operation is cancelled.

ConnectIfNeededAsync(ConnectionOptions?, TimeSpan?, CancellationToken)

Connects to the device if it is not already connected asynchronously.

public virtual ValueTask ConnectIfNeededAsync(ConnectionOptions? connectionOptions = null, TimeSpan? timeout = null, CancellationToken cancellationToken = default)

Parameters

connectionOptions ConnectionOptions

The connection options to use. If null, default options will be used.

timeout TimeSpan?

The timeout for this operation

cancellationToken CancellationToken

A cancellation token to cancel this operation.

Returns

ValueTask

A task that represents the asynchronous operation.

Exceptions

TimeoutException

Thrown if the connection attempt times out.

DisconnectAsync(TimeSpan?, CancellationToken)

Disconnects from the device asynchronously.

public ValueTask DisconnectAsync(TimeSpan? timeout = null, CancellationToken cancellationToken = default)

Parameters

timeout TimeSpan?

The timeout for this operation

cancellationToken CancellationToken

A cancellation token to cancel this operation.

Returns

ValueTask

A task that represents the asynchronous operation.

Exceptions

InvalidOperationException

Thrown when the device is not connected.

TimeoutException

Thrown if the disconnection attempt times out.

OperationCanceledException

Thrown when the operation is cancelled.

DisconnectIfNeededAsync(TimeSpan?, CancellationToken)

Disconnects from the device if it is not already disconnected asynchronously.

public ValueTask DisconnectIfNeededAsync(TimeSpan? timeout = null, CancellationToken cancellationToken = default)

Parameters

timeout TimeSpan?

The timeout for this operation

cancellationToken CancellationToken

A cancellation token to cancel this operation.

Returns

ValueTask

A task that represents the asynchronous operation.

Exceptions

TimeoutException

Thrown if the disconnection attempt times out.

DisposeAsync()

Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources asynchronously.

public ValueTask DisposeAsync()

Returns

ValueTask

A task that represents the asynchronous dispose operation.

DisposeAsyncCore()

Performs the core disposal logic for the device, including disconnection, cleanup of pending operations, and resource disposal.

protected virtual ValueTask DisposeAsyncCore()

Returns

ValueTask

A task that represents the asynchronous disposal operation.

ExploreServicesAsync(ServiceExplorationOptions?, TimeSpan?, CancellationToken)

Explores the services of the device asynchronously.

public Task ExploreServicesAsync(ServiceExplorationOptions? options = null, TimeSpan? timeout = null, CancellationToken cancellationToken = default)

Parameters

options ServiceExplorationOptions

Optional exploration configuration. If null, uses default options (services only, with caching enabled). Use ServicesOnly for services-only exploration, WithCharacteristics to include characteristics, or Full for full discovery (services + characteristics + descriptors). Set UseCache = false to force re-exploration even if services were previously discovered.

timeout TimeSpan?

The timeout for this operation

cancellationToken CancellationToken

A cancellation token to cancel this operation.

Returns

Task

A task that represents the asynchronous operation.

Remarks

Common Usage Patterns:

// Simple exploration (uses defaults: services only, with caching):
await device.ExploreServicesAsync();

// Explore services and characteristics: await device.ExploreServicesAsync(ServiceExplorationOptions.WithCharacteristics);

// Full exploration (services, characteristics, descriptors): await device.ExploreServicesAsync(ServiceExplorationOptions.Full);

// Force re-exploration (ignore cache): await device.ExploreServicesAsync(new() { UseCache = false });

// Custom options with UUID filtering: await device.ExploreServicesAsync(new ServiceExplorationOptions { Depth = ExplorationDepth.Characteristics, ServiceUuidFilter = uuid => uuid == myServiceUuid, UseCache = false }); Caching Behavior: By default (options = null), caching is enabled (UseCache = true). This means if services have already been explored, the method returns immediately without re-querying the device. To force re-exploration, explicitly set UseCache = false.

Exceptions

DeviceNotConnectedException

Thrown when the device is not connected.

TimeoutException

Thrown when the operation times out.

OperationCanceledException

Thrown when the operation is cancelled.

GetService(Func<IBluetoothRemoteService, bool>)

Gets the service that matches the specified filter.

public IBluetoothRemoteService GetService(Func<IBluetoothRemoteService, bool> filter)

Parameters

filter Func<IBluetoothRemoteService, bool>

The filter to apply to the services.

Returns

IBluetoothRemoteService

The service that matches the filter.

Exceptions

ServiceNotFoundException

Thrown if no service matches the specified filter.

MultipleServicesFoundException

Thrown if multiple services match the specified filter.

GetService(Guid)

Gets the service with the specified ID.

public IBluetoothRemoteService GetService(Guid id)

Parameters

id Guid

The ID of the service to get.

Returns

IBluetoothRemoteService

The service with the specified ID.

Exceptions

ServiceNotFoundException

Thrown if no service with the specified ID is found.

MultipleServicesFoundException

Thrown if multiple services match the specified filter.

GetServiceOrDefault(Func<IBluetoothRemoteService, bool>)

Gets the service that matches the specified filter.

public IBluetoothRemoteService? GetServiceOrDefault(Func<IBluetoothRemoteService, bool> filter)

Parameters

filter Func<IBluetoothRemoteService, bool>

The filter to apply to the services.

Returns

IBluetoothRemoteService

The service that matches the filter, or null if no such service exists.

Exceptions

MultipleServicesFoundException

Thrown if multiple services match the specified filter.

GetServiceOrDefault(Guid)

Gets the service with the specified ID.

public IBluetoothRemoteService? GetServiceOrDefault(Guid id)

Parameters

id Guid

The ID of the service to get.

Returns

IBluetoothRemoteService

The service with the specified ID, or null if no such service exists.

Exceptions

MultipleServicesFoundException

Thrown if multiple services match the specified filter.

GetServices(Func<IBluetoothRemoteService, bool>?)

Gets the services that match the specified filter.

public IReadOnlyList<IBluetoothRemoteService> GetServices(Func<IBluetoothRemoteService, bool>? filter = null)

Parameters

filter Func<IBluetoothRemoteService, bool>

The filter to apply to the services.

Returns

IReadOnlyList<IBluetoothRemoteService>

A read-only snapshot of services at the time of the call. This collection is immutable and will not be modified if services are added or removed after the call returns. To get updated results, call this method again or subscribe to ServiceListChanged event.

HasService(Func<IBluetoothRemoteService, bool>?)

Determines whether the device has a service that matches the specified filter.

public bool HasService(Func<IBluetoothRemoteService, bool>? filter = null)

Parameters

filter Func<IBluetoothRemoteService, bool>

The filter to apply to the services.

Returns

bool

True if a matching service exists; otherwise, false.

HasService(Guid)

Determines whether the device has a service with the specified ID.

public bool HasService(Guid id)

Parameters

id Guid

The ID of the service to check for.

Returns

bool

True if a service with the specified ID exists; otherwise, false.

NativeConnectAsync(ConnectionOptions, TimeSpan?, CancellationToken)

Platform-specific implementation to initiate a connection to the device.

protected abstract ValueTask NativeConnectAsync(ConnectionOptions connectionOptions, TimeSpan? timeout = null, CancellationToken cancellationToken = default)

Parameters

connectionOptions ConnectionOptions
timeout TimeSpan?

Optional timeout for the operation.

cancellationToken CancellationToken

Token to cancel the operation.

Returns

ValueTask

NativeDisconnectAsync(TimeSpan?, CancellationToken)

Platform-specific implementation to initiate a disconnection from the device.

protected abstract ValueTask NativeDisconnectAsync(TimeSpan? timeout = null, CancellationToken cancellationToken = default)

Parameters

timeout TimeSpan?

Optional timeout for the operation.

cancellationToken CancellationToken

Token to cancel the operation.

Returns

ValueTask

NativeOpenL2CapChannelAsync(int)

Platform-specific implementation to open an L2CAP channel.

protected abstract ValueTask NativeOpenL2CapChannelAsync(int psm)

Parameters

psm int

Returns

ValueTask

NativeReadSignalStrength()

Platform-specific implementation to initiate a signal strength reading.

protected abstract void NativeReadSignalStrength()

NativeRefreshIsConnected()

Platform-specific implementation to refresh the current connection state from the native platform.

protected abstract void NativeRefreshIsConnected()

NativeRequestConnectionPriorityAsync(ConnectionPriority, TimeSpan?, CancellationToken)

Platform-specific implementation to request a connection priority change.

protected abstract ValueTask NativeRequestConnectionPriorityAsync(ConnectionPriority priority, TimeSpan? timeout = null, CancellationToken cancellationToken = default)

Parameters

priority ConnectionPriority

The desired connection priority mode.

timeout TimeSpan?

Optional timeout for the operation.

cancellationToken CancellationToken

Token to cancel the operation.

Returns

ValueTask

A task that represents the asynchronous operation.

Remarks

On platforms that don't support this feature (iOS, Windows), this should be a no-op.

NativeRequestMtuAsync(int)

Platform-specific implementation to request MTU.

protected abstract ValueTask NativeRequestMtuAsync(int requestedMtu)

Parameters

requestedMtu int

Returns

ValueTask

NativeServicesExplorationAsync(bool, TimeSpan?, CancellationToken)

Platform-specific implementation to explore services.

protected abstract ValueTask NativeServicesExplorationAsync(bool useCache, TimeSpan? timeout = null, CancellationToken cancellationToken = default)

Parameters

useCache bool

When false, platforms that maintain their own OS-level GATT cache independent of this library's cache (Android) should force a genuinely fresh read from the peripheral - confirmed against real hardware: Android can keep serving a peripheral's pre-reboot service list from its own Bluetooth stack cache even after ExploreServicesAsync's UseCache=false already bypassed this library's own cache, because that flag never reached the platform layer that actually owns the stale cache.

timeout TimeSpan?

The timeout for this operation.

cancellationToken CancellationToken

A cancellation token to cancel this operation.

Returns

ValueTask

NativeSetPreferredPhyAsync(PhyMode, PhyMode)

Platform-specific implementation to set preferred PHY.

protected abstract ValueTask NativeSetPreferredPhyAsync(PhyMode txPhy, PhyMode rxPhy)

Parameters

txPhy PhyMode
rxPhy PhyMode

Returns

ValueTask

OnAdvertisementReceived(IBluetoothAdvertisement)

Handles the advertisement information received event.

public void OnAdvertisementReceived(IBluetoothAdvertisement advertisement)

Parameters

advertisement IBluetoothAdvertisement

The advertisement information received.

OnConnectFailed(Exception)

Called when a connection attempt fails. Completes the connection task with an exception or dispatches to the unhandled exception listener.

protected void OnConnectFailed(Exception e)

Parameters

e Exception

The exception that occurred during the connection attempt.

OnConnectSucceeded()

Called when a connection attempt succeeds. Updates the connection state and completes the connection task.

protected void OnConnectSucceeded()

OnDisconnect(Exception?)

Called when a disconnection occurs, either intentionally or unexpectedly. Completes the disconnection task.

protected void OnDisconnect(Exception? e = null)

Parameters

e Exception

Optional exception that caused the disconnection.

OnL2CapChannelOpened(IBluetoothRemoteL2CapChannel)

Called when L2CAP channel is opened successfully.

protected void OnL2CapChannelOpened(IBluetoothRemoteL2CapChannel channel)

Parameters

channel IBluetoothRemoteL2CapChannel

OnMtuChanged(int)

Called when MTU request succeeds or MTU changes.

protected void OnMtuChanged(int mtu)

Parameters

mtu int

OnOpenL2CapChannelFailed(Exception)

Called when L2CAP channel open fails.

protected void OnOpenL2CapChannelFailed(Exception e)

Parameters

e Exception

OnPhyChanged(PhyMode, PhyMode)

Called when PHY changes.

protected void OnPhyChanged(PhyMode txPhy, PhyMode rxPhy)

Parameters

txPhy PhyMode
rxPhy PhyMode

OnRequestMtuFailed(Exception)

Called when MTU request fails.

protected void OnRequestMtuFailed(Exception e)

Parameters

e Exception

OnServicesExplorationFailed(Exception)

Called when service exploration fails. Completes the exploration task with an exception or dispatches to the unhandled exception listener.

protected void OnServicesExplorationFailed(Exception e)

Parameters

e Exception

The exception that occurred during service exploration.

OnServicesExplorationSucceeded<TNativeServiceType>(IList<TNativeServiceType>, Func<TNativeServiceType, IBluetoothRemoteService, bool>, Func<TNativeServiceType, IBluetoothRemoteService>)

Called when service exploration succeeds. Updates the Services collection and completes the exploration task.

protected void OnServicesExplorationSucceeded<TNativeServiceType>(IList<TNativeServiceType> services, Func<TNativeServiceType, IBluetoothRemoteService, bool> areRepresentingTheSameObject, Func<TNativeServiceType, IBluetoothRemoteService> fromInputTypeToOutputTypeConversion)

Parameters

services IList<TNativeServiceType>

The list of native services discovered.

areRepresentingTheSameObject Func<TNativeServiceType, IBluetoothRemoteService, bool>

Function to determine if a native service and IBluetoothService represent the same object.

fromInputTypeToOutputTypeConversion Func<TNativeServiceType, IBluetoothRemoteService>

Function to convert from native service type to IBluetoothService.

Type Parameters

TNativeServiceType

The platform-specific service type.

OnSetPreferredPhyFailed(Exception)

Called when set preferred PHY fails.

protected void OnSetPreferredPhyFailed(Exception e)

Parameters

e Exception

OnSignalStrengthRead(int)

Called when signal strength reading succeeds. Updates the SignalStrengthInDbm property and completes the task.

protected void OnSignalStrengthRead(int rssi)

Parameters

rssi int

The signal strength value in dBm.

OnSignalStrengthReadFailed(Exception)

Called when signal strength reading fails. Completes the task with an exception or dispatches to the unhandled exception listener.

protected void OnSignalStrengthReadFailed(Exception e)

Parameters

e Exception

The exception that occurred during the signal strength reading.

OnUnexpectedDisconnection(Exception?)

Called when an unexpected disconnection occurs. Clears services and raises the UnexpectedDisconnection event.

protected virtual void OnUnexpectedDisconnection(Exception? e = null)

Parameters

e Exception

Optional exception that caused the unexpected disconnection.

OpenL2CapChannelAsync(int, TimeSpan?, CancellationToken)

Opens an L2CAP channel to the specified PSM (Protocol Service Multiplexer). L2CAP channels provide connection-oriented data transfer with higher throughput than GATT.

public ValueTask<IBluetoothRemoteL2CapChannel> OpenL2CapChannelAsync(int psm, TimeSpan? timeout = null, CancellationToken cancellationToken = default)

Parameters

psm int

The PSM value to connect to.

timeout TimeSpan?

The timeout for this operation.

cancellationToken CancellationToken

A cancellation token to cancel this operation.

Returns

ValueTask<IBluetoothRemoteL2CapChannel>

A task that represents the asynchronous operation. The task result contains the opened L2CAP channel.

Remarks

Platform Support:

  • iOS/macOS: Supported on iOS 11+ / macOS 10.13+ via CBPeripheral.openL2CAPChannel()
  • Android: Supported on Android 10+ (API 29+) via BluetoothDevice.createL2capChannel()
  • Windows: Not supported - throws PlatformNotSupportedException

L2CAP channels bypass GATT overhead and provide direct socket-like communication: - Higher throughput for bulk data transfer - Lower latency for time-sensitive data - Custom protocol implementation support

Valid PSM range is typically 0x0001-0x00FF (dynamic) or vendor-specific values.

Exceptions

ArgumentOutOfRangeException

Thrown when psm is invalid.

InvalidOperationException

Thrown when the device is not connected or L2CAP is not supported.

TimeoutException

Thrown when the operation times out.

OperationCanceledException

Thrown when the operation is cancelled.

ReadBatteryLevelAsync(TimeSpan?, CancellationToken)

Reads the battery level asynchronously.

public ValueTask<double?> ReadBatteryLevelAsync(TimeSpan? timeout = null, CancellationToken cancellationToken = default)

Parameters

timeout TimeSpan?

Optional timeout for service exploration and read operations.

cancellationToken CancellationToken

A cancellation token to cancel this operation.

Returns

ValueTask<double?>

A task that represents the asynchronous operation. The task result contains the battery level percentage.

ReadFirmwareVersionAsync()

Reads the firmware version asynchronously.

public Task<Version> ReadFirmwareVersionAsync()

Returns

Task<Version>

A task that represents the asynchronous operation. The task result contains the firmware version.

ReadHardwareVersionAsync()

Reads the hardware version asynchronously.

public Task<string> ReadHardwareVersionAsync()

Returns

Task<string>

A task that represents the asynchronous operation. The task result contains the hardware version.

ReadSignalStrengthAsync(TimeSpan?, CancellationToken)

Reads the signal strength asynchronously. This is an operation running on a ticker when the device is connected. We can't get that value from advertisement anymore.

public ValueTask<int> ReadSignalStrengthAsync(TimeSpan? timeout = null, CancellationToken cancellationToken = default)

Parameters

timeout TimeSpan?

The timeout for this operation

cancellationToken CancellationToken

A cancellation token to cancel this operation.

Returns

ValueTask<int>

A task that represents the asynchronous operation.

Remarks

Platform Support:

  • Android: Real-time RSSI reading via BluetoothGatt.readRemoteRssi() with callback
  • iOS/macOS: Real-time RSSI reading via CBPeripheral.readRSSI() with delegate callback
  • Windows: Limited support - RSSI may be cached or require periodic polling

Signal strength is measured in dBm (decibel-milliwatts): - Typical range: -100 dBm (very weak, ~100m) to -30 dBm (very strong, close proximity) - Values update based on radio conditions and may fluctuate - Accuracy varies by platform and hardware capabilities

Call frequency should be limited to avoid impacting performance - recommended interval: 1-5 seconds.

Returns the last known SignalStrengthInDbm without touching the radio when IsSignalStrengthProbingEnabled is false.

Exceptions

InvalidOperationException

Thrown when the device is not connected.

TimeoutException

Thrown when the operation times out.

OperationCanceledException

Thrown when the operation is cancelled.

ReadSoftwareVersionAsync()

Reads the software version asynchronously.

public Task<Version> ReadSoftwareVersionAsync()

Returns

Task<Version>

A task that represents the asynchronous operation. The task result contains the software version.

ReadVersionsAsync()

Reads all versions (firmware, software, and hardware) asynchronously.

public Task ReadVersionsAsync()

Returns

Task

A task that represents the asynchronous operation.

RequestConnectionPriorityAsync(ConnectionPriority, TimeSpan?, CancellationToken)

Requests a change in connection priority/performance mode for an active connection.

public ValueTask RequestConnectionPriorityAsync(ConnectionPriority priority, TimeSpan? timeout = null, CancellationToken cancellationToken = default)

Parameters

priority ConnectionPriority

The desired connection priority mode.

timeout TimeSpan?

The timeout for this operation.

cancellationToken CancellationToken

A cancellation token to cancel this operation.

Returns

ValueTask

A task that represents the asynchronous operation.

Remarks

Platform Support:

  • Android: Full support via BluetoothGatt.requestConnectionPriority()
  • iOS/macOS: Connection parameters are system-managed. This method is a no-op.
  • Windows: Connection parameters are system-managed. This method is a no-op.

On Android, this allows fine-tuning the connection parameters for different use cases: - High priority: Fast data transfer, low latency (11.25-15ms interval) - Balanced: Reasonable performance with moderate power (30-50ms interval) - Low power: Battery optimization, higher latency (100-125ms interval)

Changes typically take effect within a few connection intervals after the request.

Exceptions

InvalidOperationException

Thrown when the device is not connected.

TimeoutException

Thrown when the operation times out.

OperationCanceledException

Thrown when the operation is cancelled.

RequestMtuAsync(int, TimeSpan?, CancellationToken)

Requests a new MTU size for the connection.

public ValueTask<int> RequestMtuAsync(int requestedMtu, TimeSpan? timeout = null, CancellationToken cancellationToken = default)

Parameters

requestedMtu int

The desired MTU size (typically between 23 and 517 bytes).

timeout TimeSpan?

The timeout for this operation.

cancellationToken CancellationToken

A cancellation token to cancel this operation.

Returns

ValueTask<int>

A task that represents the asynchronous operation. The task result contains the negotiated MTU size.

Remarks

Platform Support:

  • Android: Full support for explicit MTU negotiation via BluetoothGatt.requestMtu() (range: 23-517 bytes, default: 23)
  • iOS/macOS: MTU is automatically negotiated by the system. This method is a no-op and returns the current system-negotiated MTU.
  • Windows: MTU is automatically negotiated via GATT session. This method returns the current negotiated value.

MTU (Maximum Transmission Unit) determines the maximum payload size per packet: - Larger MTU = fewer packets for large data transfers = better throughput - Default MTU is 23 bytes (20 bytes payload + 3 bytes ATT header) - Maximum MTU is typically 517 bytes but depends on hardware

The final MTU is negotiated between both devices and may be lower than requested.

Exceptions

ArgumentOutOfRangeException

Thrown when requestedMtu is out of valid range.

InvalidOperationException

Thrown when the device is not connected.

TimeoutException

Thrown when the operation times out.

OperationCanceledException

Thrown when the operation is cancelled.

SetPreferredPhyAsync(PhyMode, PhyMode, TimeSpan?, CancellationToken)

Requests a preferred PHY mode for the connection (Bluetooth 5.0+ feature).

public ValueTask SetPreferredPhyAsync(PhyMode txPhy, PhyMode rxPhy, TimeSpan? timeout = null, CancellationToken cancellationToken = default)

Parameters

txPhy PhyMode

The desired transmit PHY mode.

rxPhy PhyMode

The desired receive PHY mode.

timeout TimeSpan?

The timeout for this operation.

cancellationToken CancellationToken

A cancellation token to cancel this operation.

Returns

ValueTask

A task that represents the asynchronous operation.

Remarks

Platform Support:

  • Android: Full support on Android 8.0 (API 26+) with Bluetooth 5.0 hardware via BluetoothGatt.setPreferredPhy()
  • iOS/macOS: PHY selection is system-managed and automatic. This method is a no-op.
  • Windows: Limited support - PHY is typically auto-negotiated by the system.

PHY modes affect range, speed, and power consumption: - 1M PHY: Standard mode with balanced range and throughput (1 Mbps) - 2M PHY: High-speed mode with reduced range (2 Mbps) - Coded PHY: Long-range mode with reduced throughput (~125-500 Kbps) but 4x range

The actual PHY used depends on negotiation with the remote device and hardware capabilities.

Exceptions

InvalidOperationException

Thrown when the device is not connected or PHY mode is not supported.

TimeoutException

Thrown when the operation times out.

OperationCanceledException

Thrown when the operation is cancelled.

ToString()

Returns a string that represents the current object.

public override string ToString()

Returns

string

WaitForAdvertisementAsync(Func<IBluetoothAdvertisement?, bool>, TimeSpan?, CancellationToken)

Waits for advertisement information asynchronously.

public ValueTask<IBluetoothAdvertisement> WaitForAdvertisementAsync(Func<IBluetoothAdvertisement?, bool> filter, TimeSpan? timeout = null, CancellationToken cancellationToken = default)

Parameters

filter Func<IBluetoothAdvertisement, bool>

The filter to apply to the advertisement information.

timeout TimeSpan?

The timeout for this operation

cancellationToken CancellationToken

A cancellation token to cancel this operation.

Returns

ValueTask<IBluetoothAdvertisement>

A task that represents the asynchronous operation. The task result contains the advertisement information.

WaitForAdvertisementAsync(TimeSpan?, CancellationToken)

Waits for advertisement information asynchronously.

public ValueTask<IBluetoothAdvertisement> WaitForAdvertisementAsync(TimeSpan? timeout = null, CancellationToken cancellationToken = default)

Parameters

timeout TimeSpan?

The timeout for this operation

cancellationToken CancellationToken

A cancellation token to cancel this operation.

Returns

ValueTask<IBluetoothAdvertisement>

A task that represents the asynchronous operation. The task result contains the advertisement information.

WaitForIsConnectedAsync(bool, TimeSpan?, CancellationToken)

Waits for the device to be connected or disconnected asynchronously.

public ValueTask WaitForIsConnectedAsync(bool isConnected, TimeSpan? timeout = null, CancellationToken cancellationToken = default)

Parameters

isConnected bool

True to wait for the device to be connected, false to wait for it to be disconnected.

timeout TimeSpan?

The timeout for this operation

cancellationToken CancellationToken

A cancellation token to cancel this operation.

Returns

ValueTask

A task that represents the asynchronous operation.

WaitForNameToChangeAsync(TimeSpan?, CancellationToken)

Waits for the device's advertised name to change.

public ValueTask WaitForNameToChangeAsync(TimeSpan? timeout = null, CancellationToken cancellationToken = default)

Parameters

timeout TimeSpan?

Optional timeout for the operation.

cancellationToken CancellationToken

Token to cancel the operation.

Returns

ValueTask

A task that completes when the advertised name changes.

Events

AdvertisementReceived

Occurs when advertisement information is received.

public event EventHandler<AdvertisementReceivedEventArgs>? AdvertisementReceived

Event Type

EventHandler<AdvertisementReceivedEventArgs>

Connected

Occurs when the device is connected.

public event EventHandler? Connected

Event Type

EventHandler

Connecting

Occurs when the device is connecting.

public event EventHandler? Connecting

Event Type

EventHandler

ConnectionStateChanged

Occurs when the connection state of the device changes.

public event EventHandler<DeviceConnectionStateChangedEventArgs>? ConnectionStateChanged

Event Type

EventHandler<DeviceConnectionStateChangedEventArgs>

Disconnected

Occurs when the device is disconnected.

public event EventHandler? Disconnected

Event Type

EventHandler

Disconnecting

Occurs when the device is disconnecting.

public event EventHandler? Disconnecting

Event Type

EventHandler

MtuChanged

Event raised when the MTU changes.

public event EventHandler<MtuChangedEventArgs>? MtuChanged

Event Type

EventHandler<MtuChangedEventArgs>

PhyChanged

Event raised when the PHY changes.

public event EventHandler<PhyChangedEventArgs>? PhyChanged

Event Type

EventHandler<PhyChangedEventArgs>

ServiceListChanged

Occurs when the service list changes.

public event EventHandler<ServiceListChangedEventArgs>? ServiceListChanged

Event Type

EventHandler<ServiceListChangedEventArgs>

ServicesAdded

Event triggered when services are added.

public event EventHandler<ServicesAddedEventArgs>? ServicesAdded

Event Type

EventHandler<ServicesAddedEventArgs>

ServicesRemoved

Event triggered when services are removed.

public event EventHandler<ServicesRemovedEventArgs>? ServicesRemoved

Event Type

EventHandler<ServicesRemovedEventArgs>

UnexpectedDisconnection

Occurs when an unexpected disconnection happens.

public event EventHandler<DeviceUnexpectedDisconnectionEventArgs>? UnexpectedDisconnection

Event Type

EventHandler<DeviceUnexpectedDisconnectionEventArgs>