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
adapterIBluetoothAdapterThe Bluetooth adapter to associate with this broadcaster.
tickerITickerThe ticker for scheduling periodic refresh tasks.
loggerFactoryILoggerFactoryOptional logger factory for creating loggers.
Properties
Adapter
Gets the Bluetooth adapter associated with this broadcaster.
public IBluetoothAdapter Adapter { get; }
Property Value
CurrentBroadcastingOptions
Gets the current broadcasting options being used by the Broadcaster.
public BroadcastingOptions CurrentBroadcastingOptions { get; }
Property Value
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
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
IsRunning
Gets a value indicating whether the Bluetooth activity is actively running.
public bool IsRunning { get; protected set; }
Property Value
IsStarting
Gets a value indicating whether the Bluetooth activity is starting.
public bool IsStarting { get; }
Property Value
IsStopping
Gets a value indicating whether the Broadcaster is stopping.
public bool IsStopping { get; }
Property Value
LoggerFactory
Gets the logger factory for creating loggers within the Bluetooth broadcaster/server implementation.
public ILoggerFactory? LoggerFactory { get; }
Property Value
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
deviceIBluetoothConnectedDeviceThe 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
idGuidThe UUID of the service to add.
namestringAn optional name for the service. If not provided, a default name may be assigned based on the UUID or other heuristics.
isPrimaryboolIndicates whether the service is a primary service. Defaults to true.
timeoutTimeSpan?The timeout for this operation
cancellationTokenCancellationTokenA 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
GetClientDevice(Func<IBluetoothConnectedDevice, bool>)
Returns the first Bluetooth device that matches the specified filter.
public IBluetoothConnectedDevice GetClientDevice(Func<IBluetoothConnectedDevice, bool> filter)
Parameters
filterFunc<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
idstringThe 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
filterFunc<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
idstringThe 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
filterFunc<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
filterFunc<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
idGuidThe 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
filterFunc<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
idGuidThe 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
filterFunc<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
permissionOptionsPermissionOptionsThe permission options containing the strategy for handling permissions.
cancellationTokenCancellationTokenCancellation token to cancel the permission request operation.
Returns
HasBroadcasterPermissionsAsync()
Checks if the application has the necessary broadcaster permissions.
public ValueTask<bool> HasBroadcasterPermissionsAsync()
Returns
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
filterFunc<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
idstringThe 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
filterFunc<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
idGuidThe 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
idGuidnamestringisPrimarybooltimeoutTimeSpan?cancellationTokenCancellationToken
Returns
NativeHasBroadcasterPermissionsAsync()
Platform-specific implementation to check if broadcaster permissions are granted.
protected abstract ValueTask<bool> NativeHasBroadcasterPermissionsAsync()
Returns
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
cancellationTokenCancellationTokenCancellation token to cancel the permission request operation.
Returns
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
optionsBroadcastingOptionstimeoutTimeSpan?cancellationTokenCancellationToken
Returns
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
timeoutTimeSpan?cancellationTokenCancellationToken
Returns
OnIsRunningChanged(bool)
Called when the IsRunning property changes.
protected virtual void OnIsRunningChanged(bool value)
Parameters
valueboolThe 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
eExceptionThe 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
eExceptionThe 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
cancellationTokenCancellationTokenA token to monitor for cancellation requests.
Returns
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
timeoutTimeSpan?The timeout for this operation
cancellationTokenCancellationTokenA 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
deviceIBluetoothConnectedDeviceThe 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
idstringThe 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
localServiceIBluetoothLocalServiceThe service to remove.
timeoutTimeSpan?The timeout for this operation
cancellationTokenCancellationTokenA 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
idGuidThe UUID of the service to remove.
timeoutTimeSpan?The timeout for this operation
cancellationTokenCancellationTokenA 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
cancellationTokenCancellationTokenCancellation 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
broadcastingOptionsBroadcastingOptionsThe broadcasting options to use when starting the broadcaster. If null, default options will be used.
permissionOptionsPermissionOptionsThe permission options to use when starting the broadcaster. If null, default options will be used.
timeoutTimeSpan?The timeout for this operation
cancellationTokenCancellationTokenA 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
broadcastingOptionsBroadcastingOptionsThe broadcasting options to use when starting the broadcaster. If null, default options will be used.
permissionOptionsPermissionOptionsThe permission options to use when starting the broadcaster. If null, default options will be used.
timeoutTimeSpan?The timeout for this operation
cancellationTokenCancellationTokenA 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
timeoutTimeSpan?The timeout for this operation
cancellationTokenCancellationTokenA 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
timeoutTimeSpan?The timeout for this operation
cancellationTokenCancellationTokenA 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
Events
ClientDeviceListChanged
Event triggered when the list of connected client devices changes.
public event EventHandler<ClientDeviceListChangedEventArgs>? ClientDeviceListChanged
Event Type
ClientDevicesAdded
Event triggered when client devices connect.
public event EventHandler<ClientDevicesAddedEventArgs>? ClientDevicesAdded
Event Type
ClientDevicesRemoved
Event triggered when client devices disconnect.
public event EventHandler<ClientDevicesRemovedEventArgs>? ClientDevicesRemoved
Event Type
RunningStateChanged
Occurs when the running state of the Bluetooth activity changes.
public event EventHandler? RunningStateChanged
Event Type
ServiceListChanged
Occurs when the service list changes.
public event EventHandler<ServiceListChangedEventArgs>? ServiceListChanged
Event Type
ServicesAdded
Event triggered when services are added.
public event EventHandler<ServicesAddedEventArgs>? ServicesAdded
Event Type
ServicesRemoved
Event triggered when services are removed.
public event EventHandler<ServicesRemovedEventArgs>? ServicesRemoved
Event Type
Started
Occurs when the Bluetooth activity has started.
public event EventHandler? Started
Event Type
Starting
Occurs when the Bluetooth activity is starting.
public event EventHandler? Starting
Event Type
Stopped
Occurs when the Broadcaster has stopped.
public event EventHandler? Stopped
Event Type
Stopping
Occurs when the Broadcaster is stopping.
public event EventHandler? Stopping