react-native-ble-plx

repository·master·Indexed 25 days ago

https://github.com/dotintent/react-native-ble-plx

A React Native Bluetooth Low Energy (BLE) library version 3.5.1 for interacting with BLE devices. It provides functionality for scanning, connecting, discovering services and characteristics, reading/writing data, and observing notifications. The library includes a BleManager for API entry and supports background mode, custom error handling via BleErrorCode, and specific configurations for Android and iOS, including support for Expo SDK 43+ via a config plugin.

Tokens
16.3K
Snippets
43
Records
116
Agent score
83%

What's inside react-native-ble-plx

  1. Setup and usage BLE device emulator with nRF Connect

    master

    To test the react-native-ble-plx library using a BLE device emulator, you need the BLE-PLX-example.xml file and the nRF Connect app (available on Android and iOS).

    1. Configure the GATT Server

    1. Open the nRF Connect app.
    2. Navigate to the Configure GATT server screen.
    3. Use the import option in the top bar to import BLE-PLX-example.xml.
    4. Go to the ADVERTISER tab and configure the advertising packet:
      • Enable the Connectable checkbox.
      • Set the advertiser name to BLX-PLX-test.
      • Advertising data: Add a Complete Local Name record and a Service UUID record for the Device time (0x1847) service.
      • Scan Response data: Add a Complete Local Name record and a Service UUID record for the Device time (0x1847) service.
    5. Click ok and turn on the BLX-PLX-test advertiser.

    2. Run the Test in the Example App

    1. Open the example app and click Go to nRF test.
    2. Enter the Complete Local Name you configured in the server into the Device name to connect field.
    3. Click Start (grant BLE permissions if prompted).
    4. Once the app starts the Monitor current time characteristic for device test case, return to the nRF Connect app.
    5. Go to the SERVER tab.
    6. Open the Device Time service.
    7. Click the send icon next to the Current Time characteristic and send the value Hi, it works! as TEXT(UTF-8).
    8. The test should complete successfully with a check mark icon.
  2. Reload the application to apply changes

    master

    After modifying your code (e.g., in App.tsx), use the following methods to reload the app and see your changes:

    • Android: Press the <kbd>R</kbd> key twice, or open the Developer Menu (<kbd>Ctrl</kbd> + <kbd>M</kbd> on Windows/Linux or <kbd>Cmd ⌘</kbd> + <kbd>M</kbd> on macOS) and select "Reload".
    • iOS: Press <kbd>Cmd ⌘</kbd> + <kbd>R</kbd> in the iOS Simulator.
  3. Install react-native-ble-plx on iOS (Expo/Podfile and RN 0.60+)

    master

    To install the library in an ejected Expo project or a React Native project with version 0.60 or higher, follow these steps:

    1. Install the package: npm install --save react-native-ble-plx.
    2. Link the library: react-native link react-native-ble-plx.
    3. Add a Swift file: Open the Xcode workspace in the ios folder and create a new empty Swift file. Accept the prompt to create an Objective-C bridging header.
    4. Update Podfile: Add pod 'react-native-ble-plx', :path => '../node_modules/react-native-ble-plx' to your ios/Podfile.
    5. Install pods: Run pod update inside the ios folder.

    Requirements:

    • Minimal iOS version: 8.0.
    • For iOS 13+, add NSBluetoothAlwaysUsageDescription to your info.plist.
    npm install --save react-native-ble-plx
    react-native link react-native-ble-plx
    # Inside ios folder
    pod update
  4. Setup for Android (Bare React Native)

    master
    1. Install the package: npm install --save react-native-ble-plx.
    2. Configure build.gradle:
      • Set minSdkVersion to at least 23.
      • Add maven { url 'https://www.jitpack.io' } to the allprojects.repositories block.
    3. Configure AndroidManifest.xml:
      • Add Bluetooth permissions (see reference below).
      • Add <uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>.

    Android 12+ Permissions:

    • android.permission.BLUETOOTH_SCAN
    • android.permission.BLUETOOTH_CONNECT
    • android.permission.ACCESS_FINE_LOCATION (Common)

    Android 12+ with neverForLocation (Optional): If you do not use location, you can use the neverForLocation flag in the scan permission to avoid requesting ACCESS_FINE_LOCATION.

    // build.gradle
    buildscript {
        ext {
            minSdkVersion = 23
        }
    }
    
    allprojects {
        repositories {
            maven { url 'https://www.jitpack.io' }
        }
    }
  5. Configure iOS Background Mode for BLE

    master

    To enable background mode on iOS:

    1. In your application target in Xcode, go to the Capabilities tab.
    2. Enable Uses Bluetooth LE Accessories in the Background Modes section.
    3. When initializing the BleManager, pass the restoreStateIdentifier and restoreStateFunction to the constructor.
  6. Monitor device disconnection

    master

    Use the onDeviceDisconnected method on your BleManager instance to listen for disconnection events. This allows you to implement custom logic such as automatic reconnection or user notifications.

    Note: Connection monitoring only occurs while the application is in the foreground.

    const setupOnDeviceDisconnected = (deviceIdToMonitor: String) => {
      bleManagerInstance.onDeviceDisconnected(deviceIdToMonitor, disconnectedListener)
    }
    
    const disconnectedListener = (error: BleError | null, device: Device | null) => {
      if (error) {
        console.error(JSON.stringify(error, null, 4))
      }
      if (device) {
        console.info(JSON.stringify(device, null, 4))
    
        // reconnect to the device
        device.connect()
      }
    }
  7. Setup for iOS (Bare React Native)

    master
    1. Install the package: npm install --save react-native-ble-plx.
    2. Install pods: Navigate to the ios folder and run pod update.
    3. Configure Permissions: Add NSBluetoothAlwaysUsageDescription to your Info.plist (required for iOS 13+).
    4. Background Mode (Optional):
      • In your application target, go to the Capabilities tab and enable Uses Bluetooth LE Accessories under Background Modes.
      • Pass restoreStateIdentifier and restoreStateFunction to the BleManager constructor.
  8. Wait for the Bluetooth PoweredOn state

    master

    On iOS, the BLE stack is not immediately available upon launch. Use onStateChange() to listen for the PoweredOn state before attempting to scan or connect.

    React.useEffect(() => {
      const subscription = manager.onStateChange(state => {
        if (state === 'PoweredOn') {
          scanAndConnect()
          subscription.remove()
        }
      }, true)
      return () => subscription.remove()
    }, [manager])
  9. Prepare a connection for service interaction

    master

    After calling device.connect(), you must call device.discoverAllServicesAndCharacteristics() before you can interact with the device's services and characteristics. Even if you already know the UUIDs, they must be discovered to be visible to the GATT client.

    device
      .connect()
      .then(device => {
        return device.discoverAllServicesAndCharacteristics()
      })
      .then(device => {
        // A fully functional connection you can use, now you can read, write and monitor values
      })
      .catch(error => {
        // Handle errors
      })