### Register Example App Source: https://github.com/innoveit/react-native-ble-manager/blob/master/README.md To test the library, point your AppRegistry to the example component. Note that this import only works when cloning the repository, not from node_modules. ```javascript // in your index.ios.js or index.android.js import React, { Component } from "react"; import { AppRegistry } from "react-native"; import App from "react-native-ble-manager/example/App"; /* Note: The react-native-ble-manager/example directory is only included when cloning the repo, the above import will not work if trying to import react-native-ble-manager/example from node_modules */ AppRegistry.registerComponent("MyAwesomeApp", () => App); ``` -------------------------------- ### Run Example on iOS Source: https://github.com/innoveit/react-native-ble-manager/blob/master/example/README.md Execute the example application on an iOS simulator or device using Expo CLI. ```bash npx expo run:ios ``` -------------------------------- ### Run Example on Android Source: https://github.com/innoveit/react-native-ble-manager/blob/master/example/README.md Execute the example application on an Android emulator or device using Expo CLI. ```bash npx expo run:android ``` -------------------------------- ### Install Dependencies and Prebuild Source: https://github.com/innoveit/react-native-ble-manager/blob/master/example/README.md Install project dependencies and prebuild the native projects using npm and Expo CLI. ```bash npm i npx expo prebuild ``` -------------------------------- ### Check if BLE Manager is Started Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Checks if the BLE module has been successfully initialized using the `start` method. Returns a Promise that resolves to a boolean. ```javascript BleManager.isStarted().then((started) => { // Success code console.log(`Module is ${isStarted ? '' : 'not '}started`); }); ``` -------------------------------- ### start(options) Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Initializes the BLE manager module. This should be called before any other BLE operations. It returns a Promise and should not be called multiple times. ```APIDOC ## start(options) ### Description Initializes the BLE manager module. Returns a `Promise` object. It's recommended not to call this multiple times. ### Method `start(options)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - `options` (JSON) - Optional configuration object. - `showAlert` (Boolean) - [iOS only] Controls whether to show an alert if Bluetooth is turned off during initialization. - `restoreIdentifierKey` (String) - [iOS only] A unique key for CoreBluetooth state restoration. - `queueIdentifierKey` (String) - [iOS only] A unique key for dispatching CoreBluetooth events. - `forceLegacy` (Boolean) - [Android only] Forces the use of the LegacyScanManager. ### Request Example ```javascript BleManager.start({ showAlert: false }).then(() => { // Success code console.log("Module initialized"); }); ``` ### Response #### Success Response (Promise resolves) Indicates successful initialization. #### Response Example (Promise resolves without a specific value, success is indicated by the `.then()` block execution) ``` -------------------------------- ### Install via npm Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/install.markdown Use this command to add the library to your React Native project. ```shell npm i --save react-native-ble-manager ``` -------------------------------- ### isStarted() Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Checks if the BLE manager module has been initialized using the `start` method. Returns a Promise that resolves to a boolean. ```APIDOC ## isStarted() ### Description Checks if the module has been initialized with `start`. Returns a `Promise` object. ### Method `isStarted()` ### Parameters None ### Request Example ```javascript BleManager.isStarted().then((started) => { // Success code console.log(`Module is ${started ? '' : 'not '}started`); }); ``` ### Response #### Success Response (Promise resolves) - `started` (Boolean) - `true` if the module is started, `false` otherwise. #### Response Example ```json { "started": true } ``` ``` -------------------------------- ### Build Library for Development Source: https://github.com/innoveit/react-native-ble-manager/blob/master/README.md Install dependencies and build the TypeScript library. Use 'npm run watch' for on-the-fly TypeScript file changes. ```shell npm install npm run build ``` -------------------------------- ### Link Library Code Source: https://github.com/innoveit/react-native-ble-manager/blob/master/example/README.md Link the local library code into the example project for direct modification. Otherwise, the code is copied to node_modules. ```bash npm link react-native-ble-manager ``` -------------------------------- ### Start Notification with Buffer (Android Only) Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Starts receiving notifications from a characteristic with a buffer. Data is collected until the buffer limit is reached before emitting. Requires `retrieveServices` to be called first. ```javascript BleManager.startNotificationWithBuffer( "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", 1234 ) .then(() => { // Success code console.log("Notification started"); }) .catch((error) => { // Failure code console.log(error); }); ``` -------------------------------- ### Get Bonded Peripherals Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Retrieves a list of all currently bonded Bluetooth peripherals. This method is available on Android. ```javascript BleManager.getBondedPeripherals([]).then((bondedPeripheralsArray) => { // Each peripheral in returned array will have id and name properties console.log("Bonded peripherals: " + bondedPeripheralsArray.length); }); ``` -------------------------------- ### Get Discovered Peripherals Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Returns an array of peripherals that have been discovered during a scan. This method is useful for listing available devices. ```javascript BleManager.getDiscoveredPeripherals().then((peripheralsArray) => { // Success code console.log("Discovered peripherals: " + peripheralsArray.length); }); ``` -------------------------------- ### Start BLE Characteristic Notification Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Starts receiving notifications for a specific characteristic on a peripheral. `retrieveServices` must be called beforehand. Events are received via `onDidUpdateValueForCharacteristic`. Returns a Promise. ```javascript BleManager.startNotification( "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ) .then(() => { // Success code console.log("Notification started"); }) .catch((error) => { // Failure code console.log(error); }); ``` -------------------------------- ### startNotificationWithBuffer(peripheralId, serviceUUID, characteristicUUID, buffer) [Android only] Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Starts notifications for a characteristic on Android, buffering data until a specified byte limit is reached before emitting. Requires `retrieveServices` to be called first. Returns a promise. ```APIDOC ## startNotificationWithBuffer(peripheralId, serviceUUID, characteristicUUID, buffer) [Android only] ### Description Start the notification on the specified characteristic, you need to call `retrieveServices` method before. The buffer collect messages until the buffer of messages bytes reaches the limit defined with the `buffer` argument and then emit all the collected data. Useful to reduce the number of calls between the native and the react-native part in case of many messages. ### Method `BleManager.startNotificationWithBuffer(peripheralId, serviceUUID, characteristicUUID, buffer)` ### Parameters #### Arguments - `peripheralId` - `String` - the id/mac address of the peripheral. - `serviceUUID` - `String` - the UUID of the service. - `characteristicUUID` - `String` - the UUID of the characteristic. - `buffer` - `Integer` - the capacity of the buffer (bytes) stored before emitting the data for the characteristic. ### Returns A `Promise` object that resolves on success or rejects on failure. ``` -------------------------------- ### Generate iOS Codegen Source: https://github.com/innoveit/react-native-ble-manager/blob/master/README.md Generate iOS native code using Expo prebuild and then running 'pod install' in the ios folder to trigger the codegen during the build process. ```shell # in the example folder generate the ios project from expo: npx expo prebuild --platform ios # the codegen run during the first build, if you need to run it again use pod install in the ios folder ``` -------------------------------- ### Get Connected Peripherals Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Retrieves a list of currently connected Bluetooth peripherals. On Android, this list might be limited if peripherals were not discovered via a scan first. ```javascript BleManager.getConnectedPeripherals([]).then((peripheralsArray) => { // Success code console.log("Connected peripherals: " + peripheralsArray.length); }); ``` -------------------------------- ### Read RSSI of a Peripheral Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Use this method to get the current RSSI value of a connected peripheral. Ensure the peripheral is already connected. ```javascript BleManager.readRSSI("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX") .then((rssi) => { // Success code console.log("Current RSSI: " + rssi); }) .catch((error) => { // Failure code console.log(error); }); ``` -------------------------------- ### Get Maximum Write Value Length With Response (iOS) Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Returns the maximum data length allowed for a 'Write With Response' operation on iOS. Requires a peripheral ID. ```javascript BleManager.getMaximumWriteValueLengthForWithResponse( "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ).then((maxValue) => { console.log("Maximum length for WriteWithResponse: " + maxValue); }); ``` -------------------------------- ### onDidUpdateNotificationStateFor Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/events.markdown [iOS only] The peripheral received a request to start or stop providing notifications for a specified characteristic's value. This event handler provides details about the peripheral, characteristic, and notification status, along with error information. ```APIDOC ## onDidUpdateNotificationStateFor [iOS only] ### Description The peripheral received a request to start or stop providing notifications for a specified characteristic's value. ### Arguments - `peripheral` (String) - the id of the peripheral - `characteristic` (String) - the UUID of the characteristic - `isNotifying` (Boolean) - Is the characteristic notifying or not - `domain` (String) - [iOS only] error domain - `code` (Number) - [iOS only] error code ``` -------------------------------- ### Get Maximum Write Value Length (iOS) Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Returns the maximum data length allowed for a 'Write Without Response' operation on iOS. Requires a peripheral ID. ```javascript BleManager.getMaximumWriteValueLengthForWithoutResponse( "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ).then((maxValue) => { console.log("Maximum length for WriteWithoutResponse: " + maxValue); }); ``` -------------------------------- ### Prepare Data Buffer for BLE Write Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Demonstrates how to create a Buffer from various sources like arrays, numbers, or strings for BLE data transmission. This is crucial for converting data into the required `number[]` format. ```javascript // https://github.com/feross/buffer import { Buffer } from 'buffer'; // Creates a Buffer containing the bytes [0x01, 0x02, 0x03]. const buffer = Buffer.from([1, 2, 3]); // Creates a Buffer containing the bytes [0x01, 0x01, 0x01, 0x01] – the entries // are all truncated using `(value & 255)` to fit into the range 0–255. const buffer = Buffer.from([257, 257.5, -255, '1']); // Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést': // [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation) // [116, 195, 169, 115, 116] (in decimal notation) const buffer = Buffer.from('tést'); ``` -------------------------------- ### Implement Theme Persistence and Switching Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/_includes/nav_footer_custom.html Loads the saved theme from localStorage on initialization and sets up an event listener to update the theme and localStorage when the theme switch is toggled. ```javascript const savedTheme = localStorage.getItem('theme'); if (savedTheme) { jtd.setTheme(savedTheme); document.getElementById('theme-switch').checked = savedTheme === 'light'; } document.getElementById('theme-switch').addEventListener('change', function (event) { const newTheme = event.target.checked ? "light" : "dark"; jtd.setTheme(newTheme); localStorage.setItem('theme', newTheme); }); ``` -------------------------------- ### Initialize BLE Manager Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Initializes the BLE module. Call this before using other BLE functionalities. It returns a Promise and should not be called multiple times. ```javascript BleManager.start({ showAlert: false }).then(() => { // Success code console.log("Module initialized"); }); ``` -------------------------------- ### connect(peripheralId, options) Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Attempts to establish a connection with a specified Bluetooth peripheral. It's often necessary to scan for the peripheral before attempting to connect. This method returns a Promise. ```APIDOC ## connect(peripheralId, options) ### Description Attempts to connect to a peripheral. In many cases, if you cannot connect, you must scan for the peripheral first. ### Method `connect(peripheralId, options)` ### Parameters #### Path Parameters - `peripheralId` (String) - The ID or MAC address of the peripheral to connect to. - `options` (JSON) - Optional. The configuration keys are: - `phy` (Number) - [Android only] Corresponds to the preferred PHY channel. - `autoconnect` (Boolean) - [Android only] Whether to directly connect to the remote device (false) or to automatically connect as soon as the remote device becomes available (true). ### Returns A `Promise` object. ### Request Example ```javascript BleManager.connect("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX") .then(() => { // Success code console.log("Connected"); }) .catch((error) => { // Failure code console.log(error); }); ``` ``` -------------------------------- ### scan(scanningOptions) Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Initiates a scan for available Bluetooth peripherals. This method returns a Promise and can be configured with various options to control scan behavior. Use `onDiscoverPeripheral` for live updates and `getDiscoveredPeripherals` to retrieve a list after scanning. ```APIDOC ## scan(scanningOptions) ### Description Scans for available peripherals. Use `onDiscoverPeripheral` to get live updates of discovered devices and `getDiscoveredPeripherals` to get a list of discovered devices after a scan is completed. Returns a `Promise` object. ### Method `scan(scanningOptions)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - `scanningOptions` (JSON) - Options to control specific BLE scan behaviors: - `serviceUUIDs` (String[]) - The UUIDs of the services to look for. - `seconds` (Integer) - The amount of seconds to scan. If not set or set to `0`, scans until `stopScan()` is called. - `exactAdvertisingName` (String[]) - [Android only] Corresponds to `ScanFilter.setDeviceName()`. [iOS only] Filter is done manually before sending the peripheral. - `allowDuplicates` (Boolean) - [iOS only] Allows duplicates in device scanning. - `numberOfMatches` (Number) - [Android only] Corresponds to `ScanSettings.Builder.setNumOfMatches()`. Defaults to `ScanSettings.MATCH_NUM_MAX_ADVERTISEMENT`. Note: anything other than the default may only work when a `ScanFilter` is active. - `matchMode` (Number) - [Android only] Corresponds to `ScanSettings.Builder.setMatchMode()`. Defaults to `ScanSettings.MATCH_MODE_AGGRESSIVE`. - `callbackType` (Number) - [Android only] Corresponds to `ScanSettings.Builder.setCallbackType()`. Defaults to `ScanSettings.CALLBACK_TYPE_ALL_MATCHES`. Note: anything other than the default may only work when a `ScanFilter` is active. - `scanMode` (Number) - [Android only] Corresponds to `ScanSettings.Builder.setScanMode()`. Defaults to `ScanSettings.SCAN_MODE_LOW_POWER`. - `reportDelay` (Number) - [Android only] Corresponds to `ScanSettings.Builder.setReportDelay()`. Defaults to `0ms`. - `phy` (Number) - [Android only] Corresponds to `ScanSettings.Builder.setPhy()`. - `legacy` (Boolean) - [Android only] Corresponds to `ScanSettings.Builder.setLegacy()`. - `manufacturerData` (Object) - [Android only] Corresponds to `ScanFilter.Builder.setManufacturerData()`. Filters by manufacturer ID or data. - `manufacturerId` (Number) - Manufacturer/company ID to filter for. - `manufacturerData` (Number[]) - Additional manufacturer data filter. - `manufacturerDataMask` (Number[]) - Mask for manufacturer data, must have the same length as `manufacturerData`. Set bits to 1 to match the corresponding bit in `manufacturerData`, otherwise set to 0. - `useScanIntent` (Boolean) - [Android only, API 26+] Delivers scan results through a `PendingIntent` instead of the default callback. Any ongoing callback scan is automatically stopped before switching to this mode. ### Request Example ```javascript BleManager.scan({ serviceUUIDs: [], seconds: 5 }).then(() => { // Success code console.log("Scan started"); }); ``` ### Response #### Success Response (Promise resolves) Indicates that the scan has been initiated successfully. #### Response Example (Promise resolves without a specific value, success is indicated by the `.then()` block execution) ``` -------------------------------- ### Check for Companion Device Manager Support (Android Only) Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Verifies if the current Android device supports the companion device manager. Returns a promise that resolves to a boolean. ```javascript BleManager.supportsCompanion().then((isSupported) => { if (isSupported) { console.log("Companion device manager is supported!"); } else { console.log("Companion device manager is NOT supported!"); } }); ``` -------------------------------- ### supportsCompanion() [Android only] Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Checks if the current Android device supports the companion device manager. Returns a promise that resolves to a boolean. ```APIDOC ## supportsCompanion() [Android only] ### Description Check if current device supports the companion device manager. ### Method `BleManager.supportsCompanion()` ### Returns A `Promise` object that resolves with a boolean indicating if companion device manager is supported. ``` -------------------------------- ### onCompanionPeripheral Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/events.markdown [Android only] User picked a device to associate with. This event handler is null if the request was cancelled by the user and provides details about the selected peripheral. ```APIDOC ## onCompanionPeripheral [Android only] ### Description User picked a device to associate with. Null if the request was cancelled by the user. ### Arguments - `id` (String) - the id of the peripheral - `name` (String) - the name of the peripheral - `rssi` (Number) - the RSSI value ``` -------------------------------- ### enableBluetooth() [Android only] Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Requests the user to enable Bluetooth on Android devices. Returns a promise that indicates success or failure. ```APIDOC ## enableBluetooth() [Android only] ### Description Create the ACTION_REQUEST_ENABLE to ask the user to activate the bluetooth. ### Method `BleManager.enableBluetooth()` ### Returns A `Promise` object that resolves on success or rejects on failure. ``` -------------------------------- ### Scan for Peripherals Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Initiates a scan for available Bluetooth peripherals. This method returns a Promise and can be configured with various options to control the scanning behavior. ```javascript BleManager.scan({ serviceUUIDs: [], seconds: 5 }).then(() => { // Success code console.log("Scan started"); }); ``` -------------------------------- ### onPeripheralDidBond Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/events.markdown A bond with a peripheral was established. This event handler provides object with information about the bonded device. ```APIDOC ## onPeripheralDidBond ### Description A bond with a peripheral was established. ### Arguments Object with information about the device. ``` -------------------------------- ### Enable Bluetooth (Android Only) Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Prompts the user to enable Bluetooth on Android devices. The promise resolves if Bluetooth is already enabled or the user confirms, and rejects if the user refuses. ```javascript BleManager.enableBluetooth() .then(() => { // Success code console.log("The bluetooth is already enabled or the user confirm"); }) .catch((error) => { // Failure code console.log("The user refuse to enable bluetooth"); }); ``` -------------------------------- ### companionScan() [Android only, API 26+] Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Initiates a scan for companion devices on Android. This method is specific to Android and requires API level 26 or higher. It returns a promise that resolves with the selected peripheral or null if cancelled. ```APIDOC ## companionScan() [Android only, API 26+] ### Description Scan for companion devices. Rejects if the companion device manager is not supported on this device. The promise it will eventually resolve with either a peripheral if user selects one, or null if user "cancels" (i.e. doesn't select anything). ### Method `BleManager.companionScan(serviceUUIDs, options)` ### Parameters #### Arguments - `serviceUUIDs` - `String[]` - List of service UUIDs to use as a filter - `options` - `JSON` - Additional options - `single` - `String?` - Scan only for single peripheral. See Android's `AssociationRequest.Builder.setSingleDevice`. ### Returns A `Promise` object that resolves with the selected peripheral or null if cancelled. ``` -------------------------------- ### Scan for Companion Devices (Android Only) Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Initiates a scan for companion devices on Android API 26+. This method requires the companion device manager to be supported. It resolves with the selected peripheral or null if cancelled. ```javascript BleManager.companionScan([]).then(peripheral => { console.log('Associated peripheral', peripheral); }); ``` -------------------------------- ### createBond(peripheralId, peripheralPin) Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Initiates the bonding (pairing) process with a remote Bluetooth device. An optional `peripheralPin` can be provided for automatic bonding. This method is available only on Android. It's recommended to make only one bond request at a time. ```APIDOC ## createBond(peripheralId, peripheralPin) ### Description Start the bonding (pairing) process with the remote device. If you pass peripheralPin (optional), bonding will be auto (without manually entering the pin). Returns a `Promise` object that will resolve if the bond is successfully created, otherwise it will be rejected with the appropriate error message. > In Android, Ensure to make one bond request at a time. ### Platform Android only ### Method `BleManager.createBond(peripheralId, peripheralPin)` ### Parameters #### Path Parameters - **peripheralId** (String) - Required - The id/mac address of the peripheral. - **peripheralPin** (String) - Optional - Will be used to auto-bond if possible. ### Request Example ```js BleManager.createBond(peripheralId) .then(() => { console.log("createBond success or there is already an existing one"); }) .catch(() => { console.log("fail to bond"); }); ``` ``` -------------------------------- ### retrieveServices Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Retrieves the services and characteristics of a specified peripheral. This method is a prerequisite for operations like reading or writing descriptors. It returns a Promise. ```APIDOC ## retrieveServices(peripheralId[, serviceUUIDs]) ### Description Retrieve the peripheral's services and characteristics. ### Method `retrieveServices` ### Parameters #### Path Parameters - **peripheralId** (String) - The id/mac address of the peripheral. - **serviceUUIDs** (String[]) - [iOS only] Optional, only retrieve these services. ### Request Example ```javascript BleManager.retrieveServices("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX").then( (peripheralInfo) => { // Success code console.log("Peripheral info:", peripheralInfo); } ); ``` ``` -------------------------------- ### onDiscoverPeripheral Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/events.markdown The scanning found a new peripheral. This event handler provides details about the discovered peripheral. ```APIDOC ## onDiscoverPeripheral ### Description The scanning found a new peripheral. ### Arguments - `id` (String) - the id of the peripheral - `name` (String) - the name of the peripheral - `rssi` (Number) - the RSSI value - `advertising` (JSON) - the advertising payload, here are some examples: - `isConnectable` (Boolean) - `serviceUUIDs` (String[]) - `manufacturerData` (JSON) - contains a json with the company id as field and the custom value as raw `bytes` and `data` (Base64 encoded string) - `serviceData` (JSON) - contains the raw `bytes` and `data` (Base64 encoded string) - `txPowerLevel` (Int) - `rawData` ([Android only] JSON) - contains the raw `bytes` and `data` (Base64 encoded string) of all the advertising data ``` -------------------------------- ### Retrieve Peripheral Services Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Fetches the services and characteristics of a peripheral. This is a prerequisite for many other operations like reading or writing descriptors. ```javascript BleManager.retrieveServices("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX").then( (peripheralInfo) => { // Success code console.log("Peripheral info:", peripheralInfo); } ); ``` -------------------------------- ### startNotification(peripheralId, serviceUUID, characteristicUUID) Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Initiates notifications for a specified characteristic. Ensure `retrieveServices` has been called prior to using this method. Events will be sent to `onDidUpdateValueForCharacteristic` when the peripheral notifies a new value. This method returns a Promise. ```APIDOC ## startNotification(peripheralId, serviceUUID, characteristicUUID) ### Description Start the notification on the specified characteristic. You need to call the `retrieveServices` method before. Events will be sent to `onDidUpdateValueForCharacteristic` when the peripheral notifies a new value for the characteristic. ### Method `startNotification(peripheralId, serviceUUID, characteristicUUID)` ### Parameters #### Path Parameters - `peripheralId` (String) - The ID or MAC address of the peripheral. - `serviceUUID` (String) - The UUID of the service. - `characteristicUUID` (String) - The UUID of the characteristic. ### Returns A `Promise` object. ### Request Example ```javascript BleManager.startNotification( "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" ) .then(() => { // Success code console.log("Notification started"); }) .catch((error) => { // Failure code console.log(error); }); ``` ``` -------------------------------- ### checkState() Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Forces the module to check the current state of the native BLE manager and trigger a `BleManagerDidUpdateState` event. This method resolves to a promise containing the current BLE state. ```APIDOC ## checkState() ### Description Force the module to check the state of the native BLE manager and trigger a BleManagerDidUpdateState event. ### Method `checkState()` ### Returns Resolves to a promise containing the current BleState. ### Request Example ```javascript BleManager.checkState().then((state) => console.log(`current BLE state = '${state}'.`) ); ``` ``` -------------------------------- ### Request MTU Size (Android Only API 21+) Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Requests a specific MTU size for a given peripheral connection. Returns a promise that resolves with the new MTU size. ```javascript BleManager.requestMTU("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", 512) .then((mtu) => { // Success code console.log("MTU size changed to " + mtu + " bytes"); }) .catch((error) => { // Failure code console.log(error); }); ``` -------------------------------- ### onStopScan Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/events.markdown The scanning for peripherals is ended. This event handler receives arguments detailing the reason for the scan stopping. ```APIDOC ## onStopScan ### Description The scanning for peripherals is ended. ### Arguments - `status` (Number) - [iOS] the reason for stopping the scan. Error code 10 is used for timeouts, 0 covers everything else. [Android] the reason for stopping the scan (). Error code 10 is used for timeouts ``` -------------------------------- ### write(peripheralId, serviceUUID, characteristicUUID, data, maxByteSize) Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Writes data to a specified characteristic with a response. Requires 'retrieveServices' to be called beforehand. Data should be provided as a number array. Optionally specify maxByteSize. ```APIDOC ## write(peripheralId, serviceUUID, characteristicUUID, data, maxByteSize) ### Description Writes data with response to the specified characteristic. You must call `retrieveServices` before using this method. ### Parameters #### Path Parameters - **peripheralId** (String) - The ID or MAC address of the peripheral. - **serviceUUID** (String) - The UUID of the service. - **characteristicUUID** (String) - The UUID of the characteristic. - **data** (number[]) - The data to write as a plain integer array representing a ByteArray structure. - **maxByteSize** (Integer) - Optional. Specifies the maximum byte size before splitting the message. Defaults to 20 bytes. ### Request Example ```js BleManager.write( "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", buffer.toJSON().data ) .then(() => { console.log("Write: " + data); }) .catch((error) => { console.log(error); }); ``` ``` -------------------------------- ### requestMTU(peripheralId, mtu) [Android only API 21+] Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Requests a specific MTU size for a given connection on Android (API 21+). Returns a promise that resolves with the new MTU size. ```APIDOC ## requestMTU(peripheralId, mtu) [Android only API 21+] ### Description Request an MTU size used for a given connection. ### Method `BleManager.requestMTU(peripheralId, mtu)` ### Parameters #### Arguments - `peripheralId` - `String` - the id/mac address of the peripheral. - `mtu` - `Integer` - the MTU size to be requested in bytes. ### Returns A `Promise` object that resolves with the new MTU size. ``` -------------------------------- ### isScanning() Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Checks if the Bluetooth scan is currently in progress. Returns a promise that resolves to a boolean. ```APIDOC ## isScanning() ### Description Checks whether the scan is in progress and return `true` or `false`. ### Method `BleManager.isScanning()` ### Returns A `Promise` object that resolves with a boolean indicating if scanning is in progress. ``` -------------------------------- ### setName(name) Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Requests to set the name of the Bluetooth adapter. This method is available only on Android and returns a Promise. ```APIDOC ## setName(name) ### Description Create the request to set the name of the bluetooth adapter. (https://developer.android.com/reference/android/bluetooth/BluetoothAdapter#setName(java.lang.String)) Returns a `Promise` object. ### Platform Android only ### Method `BleManager.setName(name)` ### Parameters #### Path Parameters - **name** (String) - Required - The desired name for the Bluetooth adapter. ### Request Example ```js BleManager.setName("INNOVEIT_CENTRAL") .then(() => { // Success code console.log("Name set successfully"); }) .catch((error) => { // Failure code console.log("Name could not be set"); }); ``` ``` -------------------------------- ### Android Manifest Permissions Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/install.markdown Configure Bluetooth permissions in your AndroidManifest.xml file. Ensure you include necessary permissions based on Android version and app functionality, such as scanning, connecting, or advertising. ```xml // file: android/app/src/main/AndroidManifest.xml ... ``` -------------------------------- ### Configure app.json for BLE Manager Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/expo.markdown Add the react-native-ble-manager plugin to your `app.json` file to configure options for Android and iOS. This is required for versions 12.1.x and later. ```json { "...": "...", "plugins" : [ ..., ["react-native-ble-manager", { options }] ], } ``` -------------------------------- ### Check if Peripheral is Connected Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Verifies if a specific peripheral is currently connected. Returns a promise that resolves to a boolean value. ```javascript BleManager.isPeripheralConnected( "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", [] ).then((isConnected) => { if (isConnected) { console.log("Peripheral is connected!"); } else { console.log("Peripheral is NOT connected!"); } }); ``` -------------------------------- ### Request Runtime Bluetooth Permissions (Android) Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/install.markdown This JavaScript function requests necessary Bluetooth permissions at runtime on Android devices. It dynamically selects permissions based on the Android version, including FINE_LOCATION, BLUETOOTH_SCAN, and BLUETOOTH_CONNECT. ```javascript /** * Request runtime permission. * @returns {boolean} */ async function requestBluetoothPermissions() { if (Platform.OS === 'android') { const permissions = []; if (Platform.Version >= 23 && Platform.Version <= 30) { permissions.push(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION); } else if (Platform.Version >= 31) { permissions.push( PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN, PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT, ); } if (permissions.length === 0) { return true; } const granted = await PermissionsAndroid.requestMultiple(permissions); return Object.values(granted).every( result => result === PermissionsAndroid.RESULTS.GRANTED, ); } return true; } ``` -------------------------------- ### onCentralManagerWillRestoreState Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/events.markdown [iOS only] This event is fired when `centralManager:WillRestoreState:` is called, indicating the app was relaunched in the background to handle a Bluetooth event. It provides an array of previously connected peripherals. ```APIDOC ## onCentralManagerWillRestoreState [iOS only] ### Description This is fired when [`centralManager:WillRestoreState:`](https://developer.apple.com/documentation/corebluetooth/cbcentralmanagerdelegate/1518819-centralmanager) is called (app relaunched in the background to handle a bluetooth event). _For more on performing long-term bluetooth actions in the background:_ [iOS Bluetooth State Preservation and Restoration](https://developer.apple.com/library/archive/documentation/NetworkingInternetWeb/Conceptual/CoreBluetooth_concepts/CoreBluetoothBackgroundProcessingForIOSApps/PerformingTasksWhileYourAppIsInTheBackground.html#//apple_ref/doc/uid/TP40013257-CH7-SW10) [iOS Relaunch Conditions](https://developer.apple.com/documentation/technotes/tn3115-bluetooth-state-restoration-app-relaunch-rules/) ### Arguments - `peripherals` (Array) - an array of previously connected peripherals. ``` -------------------------------- ### Connect to BLE Peripheral Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Attempts to connect to a specified BLE peripheral using its ID. Scanning may be required before connecting. Note that on iOS, connections do not time out by default. Returns a Promise. ```javascript BleManager.connect("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX") .then(() => { // Success code console.log("Connected"); }) .catch((error) => { // Failure code console.log(error); }); ``` -------------------------------- ### getBondedPeripherals() Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Retrieves a list of all bonded Bluetooth peripherals. This method is available only on Android and returns a Promise. ```APIDOC ## getBondedPeripherals() ### Description Return the bonded peripherals. Returns a `Promise` object. ### Platform Android only ### Method `BleManager.getBondedPeripherals()` ### Request Example ```js BleManager.getBondedPeripherals([]).then((bondedPeripheralsArray) => { // Each peripheral in returned array will have id and name properties console.log("Bonded peripherals: " + bondedPeripheralsArray.length); }); ``` ``` -------------------------------- ### onDidUpdateState Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/events.markdown The BLE state changed. This event handler receives the new BLE state as an argument. ```APIDOC ## onDidUpdateState ### Description The BLE state changed. ### Arguments - `state` (String) - the new BLE state. Can be one of `unknown` (iOS only), `resetting` (iOS only), `unsupported`, `unauthorized` (iOS only), `on`, `off`, `turning_on` (android only), `turning_off` (android only). ``` -------------------------------- ### Request Connection Priority (Android Only API 21+) Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Requests an update to the connection parameters for a given peripheral. Accepts priority levels: 0 (balanced), 1 (high), 2 (low power). ```javascript BleManager.requestConnectionPriority("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", 1) .then((status) => { // Success code console.log("Requested connection priority"); }) .catch((error) => { // Failure code console.log(error); }); ``` -------------------------------- ### onConnectPeripheral Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/events.markdown A peripheral was connected. This event handler provides the peripheral ID and connection status, with additional status reasons for Android. ```APIDOC ## onConnectPeripheral ### Description A peripheral was connected. ### Arguments - `peripheral` (String) - the id of the peripheral - `status` (Number) - [Android only] connect [`reasons`]() ``` -------------------------------- ### getAssociatedPeripherals() Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Retrieves a list of associated peripherals from the companion manager. This method is available only on Android and requires API level 26 or higher. ```APIDOC ## getAssociatedPeripherals() ### Description Retrieve associated peripherals (from companion manager). ### Platform Android only, API 26+ ### Method `BleManager.getAssociatedPeripherals()` ``` -------------------------------- ### Create Bond with Peripheral Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Initiates the bonding (pairing) process with a remote BLE device. An optional peripheralPin can be provided for automatic bonding. Ensure only one bond request is made at a time on Android. ```javascript BleManager.createBond(peripheralId) .then(() => { console.log("createBond success or there is already an existing one"); }) .catch(() => { console.log("fail to bond"); }); ``` -------------------------------- ### getConnectedPeripherals Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Returns a list of currently connected Bluetooth peripherals. Optionally, you can filter by service UUIDs on iOS. This method returns a Promise. ```APIDOC ## getConnectedPeripherals(serviceUUIDs) ### Description Return the connected peripherals. ### Method `getConnectedPeripherals` ### Parameters #### Path Parameters - **serviceUUIDs** (String[]) - [iOS only] Optional, only retrieve peripherals with these services. Ignored in Android. ### Request Example ```javascript BleManager.getConnectedPeripherals([]).then((peripheralsArray) => { // Success code console.log("Connected peripherals: " + peripheralsArray.length); }); ``` ### Response #### Success Response - **peripheralsArray** (Array) - An array of connected peripheral objects. ``` -------------------------------- ### Write Data with Response using BLE Manager Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Writes data to a BLE characteristic with a response. Ensure `retrieveServices` has been called first. The `data` argument must be a `number[]` array, typically obtained from a Buffer's `toJSON().data`. ```javascript BleManager.write( "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", // encode & extract raw `number[]`. // Each number should be in the 0-255 range as it is converted from a valid byte. buffer.toJSON().data ) .then(() => { // Success code console.log("Write: " + data); }) .catch((error) => { // Failure code console.log(error); }); ``` -------------------------------- ### writeDescriptor Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Writes a value to a specified descriptor for a given peripheral, service, and characteristic. This operation requires `retrieveServices` to be called beforehand. It returns a Promise. ```APIDOC ## writeDescriptor(peripheralId, serviceUUID, characteristicUUID, descriptorUUID, data) ### Description Write a value to the specified descriptor, you need to call `retrieveServices` method before. ### Method `writeDescriptor` ### Parameters #### Path Parameters - **peripheralId** (String) - The id/mac address of the peripheral. - **serviceUUID** (String) - The UUID of the service. - **characteristicUUID** (String) - The UUID of the characteristic. - **descriptorUUID** (String) - The UUID of the descriptor. - **data** (number[]) - The data to write as a plain integer array representing a `ByteArray` structure. ### Request Example ```javascript BleManager.writeDescriptor( "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", "XXXX", [1, 2] ) .then(() => { // Success code }) .catch((error) => { // Failure code console.log(error); }); ``` ``` -------------------------------- ### getDiscoveredPeripherals Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Returns a list of peripherals that have been discovered during the last scan. This method returns a Promise. ```APIDOC ## getDiscoveredPeripherals() ### Description Return the discovered peripherals after a scan. ### Method `getDiscoveredPeripherals` ### Request Example ```javascript BleManager.getDiscoveredPeripherals().then((peripheralsArray) => { // Success code console.log("Discovered peripherals: " + peripheralsArray.length); }); ``` ### Response #### Success Response - **peripheralsArray** (Array) - An array of discovered peripheral objects. ``` -------------------------------- ### iOS Info.plist Configuration Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/install.markdown Update your iOS Info.plist file by adding NSBluetoothAlwaysUsageDescription and optionally NSBluetoothPeripheralUsageDescription for older iOS versions. For background communication, add 'central-peripheral' to UIBackgroundModes. ```plaintext In iOS >= 13 you need to add the `NSBluetoothAlwaysUsageDescription` string key. If the deployment target is earlier than iOS 13, you also need to add the `NSBluetoothPeripheralUsageDescription` string key. For background use you need to add `central-peripheral` in `UIBackgroundModes` key. Refer to the [documentation](https://developer.apple.com/documentation/xcode/configuring-background-execution-modes/). ``` -------------------------------- ### requestConnectionPriority(peripheralId, connectionPriority) [Android only API 21+] Source: https://github.com/innoveit/react-native-ble-manager/blob/master/docs/methods.markdown Requests a connection parameter update for a peripheral on Android (API 21+). Returns a promise with the status of the request. ```APIDOC ## requestConnectionPriority(peripheralId, connectionPriority) [Android only API 21+] ### Description Request a connection parameter update. ### Method `BleManager.requestConnectionPriority(peripheralId, connectionPriority)` ### Parameters #### Arguments - `peripheralId` - `String` - the id/mac address of the peripheral. - `connectionPriority` - `Integer` - the connection priority to be requested, as follows: - 0 - balanced priority connection - 1 - high priority connection - 2 - low power priority connection ### Returns A `Promise` object which fulfills with the status of the request. ``` -------------------------------- ### Generate Android Codegen Artifacts Source: https://github.com/innoveit/react-native-ble-manager/blob/master/README.md Generate Android native code from specs using the codegen process. Includes steps for Expo prebuild and Gradle execution. Cache issues can be resolved by clearing the Gradle cache. ```shell # in the example folder generate the android project from expo: npx expo prebuild --platform android # in the example/android folder run: ./gradlew generateCodegenArtifactsFromSchema (you can add --info to have debug messages) # if you have problems with the gradle cache cd android && ./gradlew --stop && rm -rf ~/.gradle/caches ```