@csllc/blejs-types
v2.0.0
Published
Typescript definitions for BLE packages
Keywords
Readme
@csllc/blejs-types
TypeScript type definitions and a hardware-independent interface for Bluetooth Low Energy, enabling platform-agnostic BLE application code and providing a BleMock test double for unit testing.
Installation
npm install @csllc/blejs-typesOverview
Packages like @abandonware/noble, react-native-ble-manager, and WebBluetooth all expose similar BLE functionality but with incompatible APIs. This package defines the common Ble interface that all BLE adapter packages must satisfy, along with all supporting types.
Upper-level packages such as @csllc/cs1816 depend only on @csllc/blejs-types, so they work with any conforming BLE adapter without modification.
Available adapters:
@csllc/rn-mb-ble— React Native (wrapsreact-native-ble-manager)@csllc/noble-ble— Node.js desktop/Raspberry Pi (wraps@abandonware/noble)
Usage
Type annotations and the Ble interface
import type { Ble, BlePeripheral, BleCharacteristic } from '@csllc/blejs-types';
function startScanning(ble: Ble, serviceUuid: string) {
ble.on('discover', (p: BlePeripheral) => {
console.log('found:', p.name, p.id);
});
ble.startScan([serviceUuid], null, { duration: 10000 });
}Using BleMock in tests
import { BleMock, ConfigMock } from '@csllc/blejs-types';
const config: ConfigMock = {
isSupported: true,
isAllowed: true,
isEnabled: true,
knownPeripherals: [],
discoverablePeripherals: [
{ id: 'abc123', address: 'AA:BB:CC:DD:EE:FF', name: 'Test Dongle', rssi: -60, connected: false, _p: null }
],
rssi: -60,
};
const ble = new BleMock(config);
await ble.initialize();
const discovered: BlePeripheral[] = [];
await ble.startScan(['service-uuid'], (p) => discovered.push(p));
console.log(discovered.length); // 1Updating mock configuration mid-test
const ble = new BleMock();
ble.setConfig({ isSupported: false, isAllowed: false, isEnabled: false,
knownPeripherals: [], discoverablePeripherals: [] });API Reference
interface Ble
The primary interface all BLE adapter packages must implement.
| Method | Signature | Description |
|---|---|---|
| isSupported() | (): Promise<boolean> | Returns true if BLE hardware is available. |
| isAllowed() | (): Promise<boolean> | Returns true if the app has permission to use BLE (may prompt the user). |
| driver() | (): {} \| null | Returns the underlying platform driver object (use sparingly). |
| initialize(options?) | (options?: InitializeOptions): Promise<boolean> | Initializes the BLE stack. Must be called before other methods. |
| enable() | (): Promise<boolean> | Attempts to enable Bluetooth (may prompt user on Android). |
| checkState() | (): Promise<undefined> | Polls and updates BLE state. Useful when returning from background. |
| on(event, fn, context?) | (event: BleEventName, fn: BleCallback): void | Registers an event listener. |
| off(event, fn, context?) | (event: BleEventName, fn: BleCallback): void | Removes an event listener. |
| destroy() | (): Promise<undefined> | Cleans up the BLE stack on app shutdown. |
| getKnownDevices(services) | (services: string[]): Promise<BlePeripheral[]> | Returns cached/bonded peripherals matching the given service UUIDs. |
| startScan(services, cb, options?) | (services: string[], cb: BleDiscoverCallback \| null, options?: StartScanOptions): Promise<void> | Starts scanning for peripherals. |
| stopScan() | (): Promise<void> | Stops an active scan. |
| connect(peripheral) | (peripheral: BlePeripheral): Promise<void> | Connects to a peripheral. |
| disconnect(peripheral, options?) | (peripheral: BlePeripheral, options?: DisconnectOptions): Promise<boolean> | Disconnects from a peripheral. Returns true if it was already disconnected. |
| rssi(peripheral) | (peripheral: BlePeripheral): Promise<number> | Reads the peripheral's RSSI (signal strength). |
| read(peripheral, characteristic) | (peripheral, characteristic): Promise<number[]> | Reads the value of a characteristic. |
| write(peripheral, characteristic, data) | (peripheral, characteristic, data: number[]): Promise<void> | Writes bytes to a characteristic. |
| subscribe(peripheral, characteristic, cb) | (peripheral, characteristic, cb: BleNotifyCallback): Promise<void> | Subscribes to notifications from a characteristic. |
| unsubscribe(peripheral, characteristic) | (peripheral, characteristic): Promise<void> | Cancels notifications from a characteristic. |
| findCharacteristics(peripheral, service, wanted) | (peripheral, service: string, wanted: WantedCharacteristic[]): Promise<Map<string, BleCharacteristic>> | Discovers characteristics by UUID and returns a named map. |
class BleMock implements Ble
A full in-memory implementation of Ble for use in automated tests. Create a new instance per test to avoid shared state.
Constructor
new BleMock(config?: ConfigMock)Methods
| Method | Description |
|---|---|
| setConfig(config: ConfigMock): void | Updates the mock configuration at any time. |
| All Ble interface methods | See Ble interface above. |
Behavior:
startScan()synchronously calls the discover callback and emitsdiscoverfor each entry inconfig.discoverablePeripherals.connect()/disconnect()look up peripherals inknownPeripheralsanddiscoverablePeripheralsbyid.rssi()returnsconfig.rssi(a fixed number or the result of calling it as a function); defaults to-65.read()returns[0, 0, 0](stub).write(),subscribe(),unsubscribe()are no-op stubs.findCharacteristics()returns aMappopulated from thewantedarray.- Simulated delays are included (connect ~200 ms, destroy ~100 ms, etc.) to resemble real hardware.
interface ConfigMock
Configuration object for BleMock.
| Property | Type | Description |
|---|---|---|
| isSupported | boolean \| (() => boolean) | Returned by isSupported(). |
| isAllowed | boolean \| (() => boolean) | Returned by isAllowed(). |
| isEnabled | boolean \| (() => boolean) | Returned by enable(). |
| knownPeripherals | BlePeripheral[] | Returned by getKnownDevices(). |
| discoverablePeripherals | BlePeripheral[] | Reported by startScan(). |
| rssi | number \| (() => number) | (optional) Returned by rssi(). Defaults to -65. |
interface BlePeripheral
Represents a discovered or known BLE peripheral.
| Property | Type | Description |
|---|---|---|
| id | string (readonly) | OS-assigned identifier. Use this to refer to the peripheral. |
| address | string (readonly) | MAC address (may be randomized by the OS). |
| name | string | Display name. |
| rssi | number | Most recent signal strength indication. |
| connected | boolean | Whether currently connected. |
| _p | any (readonly) | Opaque reference to the platform-specific peripheral object. |
interface BleCharacteristic
Represents a GATT characteristic.
| Property | Type | Description |
|---|---|---|
| uuid | string (readonly) | Characteristic UUID. |
| _c | any (readonly) | Opaque reference to the platform-specific characteristic object. |
interface InitializeOptions
| Property | Type | Description |
|---|---|---|
| logger | Logger | (optional) A winston-compatible logger for debug output. |
| rnbm | any | (optional) Custom options passed directly to react-native-ble-manager. |
interface StartScanOptions
| Property | Type | Description |
|---|---|---|
| duration | number | (optional) Scan duration in milliseconds. |
| duplicates | boolean | (optional) Whether to report duplicate advertisements. |
interface DisconnectOptions
| Property | Type | Description |
|---|---|---|
| rnbm | any | (optional) Custom options passed to react-native-ble-manager. |
interface Logger
A winston-compatible logger interface accepted by InitializeOptions.
| Property | Type |
|---|---|
| info | (...a: any) => void |
| error | (...a: any) => void |
| trace | (...a: any) => void |
| warn | (...a: any) => void |
type BleEventName
type BleEventName = 'enable' | 'scanning' | 'discover' | 'disconnect' | 'connect';| Event | Callback arg | Description |
|---|---|---|
| enable | boolean | Bluetooth hardware enabled/disabled state changed. |
| scanning | boolean | Scan started (true) or stopped (false). |
| discover | BlePeripheral | A peripheral was found during a scan. |
| connect | BlePeripheral | A peripheral connected. |
| disconnect | BlePeripheral | A peripheral disconnected. |
Callback types
| Type | Signature | Description |
|---|---|---|
| BleDiscoverCallback | (p: BlePeripheral) => void | Passed to startScan(). |
| BleNotifyCallback | (n: number[]) => void | Passed to subscribe(). |
| BleBooleanCallback | (b: boolean) => void | Used for enable/scanning events. |
| BleStringCallback | (s: string) => void | Used for string events. |
| BleCallback | union of all above | Used by on() / off(). |
