@sfourdrinier/react-native-ble-plx
v3.7.10
Published
React Native Bluetooth Low Energy library
Maintainers
Readme
Fork Notice: This library is forked from dotintent/react-native-ble-plx because the official library does not support Expo SDK 54+ and React Native 0.81+. We've updated it to work with modern React Native and converted it from Flow to TypeScript.
Looking for maintainers! We're looking for volunteers to help maintain this fork. If you're interested, please open an issue or submit a PR.
Maintainers note: This repo is managed with
pnpm(not yarn/npm).
About this library
It supports:
- observing device's Bluetooth adapter state
- scanning BLE devices
- making connections to peripherals
- discovering services/characteristics
- reading/writing characteristics
- observing characteristic notifications/indications
- reading RSSI
- negotiating MTU
- background mode on iOS
- NEW: background mode on Android (foreground service)
- NEW: automatic reconnection with exponential backoff
- NEW: connection queue with retry logic
- turning the device's Bluetooth adapter on
It does NOT support:
- bluetooth classic devices.
- communicating between phones using BLE (Peripheral support)
- bonding peripherals
- beacons
Table of Contents
- Compatibility
- Recent Changes
- Documentation & Support
- Configuration & Installation
- iOS BLE State Restoration
- Android Background Mode
- Reliability Features
- Troubleshooting
- Releasing
- Contributions
Compatibility
Note: This is a fork of
dotintent/react-native-ble-plxmaintained at@sfourdrinier/react-native-ble-plx. It has been converted from Flow to TypeScript and updated for modern React Native.
Minimum Requirements (v3.5.0+):
- React Native 0.81.4+
- Expo SDK 54+
- Node.js 18+
| React Native | Expo SDK | This Fork | | ------------ | -------- | --------- | | 0.81.4+ | 54+ | :white_check_mark: | | < 0.81 | < 54 | :x: Not supported |
For older React Native versions, use the upstream dotintent/react-native-ble-plx library.
Recent Changes
3.7.7 (This Fork)
- Connection Manager: NEW unified
ConnectionManagerwith retry logic, timeout support, and automatic reconnection - Critical Bug Fixes (4 Stop-Ship Issues Resolved):
- ✅ Fixed promise coalescing hang when multiple callers connect to same device
- ✅ Fixed memory leak in destroy() for auto-reconnect subscriptions
- ✅ Fixed connection storms from repeated disconnect events
- ✅ Fixed race condition where cancel() + auto-reconnect could still trigger retries (attemptId pattern)
- Fixed foreground service crash on null intent restart (Android)
- Fixed ReconnectionManager race condition (callbacks after disable)
- Fixed ConnectionQueue blocking all devices during retry delays
- Added proper error normalization to BleError
- Android 12+ Compatibility (Production-Critical):
- ✅ Fixed STOP service crash (now uses
stopService()instead ofstartService()) - ✅ Added foreground state check before starting service (prevents
ForegroundServiceStartNotAllowedException) - ✅ Safe UPDATE notification handling with try-catch
- ✅ Verified Android 14 (API 34) compliance with
FOREGROUND_SERVICE_CONNECTED_DEVICE
- ✅ Fixed STOP service crash (now uses
- Improvements:
- Connection timeout support (prevents hangs)
- Concurrent connections to different devices
- Comprehensive test suite (8 tests covering all critical bugs)
- Production-grade error handling and cleanup
- Deprecated:
ConnectionQueueandReconnectionManager(useConnectionManagerinstead)
3.7.6 (This Fork)
- Refactored iOS BLE restoration to work standalone without external dependencies
- Removed BleRestoration pod dependency, added bundled fallback registry
- Improved Expo config plugin to use autolinking config
3.7.0 (This Fork)
- Android Background Mode: Added foreground service support for reliable background BLE operations
- Connection Queue:
ConnectionQueueclass with automatic retry and exponential backoff - Reconnection Manager:
ReconnectionManagerclass for automatic reconnection on unexpected disconnects - New Types: Added
BackgroundModeOptionsandReconnectionOptionstypes - Expo config plugin now supports
androidEnableForegroundServiceoption
3.5.x (This Fork)
- Converted from Flow to TypeScript
- Updated for React Native 0.81.4 and Expo SDK 54
- Added iOS BLE state restoration support (optional)
- Fixed TypeScript errors from Flow-to-TS conversion
- Dropped support for React Native < 0.81 and Expo < 54
3.2.0 (Upstream)
- Added Android Instance checking before calling its method, an error will be visible on the RN side
- Added information related to Android 14 to the documentation.
- Changed destroyClient, cancelTransaction, setLogLevel, startDeviceScan, stopDeviceScan calls to promises to allow error reporting if it occurs.
- Fixed one of the functions calls that clean up the BLE instance after it is destroyed.
Current version changes All previous changes
Documentation & Support
Interested in React Native project involving Bluetooth Low Energy? We can help you!
Documentation can be found here.
Quick introduction can be found here
Contact us at intent.
Configuration & Installation
Expo SDK 54+
This package cannot be used in the "Expo Go" app because it requires custom native code. First install the package with yarn, npm, or
npx expo install.
npm install @sfourdrinier/react-native-ble-plx
# or
pnpm add @sfourdrinier/react-native-ble-plxAfter installing, add the config plugin to the plugins array of your app.json or app.config.js:
{
"expo": {
"plugins": ["@sfourdrinier/react-native-ble-plx"]
}
}Then you should build the version using native modules (e.g. with npx expo prebuild command).
And install it directly into your device with npx expo run:android.
You can find more details in the "Adding custom native code" guide.
API
The plugin provides props for extra customization. Every time you change the props or plugins, you'll need to rebuild (and prebuild) the native app. If no extra properties are added, defaults will be used.
debug(boolean): Enable debug logging for the Expo config plugin. You can also setBLEPLX_PLUGIN_DEBUG=1(ortrue/yes) in your environment to enable logs without changing config. Defaultfalse.- When enabled, this also stamps a runtime-native flag (
BlePlxDebugLogging) into iOSInfo.plistand AndroidAndroidManifest.xmlmetadata so native debug logs can be gated consistently across platforms. isBackgroundEnabled(boolean): Enable background BLE support on Android. Adds<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>to theAndroidManifest.xml. Defaultfalse.neverForLocation(boolean): Set to true only if you can strongly assert that your app never derives physical location from Bluetooth scan results. The location permission will be still required on older Android devices. Note, that some BLE beacons are filtered from the scan results. Android SDK 31+. Defaultfalse. WARNING: This parameter is experimental and BLE might not work. Make sure to test before releasing to production.modes(string[]): Adds iOSUIBackgroundModesto theInfo.plist. Options are:peripheral, andcentral. Defaults to undefined.bluetoothAlwaysPermission(string | false): Sets the iOSNSBluetoothAlwaysUsageDescriptionpermission message to theInfo.plist. Settingfalsewill skip adding the permission. Defaults toAllow $(PRODUCT_NAME) to connect to bluetooth devices.iosEnableRestoration(boolean): Opt-in to the iOS BLE state restoration subspec (disabled by default). When true, the Podfile will includereact-native-ble-plx/Restorationand the adapter will register with a restoration registry if present.iosRestorationIdentifier(string): Custom CBCentralManager restoration identifier. Written toInfo.plistasBlePlxRestoreIdentifierand passed toBleManagerfor state restoration. Defaults tocom.reactnativebleplx.restore.androidEnableForegroundService(boolean): NEW Enable Android foreground service for background BLE operations. Adds necessary permissions (FOREGROUND_SERVICE,FOREGROUND_SERVICE_CONNECTED_DEVICE) and service declaration toAndroidManifest.xml. Defaultfalse.
Expo SDK 48 supports iOS 13+ which means
NSBluetoothPeripheralUsageDescriptionis fully deprecated. It is no longer setup in@config-plugins/[email protected]and greater.
Example
{
"expo": {
"plugins": [
[
"@sfourdrinier/react-native-ble-plx",
{
"isBackgroundEnabled": true,
"modes": ["peripheral", "central"],
"bluetoothAlwaysPermission": "Allow $(PRODUCT_NAME) to connect to bluetooth devices",
"iosEnableRestoration": true,
"iosRestorationIdentifier": "com.example.myapp.bleplx",
"androidEnableForegroundService": true
}
]
]
}
}iOS (Manual Setup)
- Install the package:
pnpm add @sfourdrinier/react-native-ble-plx(ornpm install --save @sfourdrinier/react-native-ble-plx) - Enter
iosfolder and runpod update - Add
NSBluetoothAlwaysUsageDescriptionininfo.plistfile. (it is a requirement since iOS 13) - If you want to support background mode:
- In your application target go to
Capabilitiestab and enableUses Bluetooth LE AccessoriesinBackground Modessection. - Pass
restoreStateIdentifierandrestoreStateFunctiontoBleManagerconstructor.
- In your application target go to
Optional: iOS BLE State Restoration (Restoration subspec)
- Opt-in via the config plugin: set
iosEnableRestoration: trueand optionallyiosRestorationIdentifierto a stable string. - The plugin writes
BlePlxRestoreIdentifierintoInfo.plistand injects thereact-native-ble-plx/Restorationsubspec into your Podfile. - In JS, pass the same identifier to
BleManager:
const manager = new BleManager({
restoreStateIdentifier: 'com.example.myapp.bleplx',
restoreStateFunction: (restoredState) => {
// Rehydrate your app, reconnect devices, etc.
},
});- The Restoration subspec exposes a Swift adapter (
BlePlxRestorationAdapter) that will register with any restoration registry present in the host app (for example, a sharedBleRestorationRegistry). If no registry is present, it is a no-op.
Android (Manual Setup)
Install the package:
pnpm add @sfourdrinier/react-native-ble-plx(ornpm install --save @sfourdrinier/react-native-ble-plx)In top level
build.gradlemake sure that min SDK version is at least 23:buildscript { ext { ... minSdkVersion = 23 ...In
build.gradlemake sure to add jitpack repository to known repositories:allprojects { repositories { ... maven { url 'https://www.jitpack.io' } } }In
AndroidManifest.xml, add Bluetooth permissions and update<uses-sdk/>:<manifest xmlns:android="http://schemas.android.com/apk/res/android"> ... <!-- Android >= 12 --> <uses-permission android:name="android.permission.BLUETOOTH_SCAN" /> <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" /> <!-- Android < 12 --> <uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" /> <!-- common --> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <!-- Add this line if your application always requires BLE. More info can be found on: https://developer.android.com/guide/topics/connectivity/bluetooth-le.html#permissions --> <uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/> ...(Optional) In SDK 31+ You can remove
ACCESS_FINE_LOCATION(or mark it asandroid:maxSdkVersion="30") fromAndroidManifest.xmland addneverForLocationflag intoBLUETOOTH_SCANpermissions which says that you will not use location based on scanning eg:<uses-permission android:name="android.permission.INTERNET" /> <!-- Android >= 12 --> <uses-permission android:name="android.permission.BLUETOOTH_SCAN" android:usesPermissionFlags="neverForLocation" /> <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" /> <!-- Android < 12 --> <uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" android:maxSdkVersion="30" /> ...With
neverForLocationflag active, you no longer need to ask forACCESS_FINE_LOCATIONin your app
iOS BLE State Restoration (Optional)
This fork includes optional support for iOS BLE state restoration, allowing your app to automatically reconnect to BLE devices after iOS terminates it in the background.
Why Use State Restoration?
| Scenario | Without Restoration | With Restoration | |----------|---------------------|------------------| | App killed by iOS while connected | Connection lost, user must manually reconnect | Auto-reconnects when device sends data | | Phone rebooted while wearing sensor | Must open app and reconnect | System restores connection automatically | | Long recording session (hours) | Risk of disconnection if iOS reclaims memory | Seamless reconnection maintains session |
How It Works
- User connects to a BLE device and starts streaming data
- User switches to another app or locks the phone
- iOS terminates your app to free memory (not a crash - iOS reclaiming resources)
- Later, the BLE device sends data (e.g., user is still wearing it)
- iOS wakes your app in the background with the restoration state
BlePlxRestorationAdapterhandles automatic reconnection
Enabling Restoration (Expo)
{
"expo": {
"plugins": [
[
"@sfourdrinier/react-native-ble-plx",
{
"isBackgroundEnabled": true,
"modes": ["central"],
"iosEnableRestoration": true,
"iosRestorationIdentifier": "com.yourapp.bleplx"
}
]
]
}
}Then in your JavaScript code:
const manager = new BleManager({
restoreStateIdentifier: 'com.yourapp.bleplx', // Must match iosRestorationIdentifier
restoreStateFunction: (restoredState) => {
if (restoredState?.connectedPeripherals) {
console.log('Restored peripherals:', restoredState.connectedPeripherals);
// Reconnect to devices, resume streaming, etc.
}
},
});Enabling Restoration (Manual / Non-Expo)
Add the Restoration subspec to your Podfile:
pod 'react-native-ble-plx/Restoration', :path => '../node_modules/@sfourdrinier/react-native-ble-plx'Add to your
Info.plist:<key>BlePlxRestoreIdentifier</key> <string>com.yourapp.bleplx</string>Enable background modes in Xcode:
Capabilities→Background Modes→Uses Bluetooth LE accessories
Not Using Restoration?
No action needed. The restoration feature is entirely opt-in:
- The
Restorationsubspec is not included by default - Native code uses runtime reflection - if restoration classes aren't present, it's a no-op
- No changes to the JavaScript API
- Works exactly like upstream
react-native-ble-plx
Multi-Adapter Support (Advanced)
For apps using multiple BLE SDKs (e.g., Polar SDK + generic BLE-PLX), you can provide your own BleRestorationRegistry implementation with device-to-adapter routing. The bundled adapter uses reflection to find registries:
- Bundled fallback: Works out of the box via
BlePlxBundledRestorationRegistry - Custom registry: If you provide a class named
BleRestorationRegistry, it takes priority
// Your custom BleRestorationRegistry implementation
@objc(BleRestorationRegistry)
public final class BleRestorationRegistry: NSObject {
@objc public static let shared = BleRestorationRegistry()
@objc(registerAdapter:)
public func registerAdapter(_ cls: AnyClass) { /* ... */ }
@objc(registerDevice:forAdapter:)
public func registerDevice(_ deviceId: String, for cls: AnyClass) { /* ... */ }
}This ensures that when iOS restores the app, each device is reconnected by the appropriate SDK.
Android Background Mode (NEW)
⚠️ Android 12+ Requirements (CRITICAL)
If you're targeting Android 12 (API 31) or higher, you MUST follow these requirements:
1. Required Permissions in AndroidManifest.xml
<!-- Android 14+ (API 34+) - Required for foreground service type -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission
android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE"
tools:targetApi="upside_down_cake" />
<!-- Android 12+ (API 31+) - Required for BLE -->
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<!-- Android < 12 -->
<uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />
<!-- Location (required for BLE scanning on all versions) -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />2. Call enableBackgroundMode() While App is in Foreground
Android 12+ restricts starting foreground services from background. You must call enableBackgroundMode() while your app is visible to the user:
// ✅ CORRECT: Call while app is in foreground
const handleStartRecording = async () => {
// User just tapped "Start Recording" button - app is in foreground
await bleManager.enableBackgroundMode({
notificationTitle: 'Recording Session Active',
notificationText: 'Syncing sensor data...'
});
// Now you can safely background the app and BLE will continue
await connectAndStartRecording();
};
// ❌ WRONG: Calling from background task/timer
setTimeout(async () => {
// App may be backgrounded - this will throw on Android 12+
await bleManager.enableBackgroundMode({ /* ... */ });
}, 60000);Error if violated: IllegalStateException: Cannot start foreground service from background on Android 12+
3. Service Type Declaration (Expo Plugin Handles This)
If using the Expo config plugin with androidEnableForegroundService: true, the service type is configured automatically. For manual setup, ensure your service has:
<service
android:name="com.bleplx.BlePlxForegroundService"
android:enabled="true"
android:exported="false"
android:foregroundServiceType="connectedDevice"
tools:targetApi="q" />Platform Compatibility
| Android Version | Min SDK | Target SDK | Requirements |
|----------------|---------|------------|--------------|
| Android 14+ (API 34+) | 24 | 34 | FOREGROUND_SERVICE_CONNECTED_DEVICE permission + service type |
| Android 12-13 (API 31-33) | 24 | 31+ | Foreground state check required |
| Android 8-11 (API 26-30) | 24 | 26+ | Standard foreground service |
| Android < 8 (API < 26) | 24 | - | No foreground service needed |
Basic Usage
Android requires a foreground service to keep BLE operations alive when the app is in the background. This fork adds built-in support for this.
Enabling via Expo Config Plugin
{
"expo": {
"plugins": [
[
"@sfourdrinier/react-native-ble-plx",
{
"isBackgroundEnabled": true,
"androidEnableForegroundService": true
}
]
]
}
}Using in JavaScript
import { BleManager } from '@sfourdrinier/react-native-ble-plx';
const manager = new BleManager();
// Enable background mode before starting BLE operations
await manager.enableBackgroundMode({
notificationTitle: 'Connected to Heart Rate Monitor',
notificationText: 'Syncing health data...'
});
// ... perform BLE operations ...
// Update the notification while running
await manager.updateBackgroundNotification({
notificationTitle: 'Syncing Data',
notificationText: 'Progress: 75%'
});
// Check if background mode is active
const isEnabled = await manager.isBackgroundModeEnabled();
// Disable when done
await manager.disableBackgroundMode();Platform Behavior & iOS/Android Parity
| Feature | iOS | Android | Notes |
|---------|-----|---------|-------|
| Background BLE Operations | ✅ Built-in via UIBackgroundModes | ✅ Foreground Service | Both platforms fully supported |
| Configuration | Info.plist + Expo plugin | Manifest permissions + Expo plugin | Platform-specific setup |
| enableBackgroundMode() API | ✅ No-op (graceful) | ✅ Required | Same API, platform-appropriate behavior |
| disableBackgroundMode() API | ✅ No-op (graceful) | ✅ Stops service | Same API, platform-appropriate behavior |
| updateBackgroundNotification() API | ✅ No-op (graceful) | ✅ Updates notification | iOS doesn't show notification |
| isBackgroundModeEnabled() API | ✅ Returns false | ✅ Returns true/false | Consistent return type |
| Connection Management | ✅ ConnectionManager | ✅ ConnectionManager | 100% API parity |
| Auto-reconnection | ✅ Full support | ✅ Full support | 100% feature parity |
| Retry Logic | ✅ Full support | ✅ Full support | 100% feature parity |
| Timeout Support | ✅ Full support | ✅ Full support | 100% feature parity |
Cross-Platform Code Example:
// This exact code works on BOTH iOS and Android
await bleManager.enableBackgroundMode({
notificationTitle: 'Recording Active', // Shown on Android, ignored on iOS
notificationText: 'Syncing sensor data' // Shown on Android, ignored on iOS
});
// ConnectionManager has 100% API parity between platforms
const connectionManager = new ConnectionManager(bleManager);
await connectionManager.connect(deviceId, {
maxRetries: 5,
timeoutMs: 15000
});✅ Platform Parity Guarantee: All ConnectionManager features, retry logic, auto-reconnection, and timeout support work identically on iOS and Android. Only background mode setup differs due to platform requirements.
Reliability Features (NEW)
ConnectionManager (Recommended)
Unified connection management with retry logic, timeout support, and automatic reconnection - all in one manager:
import { BleManager, ConnectionManager } from '@sfourdrinier/react-native-ble-plx';
const bleManager = new BleManager();
const connectionManager = new ConnectionManager(bleManager);
// Connect with retry logic and timeout
const device = await connectionManager.connect('AA:BB:CC:DD:EE:FF', {
maxRetries: 5,
initialDelayMs: 1000,
timeoutMs: 15000, // Connection timeout
backoffMultiplier: 2
});
// Enable auto-reconnect for a device
connectionManager.enableAutoReconnect('AA:BB:CC:DD:EE:FF', {
maxRetries: 10,
initialDelayMs: 2000,
timeoutMs: 15000
}, {
onConnect: (device) => console.log('Connected!', device.id),
onDisconnect: (deviceId, error) => console.log('Disconnected', deviceId),
onConnectFailed: (deviceId, error) => console.log('Failed', deviceId, error)
});
// Set global callbacks for all devices
connectionManager.setGlobalCallbacks({
onConnect: (device) => console.log('Any device connected:', device.id),
onDisconnect: (deviceId) => console.log('Any device disconnected:', deviceId),
onConnecting: (deviceId, attempt, max) => {
console.log(`Connecting ${deviceId}: attempt ${attempt}/${max}`);
}
});
// Check status
console.log('Is connecting:', connectionManager.isConnecting('AA:BB:CC:DD:EE:FF'));
console.log('Auto-reconnect enabled:', connectionManager.isAutoReconnectEnabled('AA:BB:CC:DD:EE:FF'));
console.log('Active connections:', connectionManager.activeCount);
// Cancel a connection
connectionManager.cancel('AA:BB:CC:DD:EE:FF');
// Disable auto-reconnect
connectionManager.disableAutoReconnect('AA:BB:CC:DD:EE:FF');Key Features:
- ✅ Single state machine per device (no competing retry engines)
- ✅ Concurrent connections to different devices
- ✅ Configurable connection timeout (prevents hangs)
- ✅ Exponential backoff retry logic
- ✅ Automatic reconnection on unexpected disconnects
- ✅ Comprehensive event callbacks (onConnect, onDisconnect, onConnecting, onConnectFailed)
- ✅ Clean cancellation and lifecycle management
Migration Guide: ConnectionQueue + ReconnectionManager → ConnectionManager
If you're using the deprecated ConnectionQueue and ReconnectionManager classes, here's how to migrate to the unified ConnectionManager:
Before (Separate Managers - Deprecated)
import { BleManager, ConnectionQueue, ReconnectionManager } from '@sfourdrinier/react-native-ble-plx';
const bleManager = new BleManager();
const queue = new ConnectionQueue(bleManager);
const reconnectionManager = new ReconnectionManager(bleManager);
// Connect with retry
const device = await queue.connect(deviceId, {
maxRetries: 5,
initialDelayMs: 1000
});
// Enable auto-reconnect
reconnectionManager.enableAutoReconnect(deviceId, {
maxRetries: 10
}, {
onReconnect: (device) => console.log('Reconnected'),
onReconnectFailed: (id, error) => console.log('Failed')
});After (Unified Manager - Recommended)
import { BleManager, ConnectionManager } from '@sfourdrinier/react-native-ble-plx';
const bleManager = new BleManager();
const connectionManager = new ConnectionManager(bleManager);
// Connect with retry AND enable auto-reconnect in one step
connectionManager.enableAutoReconnect(deviceId, {
maxRetries: 10,
initialDelayMs: 2000,
timeoutMs: 15000 // NEW: connection timeout support
}, {
onConnect: (device) => console.log('Connected'), // Fires on initial connect AND reconnects
onDisconnect: (deviceId, error) => console.log('Disconnected'),
onConnectFailed: (deviceId, error) => console.log('Failed')
});
// Initial connection (auto-reconnect handles future disconnects)
const device = await connectionManager.connect(deviceId, {
maxRetries: 5,
timeoutMs: 15000
});Key Benefits of Migration
| Feature | Old (Queue + Reconnection) | New (ConnectionManager) |
|---------|---------------------------|------------------------|
| State Management | Two competing retry engines | Single state machine per device |
| Connection Timeout | ❌ Not supported | ✅ Configurable timeoutMs |
| Race Conditions | ⚠️ Possible bugs | ✅ Fixed with attemptId pattern |
| Memory Leaks | ⚠️ destroy() leaked subscriptions | ✅ Fixed |
| Connection Storms | ⚠️ Repeated disconnects caused storms | ✅ Fixed with guards |
| Concurrent Connections | ⚠️ Queue blocked all devices | ✅ Per-device isolation |
| Event Callbacks | Split between two managers | Unified callbacks |
| Code Complexity | Manage 2 instances | Single instance |
ConnectionQueue (Deprecated)
⚠️ Deprecated: Use
ConnectionManagerinstead for unified connection management.
Manage connection attempts with automatic retry logic and queue management:
import { BleManager, ConnectionQueue } from '@sfourdrinier/react-native-ble-plx';
const manager = new BleManager();
const queue = new ConnectionQueue(manager);
// Connect with automatic retry on failure
const device = await queue.connect('AA:BB:CC:DD:EE:FF', {
maxRetries: 5,
initialDelayMs: 1000,
maxDelayMs: 30000,
backoffMultiplier: 2,
connectionOptions: { timeout: 10000 }
});
// Cancel a pending connection
queue.cancel('AA:BB:CC:DD:EE:FF');
// Cancel all pending connections
queue.cancelAll();
// Check queue status
console.log('Pending connections:', queue.pendingCount);
console.log('Is device pending:', queue.isPending('AA:BB:CC:DD:EE:FF'));ReconnectionManager (Deprecated)
⚠️ Deprecated: Use
ConnectionManagerinstead for unified connection management.
Automatically reconnect when devices disconnect unexpectedly:
import { BleManager, ReconnectionManager } from '@sfourdrinier/react-native-ble-plx';
const manager = new BleManager();
const reconnectionManager = new ReconnectionManager(manager);
// Enable auto-reconnect for a device
reconnectionManager.enableAutoReconnect('AA:BB:CC:DD:EE:FF', {
maxRetries: 10,
initialDelayMs: 1000,
maxDelayMs: 60000,
backoffMultiplier: 1.5
}, {
onReconnect: (device) => {
console.log('Reconnected to', device.id);
},
onReconnectFailed: (deviceId, error) => {
console.log('Failed to reconnect to', deviceId, error);
}
});
// Set global callbacks for all devices
reconnectionManager.setGlobalCallbacks({
onReconnect: (device) => console.log('Any device reconnected:', device.id),
onReconnectFailed: (deviceId) => console.log('Any device failed:', deviceId),
onReconnecting: (deviceId, attempt, max) => {
console.log(`Reconnecting ${deviceId}: attempt ${attempt}/${max}`);
}
});
// Check status
console.log('Is enabled:', reconnectionManager.isEnabled('AA:BB:CC:DD:EE:FF'));
console.log('Is reconnecting:', reconnectionManager.isReconnecting('AA:BB:CC:DD:EE:FF'));
console.log('Retry count:', reconnectionManager.getRetryCount('AA:BB:CC:DD:EE:FF'));
// Disable auto-reconnect
reconnectionManager.disableAutoReconnect('AA:BB:CC:DD:EE:FF');
// Or disable all
reconnectionManager.disableAll();Combining Features for Reliable Background Sync
Use ConnectionManager with background mode for reliable, long-running connections:
import {
BleManager,
ConnectionManager
} from '@sfourdrinier/react-native-ble-plx';
const bleManager = new BleManager();
const connectionManager = new ConnectionManager(bleManager);
async function startReliableSync(deviceId: string) {
// 1. Enable background mode (Android)
await bleManager.enableBackgroundMode({
notificationTitle: 'Syncing Data',
notificationText: 'Connected to device'
});
// 2. Connect with retry logic and auto-reconnect
connectionManager.enableAutoReconnect(deviceId, {
maxRetries: 10,
initialDelayMs: 2000,
timeoutMs: 15000
}, {
onConnect: async (device) => {
// Start or resume data sync when connected
await startDataSync(device);
},
onDisconnect: (deviceId, error) => {
console.log('Device disconnected, will auto-reconnect:', deviceId);
},
onConnectFailed: (deviceId, error) => {
console.error('Failed to reconnect after all retries:', deviceId, error);
}
});
// 3. Initial connection
const device = await connectionManager.connect(deviceId, {
maxRetries: 5,
initialDelayMs: 1000,
timeoutMs: 15000
});
// Auto-reconnect is now active and will handle disconnects automatically
}
Troubleshooting
Releasing
To publish a new version of the package:
Ensure all tests pass:
pnpm test:package pnpm test:pluginCommit your changes with a conventional commit message:
git add . git commit -m "fix: description of fix" git push origin masterBump version in
package.json(follow semver):# Edit package.json to update version git add package.json git commit -m "chore: release X.Y.Z" git push origin masterCreate and push git tag:
git tag vX.Y.Z -m "Release vX.Y.Z" git push origin vX.Y.ZBuild and publish:
pnpm run prepack pnpm publish --access public --no-git-checks
Commit message conventions:
fix:- Bug fixes (patch version)feat:- New features (minor version)chore:- Maintenance tasksdocs:- Documentation updates
Contributions
- Special thanks to @EvanBacon for supporting the expo config plugin.
