npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@sfourdrinier/react-native-ble-plx

v3.7.10

Published

React Native Bluetooth Low Energy library

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:

It does NOT support:

Table of Contents

  1. Compatibility
  2. Recent Changes
  3. Documentation & Support
  4. Configuration & Installation
  5. iOS BLE State Restoration
  6. Android Background Mode
  7. Reliability Features
  8. Troubleshooting
  9. Releasing
  10. Contributions

Compatibility

Note: This is a fork of dotintent/react-native-ble-plx maintained 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 ConnectionManager with 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 of startService())
    • ✅ 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
  • 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: ConnectionQueue and ReconnectionManager (use ConnectionManager instead)

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: ConnectionQueue class with automatic retry and exponential backoff
  • Reconnection Manager: ReconnectionManager class for automatic reconnection on unexpected disconnects
  • New Types: Added BackgroundModeOptions and ReconnectionOptions types
  • Expo config plugin now supports androidEnableForegroundService option

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-plx

After 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 set BLEPLX_PLUGIN_DEBUG=1 (or true/yes) in your environment to enable logs without changing config. Default false.
  • When enabled, this also stamps a runtime-native flag (BlePlxDebugLogging) into iOS Info.plist and Android AndroidManifest.xml metadata 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 the AndroidManifest.xml. Default false.
  • 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+. Default false. WARNING: This parameter is experimental and BLE might not work. Make sure to test before releasing to production.
  • modes (string[]): Adds iOS UIBackgroundModes to the Info.plist. Options are: peripheral, and central. Defaults to undefined.
  • bluetoothAlwaysPermission (string | false): Sets the iOS NSBluetoothAlwaysUsageDescription permission message to the Info.plist. Setting false will skip adding the permission. Defaults to Allow $(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 include react-native-ble-plx/Restoration and the adapter will register with a restoration registry if present.
  • iosRestorationIdentifier (string): Custom CBCentralManager restoration identifier. Written to Info.plist as BlePlxRestoreIdentifier and passed to BleManager for state restoration. Defaults to com.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 to AndroidManifest.xml. Default false.

Expo SDK 48 supports iOS 13+ which means NSBluetoothPeripheralUsageDescription is 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)

  1. Install the package: pnpm add @sfourdrinier/react-native-ble-plx (or npm install --save @sfourdrinier/react-native-ble-plx)
  2. Enter ios folder and run pod update
  3. Add NSBluetoothAlwaysUsageDescription in info.plist file. (it is a requirement since iOS 13)
  4. If you want to support background mode:
    • In your application target go to Capabilities tab and enable Uses Bluetooth LE Accessories in Background Modes section.
    • Pass restoreStateIdentifier and restoreStateFunction to BleManager constructor.

Optional: iOS BLE State Restoration (Restoration subspec)

  • Opt-in via the config plugin: set iosEnableRestoration: true and optionally iosRestorationIdentifier to a stable string.
  • The plugin writes BlePlxRestoreIdentifier into Info.plist and injects the react-native-ble-plx/Restoration subspec 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 shared BleRestorationRegistry). If no registry is present, it is a no-op.

Android (Manual Setup)

  1. Install the package: pnpm add @sfourdrinier/react-native-ble-plx (or npm install --save @sfourdrinier/react-native-ble-plx)

  2. In top level build.gradle make sure that min SDK version is at least 23:

    buildscript {
        ext {
            ...
            minSdkVersion = 23
            ...
  3. In build.gradle make sure to add jitpack repository to known repositories:

    allprojects {
        repositories {
          ...
          maven { url 'https://www.jitpack.io' }
        }
    }
  4. 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"/>
    
        ...
  5. (Optional) In SDK 31+ You can remove ACCESS_FINE_LOCATION (or mark it as android:maxSdkVersion="30" ) from AndroidManifest.xml and add neverForLocation flag into BLUETOOTH_SCAN permissions 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 neverForLocation flag active, you no longer need to ask for ACCESS_FINE_LOCATION in 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

  1. User connects to a BLE device and starts streaming data
  2. User switches to another app or locks the phone
  3. iOS terminates your app to free memory (not a crash - iOS reclaiming resources)
  4. Later, the BLE device sends data (e.g., user is still wearing it)
  5. iOS wakes your app in the background with the restoration state
  6. BlePlxRestorationAdapter handles 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)

  1. Add the Restoration subspec to your Podfile:

    pod 'react-native-ble-plx/Restoration', :path => '../node_modules/@sfourdrinier/react-native-ble-plx'
  2. Add to your Info.plist:

    <key>BlePlxRestoreIdentifier</key>
    <string>com.yourapp.bleplx</string>
  3. Enable background modes in Xcode: CapabilitiesBackground ModesUses Bluetooth LE accessories

Not Using Restoration?

No action needed. The restoration feature is entirely opt-in:

  • The Restoration subspec 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:

  1. Bundled fallback: Works out of the box via BlePlxBundledRestorationRegistry
  2. 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 ConnectionManager instead 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 ConnectionManager instead 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:

  1. Ensure all tests pass:

    pnpm test:package
    pnpm test:plugin
  2. Commit your changes with a conventional commit message:

    git add .
    git commit -m "fix: description of fix"
    git push origin master
  3. Bump 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 master
  4. Create and push git tag:

    git tag vX.Y.Z -m "Release vX.Y.Z"
    git push origin vX.Y.Z
  5. Build 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 tasks
  • docs: - Documentation updates

Contributions

  • Special thanks to @EvanBacon for supporting the expo config plugin.