### Start Application - iOS Source: https://github.com/dotintent/react-native-ble-plx/blob/master/example/README.md Commands to start the iOS application using npm or Yarn. ```bash # using npm npm run ios # OR using Yarn yarn ios ``` -------------------------------- ### Start Metro Server Source: https://github.com/dotintent/react-native-ble-plx/blob/master/example/README.md Commands to start the Metro bundler using npm or Yarn. ```bash # using npm npm start # OR using Yarn yarn start ``` -------------------------------- ### Ex.1: Creating a singleton BleManager instance Source: https://github.com/dotintent/react-native-ble-plx/blob/master/docs/GETTING_STARTED.md This example shows how to create a singleton class to manage the BleManager instance, ensuring it's created after the application starts. ```typescript import { BleManager } from 'react-native-ble-plx' // create your own singleton class class BLEServiceInstance { manager: BleManager constructor() { this.manager = new BleManager() } } export const BLEService = new BLEServiceInstance() ``` -------------------------------- ### Start Application - Android Source: https://github.com/dotintent/react-native-ble-plx/blob/master/example/README.md Commands to start the Android application using npm or Yarn. ```bash # using npm npm run android # OR using Yarn yarn android ``` -------------------------------- ### Ex.2: Creating a BleManager instance directly Source: https://github.com/dotintent/react-native-ble-plx/blob/master/docs/GETTING_STARTED.md This example demonstrates creating a BleManager instance directly, which can be used as a static reference. ```typescript import { BleManager } from 'react-native-ble-plx' export const manager = new BleManager() ``` -------------------------------- ### Install pre-release version Source: https://github.com/dotintent/react-native-ble-plx/blob/master/RELEASE.md Installs a pre-release version of the library for testing. ```bash "react-native-ble-plx": "dotintent/react-native-ble-plx" ``` -------------------------------- ### Install dependencies and clean repository Source: https://github.com/dotintent/react-native-ble-plx/blob/master/RELEASE.md Installs all project dependencies and cleans the repository. ```bash git clean -xfd && npm install ``` -------------------------------- ### Connect and Discover Services Source: https://github.com/dotintent/react-native-ble-plx/blob/master/docs/GETTING_STARTED.md This code snippet shows the process of connecting to a scanned Bluetooth device and then discovering all its services and characteristics. It uses a Promise-based approach for handling the asynchronous operations. ```javascript device .connect() .then(device => { return device.discoverAllServicesAndCharacteristics() }) .then(device => { // Do work on device with services and characteristics }) .catch(error => { // Handle errors }) ``` -------------------------------- ### BleManager Initialization Example Source: https://github.com/dotintent/react-native-ble-plx/blob/master/docs/index.html Demonstrates how to initialize a new BleManager instance and the necessity of calling the destroy() method to deallocate resources. ```javascript const manager = new BleManager(); // ... work with BLE manager ... manager.destroy(); ``` -------------------------------- ### onStateChange Example Source: https://github.com/dotintent/react-native-ble-plx/blob/master/docs/index.html Example demonstrating how to subscribe to BLE manager state changes and perform actions when the state is 'PoweredOn'. ```javascript const subscription = this.manager.onStateChange((state) => { if (state === 'PoweredOn') { this.scanAndConnect(); subscription.remove(); } }, true); ``` -------------------------------- ### Requesting Bluetooth Permissions Source: https://github.com/dotintent/react-native-ble-plx/blob/master/docs/GETTING_STARTED.md This JavaScript code snippet requests necessary Bluetooth permissions for Android, handling different API levels and permission requirements. ```javascript requestBluetoothPermission = async () => { if (Platform.OS === 'ios') { return true } if (Platform.OS === 'android' && PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION) { const apiLevel = parseInt(Platform.Version.toString(), 10) if (apiLevel < 31) { const granted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION) return granted === PermissionsAndroid.RESULTS.GRANTED } if (PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN && PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT) { const result = await PermissionsAndroid.requestMultiple([ PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN, PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT, PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION ]) return ( result['android.permission.BLUETOOTH_CONNECT'] === PermissionsAndroid.RESULTS.GRANTED && result['android.permission.BLUETOOTH_SCAN'] === PermissionsAndroid.RESULTS.GRANTED && result['android.permission.ACCESS_FINE_LOCATION'] === PermissionsAndroid.RESULTS.GRANTED ) } } this.showErrorToast('Permission have not been granted') return false } ``` -------------------------------- ### Scan and Connect Source: https://github.com/dotintent/react-native-ble-plx/blob/master/docs/GETTING_STARTED.md This code snippet demonstrates how to scan for Bluetooth devices and initiate a connection if a specific device is found. It includes error handling and stopping the scan once the target device is identified. ```javascript function scanAndConnect() { manager.startDeviceScan(null, null, (error, device) => { if (error) { // Handle error (scanning will be stopped automatically) return } // Check if it is a device you are looking for based on advertisement data // or other criteria. if (device.name === 'TI BLE Sensor Tag' || device.name === 'SensorTag') { // Stop scanning as it's not necessary if you are scanning for one device. manager.stopDeviceScan() // Proceed with connection. } }) } ``` -------------------------------- ### Install react-native-ble-plx Source: https://github.com/dotintent/react-native-ble-plx/blob/master/README.md Install the library using npm. ```bash npm install --save react-native-ble-plx ``` -------------------------------- ### Expo Configuration Example Source: https://github.com/dotintent/react-native-ble-plx/blob/master/README.md Example of how to configure react-native-ble-plx within the Expo config file. ```json { "expo": { "plugins": [ [ "react-native-ble-plx", { "isBackgroundEnabled": true, "modes": ["peripheral", "central"], "bluetoothAlwaysPermission": "Allow $(PRODUCT_NAME) to connect to bluetooth devices" } ] ] } } ``` -------------------------------- ### Waiting for Powered On state Source: https://github.com/dotintent/react-native-ble-plx/blob/master/docs/GETTING_STARTED.md This React.useEffect hook listens for state changes in the BLE stack and calls scanAndConnect when the state becomes 'PoweredOn'. It also handles subscription cleanup. ```javascript React.useEffect(() => { const subscription = manager.onStateChange(state => { if (state === 'PoweredOn') { scanAndConnect() subscription.remove() } }, true) return () => subscription.remove() }, [manager]) ``` -------------------------------- ### Cancel Transaction Example Source: https://github.com/dotintent/react-native-ble-plx/blob/master/docs/index.html Shows how to monitor a characteristic for device notifications and then cancel the transaction after a specified time. ```javascript const transactionId = 'monitor_battery'; // Monitor battery notifications manager.monitorCharacteristicForDevice( device.id, '180F', '2A19', (error, characteristic) => { // Handle battery level changes... }, transactionId); // Cancel after specified amount of time setTimeout(() => manager.cancelTransaction(transactionId), 2000); ``` -------------------------------- ### Requesting Bluetooth Permissions without ACCESS_FINE_LOCATION Source: https://github.com/dotintent/react-native-ble-plx/blob/master/docs/GETTING_STARTED.md This code snippet shows how to request Bluetooth scan and connect permissions without the ACCESS_FINE_LOCATION permission, useful when the 'neverForLocation' flag is active. ```javascript const result = await PermissionsAndroid.requestMultiple([ PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN, PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT ]) return ( result['android.permission.BLUETOOTH_CONNECT'] === PermissionsAndroid.RESULTS.GRANTED && result['android.permission.BLUETOOTH_SCAN'] === PermissionsAndroid.RESULTS.GRANTED ) ``` -------------------------------- ### BleManager Construction with State Restoration Source: https://github.com/dotintent/react-native-ble-plx/wiki/Background-mode-(iOS) Example of constructing the BleManager with state restoration enabled, including a function to handle the restored state. ```javascript const manager = new BleManager({ restoreStateIdentifier: 'BleInTheBackground', restoreStateFunction: restoredState => { if (restoredState == null) { // BleManager was constructed for the first time. } else { // BleManager was restored. Check `restoredState.connectedPeripherals` property. } }, }); ``` -------------------------------- ### Prepare the connection with your device Source: https://github.com/dotintent/react-native-ble-plx/blob/master/docs/TUTORIALS.md This snippet demonstrates how to connect to a device and discover all its services and characteristics, which is a prerequisite for further interaction. ```javascript 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 }) ``` -------------------------------- ### Connecting to a device that is already connected to the OS Source: https://github.com/dotintent/react-native-ble-plx/blob/master/docs/TUTORIALS.md This snippet shows how to retrieve a list of already connected devices using `getConnectedDevices` and then connect to a specific device if it's not already connected. ```javascript bleManagerInstance .getConnectedDevices([serviceUUIDs]) .then(devices => { const device = devices.find(d => d.id === deviceIdWeWantToConnectTo) if (device && !device.isConnected) { device.connect() } }) .catch(error => { console.error('Get connected devices error:', error) }) ``` -------------------------------- ### Reading from a characteristic Source: https://github.com/dotintent/react-native-ble-plx/blob/master/docs/TUTORIALS.md This snippet shows how to read a value from a specific characteristic using its service and characteristic UUIDs. ```javascript device .readCharacteristicForService(serviceUUID, characteristicUUID) .then(characteristic => { console.log('Read characteristic value:', characteristic.value) }) .catch(error => { console.error('Read characteristic error:', error) }) ``` -------------------------------- ### Writing to a characteristic Source: https://github.com/dotintent/react-native-ble-plx/blob/master/docs/TUTORIALS.md This snippet demonstrates how to write data to a characteristic, either with or without a response, using the provided service, characteristic UUIDs, and the value to write. ```javascript device .writeCharacteristicWithResponseForService(serviceUUID, characteristicUUID, value) .then(() => { console.log('Write characteristic success') }) .catch(error => { console.error('Write characteristic error:', error) }) ``` -------------------------------- ### Sample Usage Source: https://github.com/dotintent/react-native-ble-plx/wiki/Device-Service-Discovery Demonstrates a typical workflow of discovering services and characteristics and then retrieving them. ```javascript // assuming the 'device' is already connected await device.discoverAllServicesAndCharacteristics(); const services = await device.services(); // do your thing with the services ``` -------------------------------- ### Generate documentation Source: https://github.com/dotintent/react-native-ble-plx/blob/master/RELEASE.md Generates new documentation for the project, skipping CSS changes. ```bash npm run docs ``` -------------------------------- ### Monitoring device disconnection Source: https://github.com/dotintent/react-native-ble-plx/blob/master/docs/TUTORIALS.md This snippet shows how to set up a listener for device disconnections using the `onDeviceDisconnected` method and implement a reconnection logic. ```typescript 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() } } ``` -------------------------------- ### Run local tests Source: https://github.com/dotintent/react-native-ble-plx/blob/master/RELEASE.md Executes the local test suite for the project. ```bash npm test ``` -------------------------------- ### Start Device Scan Source: https://github.com/dotintent/react-native-ble-plx/wiki/Bluetooth-Scanning Initiates a BLE peripheral scan. The listener function is called for each scanned device or if an error occurs. ```javascript bleManager.startDeviceScan( UUIDs: ?Array, options: ?ScanOptions, listener: (error: ?Error, scannedDevice: ?Device) => void ) ``` -------------------------------- ### Collecting native logs on Android Source: https://github.com/dotintent/react-native-ble-plx/blob/master/docs/TUTORIALS.md This snippet shows how to enable verbose logging on the `BleManager` instance to aid in debugging. ```javascript bleManagerInstance.setLogLevel(LogLevel.Verbose) ``` -------------------------------- ### Get current Bluetooth Adapter State Source: https://github.com/dotintent/react-native-ble-plx/wiki/Bluetooth-Adapter-State This function returns a Promise which will resolve with the current, global State of a BleManager. All APIs are working only when the active state is PoweredOn. ```javascript bleManager.state(): Promise<$Keys> ``` -------------------------------- ### Publish new version Source: https://github.com/dotintent/react-native-ble-plx/blob/master/RELEASE.md Cleans the repository and publishes a new version of the library. ```bash git clean -xfd && npm publish ``` -------------------------------- ### Descriptor Constructor Source: https://github.com/dotintent/react-native-ble-plx/blob/master/docs/index.html Constructor for the Descriptor object. ```javascript new Descriptor(nativeDescriptor: NativeDescriptor, manager: [BleManager](#blemanager)) ``` -------------------------------- ### Lint and check for errors Source: https://github.com/dotintent/react-native-ble-plx/blob/master/RELEASE.md Checks for type and documentation errors in the project. ```bash npm run lint ``` -------------------------------- ### Audit and fix vulnerabilities Source: https://github.com/dotintent/react-native-ble-plx/blob/master/RELEASE.md Fixes any identified vulnerabilities in the project dependencies. ```bash npm audit fix ``` -------------------------------- ### Add Jitpack repository Source: https://github.com/dotintent/react-native-ble-plx/blob/master/README.md Add the Jitpack repository to known repositories in build.gradle. ```groovy allprojects { repositories { ... maven { url 'https://www.jitpack.io' } } } ``` -------------------------------- ### Simulating killed state using LLDB Source: https://github.com/dotintent/react-native-ble-plx/wiki/Background-mode-(iOS) Instructions on how to simulate the killed state of an iOS application using the LLDB debugger to test restoration functionality. ```bash p (int)raise(9); ``` -------------------------------- ### Connect to Device Source: https://github.com/dotintent/react-native-ble-plx/wiki/Device-Connecting Establishes a connection to a Bluetooth Low Energy device. ```javascript bleManager.connectToDevice( deviceIdentifier: DeviceId, options: ?ConnectionOptions, ): Promise ``` -------------------------------- ### Writing Height Value to a Characteristic (Shorter) Source: https://github.com/dotintent/react-native-ble-plx/wiki/=--FAQ:-Passing-And-Retrieving-Of-Characteristic-Value A more concise JavaScript implementation for writing height to a characteristic using Buffer.writeUInt16LE for direct 16-bit unsigned integer writing in Little Endian. ```javascript const heightBuffer = Buffer.alloc(2); heightBuffer.writeUInt16LE(heightInCentimeters, 0); device.writeCharacteristicWithResponseForService(userDataServiceUUID, heightCharacteristicUUID, heightBuffer.toString('base64')); // assuming the device is already connected ``` -------------------------------- ### Discover All Services and Characteristics (Device Object) Source: https://github.com/dotintent/react-native-ble-plx/wiki/Device-Service-Discovery Initiates the discovery of all services and characteristics associated with a specific device object. ```javascript device.discoverAllServicesAndCharacteristics(): Promise ``` -------------------------------- ### Discover All Services and Characteristics (BLE Manager) Source: https://github.com/dotintent/react-native-ble-plx/wiki/Device-Service-Discovery Initiates the discovery of all services and characteristics for a device using its identifier via the BLE manager. ```javascript bleManager.discoverAllServicesAndCharacteristicsForDevice( deviceIdentifier: DeviceId, ): Promise ``` -------------------------------- ### Reading Height Value from a Characteristic (Shorter) Source: https://github.com/dotintent/react-native-ble-plx/wiki/=--FAQ:-Passing-And-Retrieving-Of-Characteristic-Value A more concise JavaScript implementation for reading height from a characteristic using Buffer.readUInt16LE for direct decoding of a 16-bit unsigned integer in Little Endian from Base64. ```javascript const readCharacteristic = await device.readCharacteristicForService(userDataServiceUUID, heightCharacteristicUUID); // assuming the device is already connected const heightInCentimeters = Buffer.from(readCharacteristic.value, 'base64').readUInt16LE(0); ``` -------------------------------- ### BleError Constructor Source: https://github.com/dotintent/react-native-ble-plx/blob/master/docs/index.html Constructor for the BleError class, which extends the native Error class. ```javascript new BleError(nativeBleError: (NativeBleError | [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)), errorMessageMapping: [BleErrorCodeMessageMapping](#bleerrorcodemessagemapping)) ``` -------------------------------- ### Reading a Characteristic Source: https://github.com/dotintent/react-native-ble-plx/wiki/Characteristic-Reading Demonstrates the different ways to read a characteristic's value using the react-native-ble-plx library. ```javascript characteristic.read(transactionId: ?TransactionId): Promise ``` ```javascript device.readCharacteristicForService( serviceUUID: UUID, characteristicUUID: UUID, transactionId: ?TransactionId ): Promise ``` ```javascript bleManager.readCharacteristicForDevice( deviceIdentifier: DeviceId, serviceUUID: UUID, characteristicUUID: UUID, transactionId: ?TransactionId ): Promise ``` ```javascript service.readCharacteristic( characteristicUUID: UUID, transactionId: ?TransactionId ): Promise ``` -------------------------------- ### Simulating background task launch Source: https://github.com/dotintent/react-native-ble-plx/wiki/Background-mode-(iOS) Command to simulate the launch of a background processing task using the BGTaskScheduler in Xcode debugger. ```bash e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@"TASK_IDENTIFIER"] ``` -------------------------------- ### Write with Response Source: https://github.com/dotintent/react-native-ble-plx/wiki/Characteristic-Writing Methods for writing characteristics with a response from the peripheral. ```javascript characteristic.writeWithResponse( valueBase64: Base64, transactionId: ?TransactionId ): Promise ``` ```javascript device.writeCharacteristicWithResponseForService( serviceUUID: UUID, characteristicUUID: UUID, valueBase64: Base64, transactionId: ?TransactionId ): Promise ``` ```javascript bleManager.writeCharacteristicWithResponseForDevice( deviceIdentifier: DeviceId, serviceUUID: UUID, characteristicUUID: UUID, base64Value: Base64, transactionId: ?TransactionId ): Promise ```