@csllc/rn-mb-ble
v3.0.0
Published
React Native BLE interface compatible with @csllc/blejs-types
Downloads
160
Keywords
Readme
@csllc/rn-mb-ble
React Native BLE adapter that implements the @csllc/blejs-types Ble interface by wrapping react-native-ble-manager, plus React-compatible stores for peripheral and status state management.
Installation
npm install @csllc/rn-mb-blePeer dependencies:
npm install react-native react-native-ble-managerReact Native linking and native module setup for react-native-ble-manager must be completed per its documentation.
Overview
This package exports three things:
BleManager— A module-level object implementing theBleinterface. It wrapsreact-native-ble-managerand normalizes UUIDs for cross-platform use (lowercase on Android, uppercase on iOS).BlePeripheralStore— A React-compatible external store (usable withuseSyncExternalStore) that tracks discovered and connected peripherals.BleStatusStore— A React-compatible external store that tracks the BLE hardware state (availability, authorization, enabled/disabled, scanning).
Usage
Initialize BLE and start scanning
import { BleManager } from '@csllc/rn-mb-ble';
import { serviceUuid } from '@csllc/cs1816';
// Call once on app startup
await BleManager.initialize({ logger: myLogger });
// Check permissions
const allowed = await BleManager.isAllowed();
if (!allowed) throw new Error('BLE permissions denied');
// Enable Bluetooth if not already on (Android)
await BleManager.enable();
// Listen for discovered devices
BleManager.on('discover', (peripheral) => {
console.log('Found:', peripheral.name, peripheral.id);
});
// Start scanning for CS1816 dongles
await BleManager.startScan([serviceUuid], null, { duration: 10000, duplicates: true });
// Stop scanning early
await BleManager.stopScan();Connect to a peripheral
BleManager.on('connect', (peripheral) => {
console.log('Connected to', peripheral.id);
});
await BleManager.connect(peripheral);Read and write characteristics
// findCharacteristics returns a Map<name, BleCharacteristic>
const characteristics = await BleManager.findCharacteristics(
peripheral,
serviceUuid,
[
{ name: 'tx', characteristic: '49535343-8841-43F4-A8D4-ECBE34729BB3', required: true },
{ name: 'rx', characteristic: '49535343-1E4D-4BD9-BA61-23C647249616', required: true },
]
);
const txChar = characteristics.get('tx')!;
// Subscribe to notifications
await BleManager.subscribe(peripheral, txChar, (data: number[]) => {
console.log('Notification:', data);
});
// Write bytes
await BleManager.write(peripheral, txChar, [0x01, 0x02, 0x03]);
// Read bytes
const value = await BleManager.read(peripheral, txChar);
// Unsubscribe
await BleManager.unsubscribe(peripheral, txChar);Using BleStatusStore with React
import { BleStatusStore } from '@csllc/rn-mb-ble';
import { useSyncExternalStore } from 'react';
BleStatusStore.initialize({ logger: myLogger });
function MyComponent() {
const status = useSyncExternalStore(
BleStatusStore.subscribe,
BleStatusStore.getSnapshot
);
if (!status.isReady) return <Loading />;
if (!status.isEnabled) return <EnableBluetooth onPress={() => BleStatusStore.enable()} />;
return <Text>BLE is ready</Text>;
}Using BlePeripheralStore with React
import { BlePeripheralStore } from '@csllc/rn-mb-ble';
import { useSyncExternalStore } from 'react';
BlePeripheralStore.initialize({ logger: myLogger });
function DeviceList() {
const peripherals = useSyncExternalStore(
BlePeripheralStore.subscribe,
BlePeripheralStore.getSnapshot
);
return [...peripherals.values()].map(bp => (
<DeviceRow key={bp.id} bp={bp}
onConnect={() => BlePeripheralStore.connect(bp)}
onDisconnect={() => BlePeripheralStore.disconnect(bp)}
/>
));
}Cleanup on app shutdown
await BleManager.destroy();
BlePeripheralStore.destroy();
BleStatusStore.destroy();API Reference
BleManager (default export from ./BleManager)
A module-level singleton object implementing the full Ble interface from @csllc/blejs-types. It wraps react-native-ble-manager.
UUID normalization: UUIDs are automatically normalized to lowercase on Android and uppercase on iOS before being passed to react-native-ble-manager.
| Method | Returns | Description |
|---|---|---|
| isSupported() | Promise<boolean> | Always returns true (platform compatibility is enforced at the app store level). |
| isAllowed() | Promise<boolean> | Requests or checks BLE permissions. On Android 12+ requests BLUETOOTH_SCAN and BLUETOOTH_CONNECT; on Android <12 requests ACCESS_FINE_LOCATION; on iOS always returns true. |
| driver() | {} \| null | Returns the underlying react-native-ble-manager module. |
| initialize(options?) | Promise<boolean> | Starts the BLE manager, registers native event handlers. Must be called before any other method. |
| enable() | Promise<boolean> | Attempts to enable Bluetooth (Android only; on iOS always returns true). |
| checkState() | Promise<undefined> | Polls the current BLE adapter state and emits enable events accordingly. |
| on(event, fn, context?) | void | Registers an event listener. |
| off(event, fn, context?) | void | Removes an event listener. |
| destroy() | Promise<undefined> | Removes all native event handlers and cleans up. |
| getKnownDevices(services) | Promise<BlePeripheral[]> | Returns bonded peripherals (Android) and currently-connected peripherals matching the service list. |
| startScan(services, cb, options?) | Promise<void> | Starts BLE scanning. Uses LowLatency scan mode and AllMatches callback type. |
| stopScan() | Promise<void> | Stops an active scan. |
| connect(peripheral) | Promise<void> | Connects to a peripheral; includes a 900 ms post-connection delay for bonding to settle. |
| disconnect(peripheral, options?) | Promise<boolean> | Disconnects. Pass options.rnbm.force = true for a forced disconnect. |
| rssi(peripheral) | Promise<number> | Reads the peripheral's RSSI. |
| read(peripheral, characteristic) | Promise<number[]> | Reads a characteristic value. |
| write(peripheral, characteristic, data) | Promise<void> | Writes bytes to a characteristic. |
| subscribe(peripheral, characteristic, cb) | Promise<void> | Starts notifications on a characteristic. |
| unsubscribe(peripheral, characteristic) | Promise<void> | Stops notifications on a characteristic. |
| findCharacteristics(peripheral, service, wanted) | Promise<Map<string, BleCharacteristic>> | Calls retrieveServices and returns a map of name-to-characteristic for the requested UUIDs. Throws if a required characteristic is missing. |
Events emitted on the internal event bus
| Event | Arg | Trigger |
|---|---|---|
| enable | boolean | Bluetooth adapter state changed (on = true). |
| scanning | boolean | Scan started or stopped. |
| discover | BlePeripheral | A peripheral was discovered during a scan. |
| disconnect | string (peripheral id) | A peripheral disconnected. |
BlePeripheralStore
A React-compatible external store that accumulates discovered and known peripherals and tracks connection state.
Methods
| Method | Returns | Description |
|---|---|---|
| initialize(options) | void | Loads known devices and registers discover/connect/disconnect listeners on BleManager. |
| destroy() | void | Removes all event listeners. |
| subscribe(listener) | () => void | Registers a change listener. Returns an unsubscribe function. Compatible with useSyncExternalStore. |
| getSnapshot() | Map<string, BlePeripheralState> | Returns the current peripheral map. Compatible with useSyncExternalStore. |
| remove(id) | void | Removes a peripheral by ID. |
| connect(bp) | Promise<void> | Connects to a peripheral and updates state. |
| disconnect(bp) | Promise<void> | Disconnects from a peripheral and updates state. |
class BlePeripheralState
Wraps a BlePeripheral with UI-friendly connection state fields.
| Property | Type | Description |
|---|---|---|
| id | string | Peripheral ID. |
| name | string | Peripheral display name. |
| rssi | number | Signal strength. |
| connecting | boolean | A connection or disconnection attempt is in progress. |
| connected | boolean | Currently connected. |
| known | boolean | Retrieved from the OS as a previously-used device. |
| p | BlePeripheral | The underlying BlePeripheral. |
BleStatusStore
A React-compatible external store that tracks the overall BLE hardware state.
Methods
| Method | Returns | Description |
|---|---|---|
| initialize(options) | void | Queries isSupported, isAllowed, and registers enable/scanning listeners. |
| destroy() | void | Removes event listeners. |
| enable() | Promise<boolean> | Delegates to BleManager.enable(). |
| checkState() | Promise<undefined> | Delegates to BleManager.checkState(). |
| startScan(services, duration) | Promise<void> | Starts a scan with duplicates: true. |
| stopScan() | Promise<void> | Stops the active scan. |
| subscribe(listener) | () => void | Registers a change listener. Returns an unsubscribe function. Compatible with useSyncExternalStore. |
| getSnapshot() | BleState | Returns the current BLE state snapshot. |
interface BleState
| Property | Type | Description |
|---|---|---|
| isReady | boolean | false until initialize() completes. |
| isAvailable | boolean | BLE hardware exists on the device. |
| isAuthorized | boolean | App has BLE permissions. |
| isEnabled | boolean | Bluetooth is currently turned on. |
| isScanning | boolean | A scan is currently active. |
