Class BleManager

Singleton manager for Bluetooth Low Energy device discovery, connection, and command dispatch.

Inheritance
BleManager
Implements
Namespace: MOSAIC.Components.Manager.BLE
Assembly: MOSAIC.dll
Syntax
public sealed class BleManager : IDisposable
Remarks

BleManager is consumed by any BaseBlock that requires BLE communication (e.g. Myo, future BLE sensor blocks). Because it is a singleton, a single scan/connect surface is shared across all blocks in the pipeline.

Usage pattern (from a block):

var mgr = BleManager.Instance;
await mgr.ScanForBleDevicesAsync(5000, ct);
var device = await mgr.ConnectToDeviceAsync("MyoArmband", sampleLength: 16, ct);
await mgr.SendCommandAsync(device, vibrationCmd, ct);
await mgr.DisconnectDeviceAsync(device, ct);

Thread safety: All public methods are safe to call from any thread. DiscoveredDevices is replaced atomically after each scan; consumers should snapshot the reference before iterating.

Constructors

BleManager()

Private constructor — use Instance to obtain the singleton.

Declaration
private BleManager()

BleManager(IBleBackend)

Declaration
internal BleManager(IBleBackend backend)
Parameters
Type Name Description
IBleBackend backend

Fields

_backend

Declaration
private readonly IBleBackend _backend
Field Value
Type Description
IBleBackend

_disposed

Declaration
private bool _disposed
Field Value
Type Description
bool

_instance

Declaration
private static readonly Lazy<BleManager> _instance
Field Value
Type Description
Lazy<BleManager>

_isScanning

Declaration
private bool _isScanning
Field Value
Type Description
bool

_lock

Declaration
private readonly object _lock
Field Value
Type Description
object

_platformBackendFactory

Declaration
private static Func<IBleBackend>? _platformBackendFactory
Field Value
Type Description
Func<IBleBackend>

Properties

ConnectedDevices

Currently connected devices keyed by their display name.

Declaration
public Dictionary<string, BleDevice> ConnectedDevices { get; }
Property Value
Type Description
Dictionary<string, BleDevice>

DiscoveredDevices

Devices discovered during the most recent ScanForBleDevicesAsync(int, CancellationToken) call. The list is replaced atomically on each scan; take a local reference before iterating.

Declaration
public IReadOnlyList<BleDiscoveredDevice> DiscoveredDevices { get; private set; }
Property Value
Type Description
IReadOnlyList<BleDiscoveredDevice>

Instance

Gets the process-wide singleton instance.

Declaration
public static BleManager Instance { get; }
Property Value
Type Description
BleManager

IsScanning

true while a BLE scan is in progress.

Declaration
public bool IsScanning { get; private set; }
Property Value
Type Description
bool

Methods

ConfigurePlatformBackend(Func<IBleBackend>)

Registers the BLE implementation supplied by a platform head before the singleton is used.

Declaration
public static void ConfigurePlatformBackend(Func<IBleBackend> backendFactory)
Parameters
Type Name Description
Func<IBleBackend> backendFactory
Remarks

The shared MOSAIC assembly targets plain net10.0, so Android/CoreBluetooth types cannot be compiled into it. Mobile heads register their native backend during bootstrap.

ConnectToBluetoothDevice(BleDiscoveredDevice, int)

Backward-compatible overload without CancellationToken.

Declaration
public Task<BleDevice?> ConnectToBluetoothDevice(BleDiscoveredDevice device, int sampleLength)
Parameters
Type Name Description
BleDiscoveredDevice device
int sampleLength
Returns
Type Description
Task<BleDevice>

ConnectToBluetoothDeviceAsync(BleDiscoveredDevice, int, CancellationToken)

Connects to a previously discovered BLE device by its peripheral handle.

Declaration
public Task<BleDevice?> ConnectToBluetoothDeviceAsync(BleDiscoveredDevice device, int sampleLength, CancellationToken ct = default)
Parameters
Type Name Description
BleDiscoveredDevice device

The discovered device (from DiscoveredDevices).

int sampleLength

Expected byte count per EMG sample, passed through to BleDevice.

CancellationToken ct

Cancellation token.

Returns
Type Description
Task<BleDevice>

The connected BleDevice, or null on failure.

ConnectToDevice(string, int)

Backward-compatible overload that matches the old ConnectToDevice signature.

Declaration
public Task<BleDevice?> ConnectToDevice(string name, int sampleLength)
Parameters
Type Name Description
string name
int sampleLength
Returns
Type Description
Task<BleDevice>

ConnectToDeviceAsync(string, int, CancellationToken)

Finds a discovered device whose name contains name and connects to it. A scan must have been completed first via ScanForBleDevicesAsync(int, CancellationToken).

Declaration
public Task<BleDevice?> ConnectToDeviceAsync(string name, int sampleLength, CancellationToken ct = default)
Parameters
Type Name Description
string name

Substring to match against discovered device names (case-sensitive).

int sampleLength

Expected byte count per EMG sample.

CancellationToken ct

Cancellation token.

Returns
Type Description
Task<BleDevice>

The connected BleDevice, or null if not found.

ConnectionRoutineAsync(BleDevice, List<BleCommand>, CancellationToken)

Runs a list of notification-subscription commands sequentially on the given device.

Declaration
public Task ConnectionRoutineAsync(BleDevice device, List<BleCommand> commands, CancellationToken ct = default)
Parameters
Type Name Description
BleDevice device

The connected device.

List<BleCommand> commands

Notification commands to set up.

CancellationToken ct

Cancellation token.

Returns
Type Description
Task

CreateBackend()

Creates the appropriate platform-specific BLE backend.

Declaration
private static IBleBackend CreateBackend()
Returns
Type Description
IBleBackend
Remarks

Selection order (all native — no InTheHand dependency):

  1. Windows — WindowsBleBackend (WinRT Windows.Devices.Bluetooth). Requires net10.0-windows10.0.19041.0 TFM (auto-defines WINDOWS10_0_19041_0_OR_GREATER).
  2. Android — AndroidBleBackend (Android.Bluetooth). Requires Android TFM (auto-defines ANDROID).
  3. macOS / iOS — AppleBleBackend (CoreBluetooth). Requires APPLE_BLE define.
  4. Linux — LinuxBleBackend (BlueZ D-Bus). Requires LINUX_BLE define and Tmds.DBus NuGet.

DisconnectAllDevices()

Backward-compatible overload matching the old DisconnectAllDevices signature.

Declaration
public Task DisconnectAllDevices()
Returns
Type Description
Task

DisconnectAllDevicesAsync(CancellationToken)

Disconnects every connected device and clears ConnectedDevices.

Declaration
public Task DisconnectAllDevicesAsync(CancellationToken ct = default)
Parameters
Type Name Description
CancellationToken ct
Returns
Type Description
Task

DisconnectDevice(BleDevice)

Backward-compatible overload without CancellationToken.

Declaration
public Task DisconnectDevice(BleDevice device)
Parameters
Type Name Description
BleDevice device
Returns
Type Description
Task

DisconnectDeviceAsync(BleDevice, CancellationToken)

Disconnects a single device and removes it from ConnectedDevices.

Declaration
public Task DisconnectDeviceAsync(BleDevice device, CancellationToken ct = default)
Parameters
Type Name Description
BleDevice device
CancellationToken ct
Returns
Type Description
Task

Dispose()

Disconnects all devices and releases resources.

Declaration
public void Dispose()

ScanForBleDevices(int)

Synchronous-signature wrapper kept for backward compatibility with existing blocks. Prefer ScanForBleDevicesAsync(int, CancellationToken) in new code.

Declaration
public Task ScanForBleDevices(int timeMs = 5000)
Parameters
Type Name Description
int timeMs
Returns
Type Description
Task

ScanForBleDevicesAsync(int, CancellationToken)

Scans for BLE devices for the specified duration.

Declaration
public Task ScanForBleDevicesAsync(int timeMs = 5000, CancellationToken ct = default)
Parameters
Type Name Description
int timeMs

Scan duration in milliseconds (default 5 000).

CancellationToken ct

Cancellation token.

Returns
Type Description
Task
Exceptions
Type Condition
PlatformNotSupportedException

Bluetooth is not supported on this platform.

InvalidOperationException

The platform BLE backend failed to initialise or scan.

SendCommand(BleDevice, BleCommand)

Backward-compatible overload matching the old SendCommand signature.

Declaration
public Task SendCommand(BleDevice device, BleCommand command)
Parameters
Type Name Description
BleDevice device
BleCommand command
Returns
Type Description
Task

SendCommandAsync(BleDevice, BleCommand, CancellationToken)

Writes a BLE command using the backend's supported control-write mode.

Declaration
public Task SendCommandAsync(BleDevice device, BleCommand command, CancellationToken ct = default)
Parameters
Type Name Description
BleDevice device

The connected device.

BleCommand command

The command to send.

CancellationToken ct

Cancellation token.

Returns
Type Description
Task
Exceptions
Type Condition
InvalidOperationException

The target characteristic was not found on the device.

StartNotificationAsync(BleDevice, BleCommand, CancellationToken)

Subscribes to BLE notifications on one characteristic and wires incoming data to HandleCharacteristicValue(byte[]).

Declaration
public Task StartNotificationAsync(BleDevice device, BleCommand command, CancellationToken ct = default)
Parameters
Type Name Description
BleDevice device

The connected device.

BleCommand command

Identifies the service/characteristic to subscribe to.

CancellationToken ct

Cancellation token.

Returns
Type Description
Task

Events

DeviceConnected

Raised after a device is successfully connected and added to ConnectedDevices. The argument is the newly connected BleDevice.

Declaration
public event EventHandler<BleDevice>? DeviceConnected
Event Type
Type Description
EventHandler<BleDevice>

DeviceDisconnected

Raised after a device is disconnected and removed from ConnectedDevices. The argument is the disconnected BleDevice.

Declaration
public event EventHandler<BleDevice>? DeviceDisconnected
Event Type
Type Description
EventHandler<BleDevice>

ScanCompleted

Raised when a BLE scan completes. The argument is the number of devices found.

Declaration
public event EventHandler<int>? ScanCompleted
Event Type
Type Description
EventHandler<int>

Implements

IDisposable

Search documentation

Start typing to search the documentation.