Table of Contents

Class BaseBluetoothBroadcaster

Namespace
Bluetooth.Core.Broadcasting
Assembly
Bluetooth.Core.Broadcasting.dll

Base class for Bluetooth Low Energy broadcaster implementations that advertise the device's presence.

public abstract class BaseBluetoothBroadcaster : BaseBindableObject, INotifyPropertyChanged, IBluetoothBroadcaster, IAsyncDisposable
Inheritance
BaseBluetoothBroadcaster
Implements
Derived
Inherited Members

Remarks

Broadcasters allow a device to act as a BLE peripheral, advertising its presence and services to nearby devices. This is the opposite role of a scanner, which listens for advertisements.

Constructors

BaseBluetoothBroadcaster(IBluetoothAdapter, ITicker, ILoggerFactory?)

Initializes a new instance of the BaseBluetoothBroadcaster class.

protected BaseBluetoothBroadcaster(IBluetoothAdapter adapter, ITicker ticker, ILoggerFactory? loggerFactory = null)

Parameters

adapter IBluetoothAdapter

The Bluetooth adapter to associate with this broadcaster.

ticker ITicker

The ticker for scheduling periodic refresh tasks.

loggerFactory ILoggerFactory

Optional logger factory for creating loggers.

Properties

Adapter

Gets the Bluetooth adapter associated with this broadcaster.

public IBluetoothAdapter Adapter { get; }

Property Value

IBluetoothAdapter

CurrentBroadcastingOptions

Gets the current broadcasting options being used by the Broadcaster.

public BroadcastingOptions CurrentBroadcastingOptions { get; }

Property Value

BroadcastingOptions

DefaultBroadcastingOptions

The default broadcasting options used when starting the broadcaster without specifying options. This can be overridden by derived classes to provide platform-specific default options.

protected static BroadcastingOptions DefaultBroadcastingOptions { get; }

Property Value

BroadcastingOptions

DefaultPermissionOptions

The default permission options used when starting the broadcaster without specifying options. This can be overridden by derived classes to provide platform-specific default options.

protected static PermissionOptions DefaultPermissionOptions { get; }

Property Value

PermissionOptions

IsRunning

Gets a value indicating whether the Bluetooth activity is actively running.

public bool IsRunning { get; protected set; }

Property Value

bool

IsStarting

Gets a value indicating whether the Bluetooth activity is starting.

public bool IsStarting { get; }

Property Value

bool

IsStopping

Gets a value indicating whether the Broadcaster is stopping.

public bool IsStopping { get; }

Property Value

bool

LoggerFactory

Gets the logger factory for creating loggers within the Bluetooth broadcaster/server implementation.

public ILoggerFactory? LoggerFactory { get; }

Property Value

ILoggerFactory

Methods

AddClientDevice(IBluetoothConnectedDevice)

Adds a newly connected client device to the collection. Called by platform implementations when a client connects.

protected void AddClientDevice(IBluetoothConnectedDevice device)

Parameters

device IBluetoothConnectedDevice

The client device to add.

CreateServiceAsync(Guid, string?, bool, TimeSpan?, CancellationToken)

Adds a GATT service to be hosted by the broadcaster.

public ValueTask<IBluetoothLocalService> CreateServiceAsync(Guid id, string? name = null, bool isPrimary = true, TimeSpan? timeout = null, CancellationToken cancellationToken = default)

Parameters

id Guid

The UUID of the service to add.

name string

An optional name for the service. If not provided, a default name may be assigned based on the UUID or other heuristics.

isPrimary bool

Indicates whether the service is a primary service. Defaults to true.

timeout TimeSpan?

The timeout for this operation

cancellationToken CancellationToken

A cancellation token to cancel this operation.

Returns

ValueTask<IBluetoothLocalService>

The added service.

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()

Disposes the resources asynchronously.

protected virtual ValueTask DisposeAsyncCore()

Returns

ValueTask

GetClientDevice(Func<IBluetoothConnectedDevice, bool>)

Returns the first Bluetooth device that matches the specified filter.

public IBluetoothConnectedDevice GetClientDevice(Func<IBluetoothConnectedDevice, bool> filter)

Parameters

filter Func<IBluetoothConnectedDevice, bool>

A function to filter devices. Should return true for matching devices.

Returns

IBluetoothConnectedDevice

The matching IBluetoothConnectedDevice.

Exceptions

ClientDeviceNotFoundException

Thrown when no device matches the specified filter.

MultipleClientDevicesFoundException

Thrown when multiple devices match the specified filter.

GetClientDevice(string)

Returns a Bluetooth device with the specified ID.

public IBluetoothConnectedDevice GetClientDevice(string id)

Parameters

id string

The ID of the device to retrieve.

Returns

IBluetoothConnectedDevice

The matching IBluetoothConnectedDevice.

Exceptions

ClientDeviceNotFoundException

Thrown when no device with the specified ID is found.

MultipleClientDevicesFoundException

Thrown when multiple devices with the specified ID are found.

GetClientDeviceOrDefault(Func<IBluetoothConnectedDevice, bool>)

Returns the first Bluetooth device that matches the specified filter.

public IBluetoothConnectedDevice? GetClientDeviceOrDefault(Func<IBluetoothConnectedDevice, bool> filter)

Parameters

filter Func<IBluetoothConnectedDevice, bool>

A function to filter devices. Should return true for matching devices.

Returns

IBluetoothConnectedDevice

The matching IBluetoothConnectedDevice, or null if none are found.

Exceptions

MultipleClientDevicesFoundException

Thrown when multiple devices match the specified filter.

GetClientDeviceOrDefault(string)

Returns a Bluetooth device with the specified ID.

public IBluetoothConnectedDevice? GetClientDeviceOrDefault(string id)

Parameters

id string

The ID of the device to retrieve.

Returns

IBluetoothConnectedDevice

The matching IBluetoothConnectedDevice, or null if none are found.

Exceptions

MultipleClientDevicesFoundException

Thrown when multiple devices with the specified ID are found.

GetClientDevices(Func<IBluetoothConnectedDevice, bool>?)

Returns all Bluetooth devices that match the specified filter.

public IReadOnlyList<IBluetoothConnectedDevice> GetClientDevices(Func<IBluetoothConnectedDevice, bool>? filter = null)

Parameters

filter Func<IBluetoothConnectedDevice, bool>

An optional function to filter devices. Defaults to null for all devices.

Returns

IReadOnlyList<IBluetoothConnectedDevice>

A read-only snapshot of connected client devices at the time of the call. This collection is immutable and will not be modified if devices connect or disconnect after the call returns. To get updated results, call this method again or subscribe to ClientDeviceListChanged event.

GetService(Func<IBluetoothLocalService, bool>)

Gets a hosted GATT service that matches the specified filter.

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

Parameters

filter Func<IBluetoothLocalService, bool>

A function to filter services. Should return true for the desired service.

Returns

IBluetoothLocalService

The matching service.

Exceptions

ServiceNotFoundException

Thrown if no service matches the specified filter.

MultipleServicesFoundException

Thrown if multiple services match the specified filter.

GetService(Guid)

Gets a hosted GATT service by its UUID.

public IBluetoothLocalService GetService(Guid id)

Parameters

id Guid

The UUID of the service to retrieve.

Returns

IBluetoothLocalService

The matching service.

Exceptions

ServiceNotFoundException

Thrown if no service matches the specified filter.

MultipleServicesFoundException

Thrown if multiple services match the specified filter.

GetServiceOrDefault(Func<IBluetoothLocalService, bool>)

Gets a hosted GATT service that matches the specified filter.

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

Parameters

filter Func<IBluetoothLocalService, bool>

A function to filter services. Should return true for the desired service.

Returns

IBluetoothLocalService

The matching service, or null if not found.

Exceptions

MultipleServicesFoundException

Thrown if multiple services match the specified filter.

GetServiceOrDefault(Guid)

Gets a hosted GATT service by its UUID.

public IBluetoothLocalService? GetServiceOrDefault(Guid id)

Parameters

id Guid

The UUID of the service to retrieve.

Returns

IBluetoothLocalService

The matching service, or null if not found.

Exceptions

MultipleServicesFoundException

Thrown if multiple services match the specified filter.

GetServices(Func<IBluetoothLocalService, bool>?)

Gets all hosted GATT services.

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

Parameters

filter Func<IBluetoothLocalService, bool>

An optional filter to apply to the services.

Returns

IReadOnlyList<IBluetoothLocalService>

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.

HandlePermissionsAsync(PermissionOptions, CancellationToken)

Handles permission requests based on the specified strategy in the broadcasting options. This method is called by StartBroadcastingAsync(BroadcastingOptions?, PermissionOptions?, TimeSpan?, CancellationToken) before starting the broadcaster to ensure necessary permissions are granted.

protected virtual ValueTask HandlePermissionsAsync(PermissionOptions permissionOptions, CancellationToken cancellationToken = default)

Parameters

permissionOptions PermissionOptions

The permission options containing the strategy for handling permissions.

cancellationToken CancellationToken

Cancellation token to cancel the permission request operation.

Returns

ValueTask

HasBroadcasterPermissionsAsync()

Checks if the application has the necessary broadcaster permissions.

public ValueTask<bool> HasBroadcasterPermissionsAsync()

Returns

ValueTask<bool>

True if broadcaster permissions are granted, otherwise false.

Remarks

This is a read-only check. It does not trigger any permission requests.

Platform-specific behavior:

  • Android: Checks BLUETOOTH_ADVERTISE (API 31+) or location permissions (older)
  • iOS/macOS: Checks Bluetooth Always + Peripheral permissions
  • Windows: Checks adapter availability and peripheral role support

HasClientDevice(Func<IBluetoothConnectedDevice, bool>)

Determines if there is at least one connected client device that matches the specified filter.

public bool HasClientDevice(Func<IBluetoothConnectedDevice, bool> filter)

Parameters

filter Func<IBluetoothConnectedDevice, bool>

A function to filter devices. Should return true for matching devices.

Returns

bool

True if at least one matching device is found; otherwise, false.

HasClientDevice(string)

Determines if there is a connected client device with the specified ID.

public bool HasClientDevice(string id)

Parameters

id string

The ID of the device to check for.

Returns

bool

True if a device with the specified ID is found; otherwise, false.

HasService(Func<IBluetoothLocalService, bool>)

Checks if a hosted GATT service that matches the specified filter exists.

public bool HasService(Func<IBluetoothLocalService, bool> filter)

Parameters

filter Func<IBluetoothLocalService, bool>

A function to filter services. Should return true for the desired service.

Returns

bool

True if a matching service exists, false otherwise.

HasService(Guid)

Checks if a hosted GATT service with the specified UUID exists.

public bool HasService(Guid id)

Parameters

id Guid

The UUID of the service to check for.

Returns

bool

True if a matching service exists, false otherwise.

NativeCreateServiceAsync(Guid, string?, bool, TimeSpan?, CancellationToken)

Creates a new local Bluetooth service with the specified parameters.

protected abstract ValueTask<IBluetoothLocalService> NativeCreateServiceAsync(Guid id, string? name = null, bool isPrimary = true, TimeSpan? timeout = null, CancellationToken cancellationToken = default)

Parameters

id Guid
name string
isPrimary bool
timeout TimeSpan?
cancellationToken CancellationToken

Returns

ValueTask<IBluetoothLocalService>

NativeHasBroadcasterPermissionsAsync()

Platform-specific implementation to check if broadcaster permissions are granted.

protected abstract ValueTask<bool> NativeHasBroadcasterPermissionsAsync()

Returns

ValueTask<bool>

True if permissions are granted, otherwise false.

Remarks

Implement platform-specific permission checks. Should NOT throw exceptions. Return false if permissions cannot be determined.

NativeRefreshIsRunning()

Refreshes the native running state from the underlying platform.

protected abstract void NativeRefreshIsRunning()

NativeRequestBroadcasterPermissionsAsync(CancellationToken)

Platform-specific implementation to request broadcaster permissions.

protected abstract ValueTask NativeRequestBroadcasterPermissionsAsync(CancellationToken cancellationToken)

Parameters

cancellationToken CancellationToken

Cancellation token to cancel the permission request operation.

Returns

ValueTask

Remarks

Implement platform-specific permission request dialogs. Throw native exceptions on failure - base class will wrap them in BluetoothPermissionException.

Exceptions

Exception

Throw platform-specific exceptions on failure.

NativeStartAsync(BroadcastingOptions, TimeSpan?, CancellationToken)

Starts the native Bluetooth broadcaster with the specified options. This method is called by StartBroadcastingAsync(BroadcastingOptions?, PermissionOptions?, TimeSpan?, CancellationToken) to perform platform-specific start operations.

protected abstract ValueTask NativeStartAsync(BroadcastingOptions options, TimeSpan? timeout = null, CancellationToken cancellationToken = default)

Parameters

options BroadcastingOptions
timeout TimeSpan?
cancellationToken CancellationToken

Returns

ValueTask

NativeStopAsync(TimeSpan?, CancellationToken)

Stops the native Bluetooth broadcaster. This method is called by StopBroadcastingAsync(TimeSpan?, CancellationToken) to perform platform-specific stop operations.

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

Parameters

timeout TimeSpan?
cancellationToken CancellationToken

Returns

ValueTask

OnIsRunningChanged(bool)

Called when the IsRunning property changes.

protected virtual void OnIsRunningChanged(bool value)

Parameters

value bool

The new running state value.

OnStartFailed(Exception)

Called when the start operation has failed. Sets the TaskCompletionSource exception or dispatches to the unhandled exception listener.

protected void OnStartFailed(Exception e)

Parameters

e Exception

The exception that caused the start to fail.

OnStartSucceeded()

Called when the start operation has succeeded. Sets the TaskCompletionSource to signal completion of the start operation.

protected void OnStartSucceeded()

Exceptions

BroadcasterUnexpectedStartException

Thrown when the broadcaster starts unexpectedly without a pending start operation.

OnStopFailed(Exception)

Called when the stop operation has failed. Sets the TaskCompletionSource exception or dispatches to the unhandled exception listener.

protected void OnStopFailed(Exception e)

Parameters

e Exception

The exception that caused the stop to fail.

OnStopSucceeded()

Called when the stop operation has succeeded. Sets the TaskCompletionSource to signal completion of the stop operation.

protected void OnStopSucceeded()

Exceptions

BroadcasterUnexpectedStopException

Thrown when the scanner stops unexpectedly without a pending stop operation.

RefreshAsync(CancellationToken)

Refreshes the broadcaster's properties and state.

protected virtual Task RefreshAsync(CancellationToken cancellationToken)

Parameters

cancellationToken CancellationToken

A token to monitor for cancellation requests.

Returns

Task

Remarks

This method is called periodically by the ticker to ensure the broadcaster's properties and state are up-to-date. Derived classes should override this method to implement the logic for refreshing the broadcaster's properties, such as checking the broadcasting state, updating the list of active services, or any other relevant information. The base implementation throws a NotImplementedException, indicating that derived classes must provide their own implementation of the refresh logic specific to the platform or implementation.

RemoveAllServicesAsync(TimeSpan?, CancellationToken)

Removes all hosted services from the broadcaster.

public ValueTask RemoveAllServicesAsync(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.

RemoveClientDevice(IBluetoothConnectedDevice)

Removes a client device from the collection. Called by platform implementations when a client disconnects.

protected void RemoveClientDevice(IBluetoothConnectedDevice device)

Parameters

device IBluetoothConnectedDevice

The client device to remove.

RemoveClientDevice(string)

Removes a client device from the collection by ID. Called by platform implementations when a client disconnects.

protected void RemoveClientDevice(string id)

Parameters

id string

The ID of the client device to remove.

RemoveServiceAsync(IBluetoothLocalService, TimeSpan?, CancellationToken)

Removes a hosted GATT service from the broadcaster.

public ValueTask RemoveServiceAsync(IBluetoothLocalService localService, TimeSpan? timeout = null, CancellationToken cancellationToken = default)

Parameters

localService IBluetoothLocalService

The service to remove.

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.

RemoveServiceAsync(Guid, TimeSpan?, CancellationToken)

Removes a hosted GATT service from the broadcaster.

public ValueTask RemoveServiceAsync(Guid id, TimeSpan? timeout = null, CancellationToken cancellationToken = default)

Parameters

id Guid

The UUID of the service to remove.

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.

RequestBroadcasterPermissionsAsync(CancellationToken)

Requests the necessary broadcaster permissions from the user.

public ValueTask RequestBroadcasterPermissionsAsync(CancellationToken cancellationToken = default)

Parameters

cancellationToken CancellationToken

Cancellation token to cancel the permission request operation.

Returns

ValueTask

Task that completes when permissions are requested.

Remarks

Platform-specific behavior:

  • Android: Shows system permission dialog; can be requested multiple times
  • iOS/macOS: Requests both Bluetooth Always and Peripheral permissions
  • Windows: Checks adapter state and requests radio access if needed

Exceptions

BluetoothPermissionException

Thrown when permission request fails or is denied. Check InnerException for platform-specific details.

StartBroadcastingAsync(BroadcastingOptions?, PermissionOptions?, TimeSpan?, CancellationToken)

Asynchronously starts the Bluetooth activity with an optional timeout.

public ValueTask StartBroadcastingAsync(BroadcastingOptions? broadcastingOptions = null, PermissionOptions? permissionOptions = null, TimeSpan? timeout = null, CancellationToken cancellationToken = default)

Parameters

broadcastingOptions BroadcastingOptions

The broadcasting options to use when starting the broadcaster. If null, default options will be used.

permissionOptions PermissionOptions

The permission options to use when starting the broadcaster. 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 start operation.

Remarks

Ensures that the Bluetooth activity is initialized and ready for use.

Exceptions

InvalidOperationException

Thrown when broadcasting is already active.

PlatformNotSupportedException

Thrown when the platform doesn't support peripheral mode.

TimeoutException

Thrown when the operation times out.

OperationCanceledException

Thrown when the operation is cancelled.

StartBroadcastingIfNeededAsync(BroadcastingOptions?, PermissionOptions?, TimeSpan?, CancellationToken)

Asynchronously starts the Bluetooth activity if it is not already running, with an optional timeout.

public ValueTask StartBroadcastingIfNeededAsync(BroadcastingOptions? broadcastingOptions = null, PermissionOptions? permissionOptions = null, TimeSpan? timeout = null, CancellationToken cancellationToken = default)

Parameters

broadcastingOptions BroadcastingOptions

The broadcasting options to use when starting the broadcaster. If null, default options will be used.

permissionOptions PermissionOptions

The permission options to use when starting the broadcaster. 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 start operation.

Remarks

Checks if the Bluetooth activity is already running before attempting to start it.

StopBroadcastingAsync(TimeSpan?, CancellationToken)

Asynchronously stops the Broadcaster with an optional timeout.

public ValueTask StopBroadcastingAsync(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 stop operation.

Remarks

Ensures that the Broadcaster and its resources are safely released.

Exceptions

InvalidOperationException

Thrown when broadcasting is not active.

TimeoutException

Thrown when the operation times out.

OperationCanceledException

Thrown when the operation is cancelled.

StopBroadcastingIfNeededAsync(TimeSpan?, CancellationToken)

Asynchronously stops the Broadcaster if it is running, with an optional timeout.

public ValueTask StopBroadcastingIfNeededAsync(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 stop operation.

Remarks

Checks if the Broadcaster is running before attempting to stop it.

ToString()

Returns a string that represents the current object.

public override string ToString()

Returns

string

Events

ClientDeviceListChanged

Event triggered when the list of connected client devices changes.

public event EventHandler<ClientDeviceListChangedEventArgs>? ClientDeviceListChanged

Event Type

EventHandler<ClientDeviceListChangedEventArgs>

ClientDevicesAdded

Event triggered when client devices connect.

public event EventHandler<ClientDevicesAddedEventArgs>? ClientDevicesAdded

Event Type

EventHandler<ClientDevicesAddedEventArgs>

ClientDevicesRemoved

Event triggered when client devices disconnect.

public event EventHandler<ClientDevicesRemovedEventArgs>? ClientDevicesRemoved

Event Type

EventHandler<ClientDevicesRemovedEventArgs>

RunningStateChanged

Occurs when the running state of the Bluetooth activity changes.

public event EventHandler? RunningStateChanged

Event Type

EventHandler

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>

Started

Occurs when the Bluetooth activity has started.

public event EventHandler? Started

Event Type

EventHandler

Starting

Occurs when the Bluetooth activity is starting.

public event EventHandler? Starting

Event Type

EventHandler

Stopped

Occurs when the Broadcaster has stopped.

public event EventHandler? Stopped

Event Type

EventHandler

Stopping

Occurs when the Broadcaster is stopping.

public event EventHandler? Stopping

Event Type

EventHandler