### Package and Install React-Native Ble-Nitro Library Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/example/README.md This snippet details the process of packaging the React-Native Ble-Nitro library and installing it locally within the example project. It involves navigating to the project root, creating a tarball of the library, and then installing that tarball into the example app's node_modules. Ensure you have npm installed. ```bash cd ../ && npm pack cd ./example && npm install ../react-native-ble-nitro/react-native-ble-nitro-*.tgz npm install; ``` -------------------------------- ### Run React-Native Ble-Nitro Example on Device Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/example/README.md These commands demonstrate how to run the React-Native Ble-Nitro example application on a physical iOS or Android device. For iOS, you specify the device name; for Android, a general command is provided. This requires the example app to be properly installed and configured. ```bash npm run ios -- --device "Your Device Name" npm run android ``` -------------------------------- ### Development Workflow: Test with Example App in react-native-ble-nitro Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/CONTRIBUTING.md Commands to navigate to the example app directory, install its dependencies, and run it on iOS or Android. ```bash cd example npm install npx expo run:ios # or run:android ``` -------------------------------- ### Development Setup Steps (Git) Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/README.md These steps outline the process for setting up a development environment for the react-native-ble-nitro project using Git. It includes forking the repository, cloning, adding remotes, installing dependencies, generating code, and preparing for pull requests. ```bash 1. **Fork the repository** on GitHub 2. **Clone your fork**: `git clone https://github.com/YOUR_USERNAME/react-native-ble-nitro.git` 3. **Add upstream remote**: `git remote add upstream https://github.com/zykeco/react-native-ble-nitro.git` 4. **Install dependencies**: `npm install` 5. **Generate Nitro code**: `npx nitro-codegen` 6. **Make your changes** and run tests: `npm test` 7. **Submit a pull request** ``` -------------------------------- ### Test Project Setup and Local Install Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/RELEASE.md Instructions for setting up a new Expo test project and installing the local `react-native-ble-nitro` package. This allows developers to test the package's integration and functionality in a controlled environment before publishing. ```bash # Create test project npx create-expo-app --template blank-typescript TestBleNitro cd TestBleNitro # Install local package npm install ../react-native-ble-nitro # Add plugin to app.json { "expo": { "plugins": ["react-native-ble-nitro"] } } # Test basic functionality # Add BLE usage code to App.tsx ``` -------------------------------- ### Development Setup for react-native-ble-nitro Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/CONTRIBUTING.md Provides bash commands for setting up the development environment, including forking the repository, installing dependencies, and generating code. ```bash # Fork the repository on GitHub first, then: git clone https://github.com/YOUR_USERNAME/react-native-ble-nitro.git cd react-native-ble-nitro git remote add upstream https://github.com/zykeco/react-native-ble-nitro.git npm install ``` -------------------------------- ### Android Permissions Setup Source: https://context7.com/zykeco/react-native-ble-nitro/llms.txt Guides on how to request the necessary Android permissions before utilizing BLE functionality, which is crucial for Android 6.0+ and varies by API level. ```APIDOC ## Android Permissions Setup ### Description Request required Android permissions before using BLE functionality. This is required for Android 6.0+ and varies by API level. ### Method N/A (This is a client-side permission request function) ### Endpoint N/A ### Parameters N/A ### Request Example ```typescript import { PermissionsAndroid, Platform } from 'react-native'; async function requestBlePermissions(): Promise { if (Platform.OS !== 'android') { return true; // Permissions not needed on non-Android platforms } const apiLevel = parseInt(Platform.Version.toString(), 10); if (apiLevel < 31) { // Android 11 and below: only need location permission const result = await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION ); return result === PermissionsAndroid.RESULTS.GRANTED; } else { // Android 12+: need Bluetooth-specific permissions const results = await PermissionsAndroid.requestMultiple([ PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN, PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT, PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION ]); return ( results['android.permission.BLUETOOTH_SCAN'] === PermissionsAndroid.RESULTS.GRANTED && results['android.permission.BLUETOOTH_CONNECT'] === PermissionsAndroid.RESULTS.GRANTED && results['android.permission.ACCESS_FINE_LOCATION'] === PermissionsAndroid.RESULTS.GRANTED ); } } // Usage example: async function initializeBle() { const hasPermissions = await requestBlePermissions(); if (!hasPermissions) { console.error('BLE permissions denied'); return false; } // Now safe to use BLE const ble = BleNitro.instance(); const isEnabled = ble.isBluetoothEnabled(); console.log('BLE ready:', isEnabled); return isEnabled; } ``` ### Response #### Success Response (boolean) - Returns `true` if permissions are granted or not applicable (non-Android). Returns `false` if permissions are denied. #### Response Example ```json true ``` ``` -------------------------------- ### JSDoc Example for BLE Connection Function (TypeScript) Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/CONTRIBUTING.md Demonstrates the use of JSDoc for documenting a public API method in TypeScript. It includes parameter descriptions, return types, and an example of usage, adhering to project documentation standards. ```typescript /** * Connects to a BLE device * * @param deviceId - The device identifier * @param options - Connection options * @returns Promise that resolves to the connected device * * @example * ```typescript * const device = await manager.connectToDevice('device-id', { * autoConnect: true, * timeout: 5000 * }); * ``` */ async connectToDevice( deviceId: string, options?: ConnectionOptions ): Promise { // Implementation } ``` -------------------------------- ### Start Development Server for react-native-ble-nitro Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/CONTRIBUTING.md Command to start the development server for the react-native-ble-nitro project, enabling hot-reloading and other development features. ```bash npm run dev ``` -------------------------------- ### Manual Release Workflow Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/RELEASE.md A step-by-step guide for manually releasing the package to npm. It includes checking the working directory, running pre-publish checks, updating the version, publishing, and pushing tags. ```bash # 1. Ensure clean working directory git status # 2. Run full build and tests npm run prepublishOnly # 3. Update version (patch/minor/major) npm version patch # or minor/major # 4. Publish to npm npm publish # 5. Push tags to GitHub git push && git push --tags ``` -------------------------------- ### Install Pods for iOS CLI Projects Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/README.md Installs the necessary CocoaPods dependencies for iOS projects when using the React Native CLI setup. ```bash npx pod-install ``` -------------------------------- ### iOS BLE Manager Implementation Example (Swift) Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/CONTRIBUTING.md A Swift code snippet demonstrating the implementation of a BLE Manager for iOS using Core Bluetooth. It shows how to initialize the CBCentralManager and handle the Bluetooth state. ```swift class BleNitroBleManager: HybridBleManagerSpec { private var centralManager: CBCentralManager! public override init() { super.init() self.centralManager = CBCentralManager(delegate: self, queue: nil) } public func state() throws -> Promise { return Promise.resolve(mapCBManagerState(centralManager.state)) } } ``` -------------------------------- ### Verify Publication on npm Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/RELEASE.md Commands to verify that a package has been successfully published to npm and to test its installation. This is a crucial post-release step to ensure the package is accessible and functional. ```bash # Check package on npm npm view react-native-ble-nitro # Test installation npm install react-native-ble-nitro ``` -------------------------------- ### Heart Rate Monitor Subscription Example (TypeScript) Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/README.md An example of connecting to a Heart Rate Monitor device and subscribing to its heart rate measurement characteristic. It includes device connection, service discovery, and handling incoming heart rate data. The subscription is removed when no longer needed. ```typescript const HEART_RATE_SERVICE = '180d'; const HEART_RATE_MEASUREMENT = '2a37'; const autoConnectOnAndroid = true; // Optional: auto-reconnect on Android const deviceId = await ble.connect( heartRateDeviceId, (deviceId, interrupted, error) => { console.log('Device got Disconnected'); console.log('Was Interrupted?', interrupted); console.log('Error:', error); }, autoConnectOnAndroid, ); await ble.discoverServices(deviceId); const subscription = await ble.subscribeToCharacteristic( deviceId, HEART_RATE_SERVICE, HEART_RATE_MEASUREMENT, (_, data) => { const heartRate = data[1]; // Second byte contains BPM console.log('Heart rate:', heartRate, 'BPM'); } ); // Unsubscribe when done await subscription.remove(); ``` -------------------------------- ### Install react-native-ble-nitro and Dependencies Source: https://context7.com/zykeco/react-native-ble-nitro/llms.txt Installs the react-native-ble-nitro package along with its peer dependency, react-native-nitro-modules. This is the initial step for integrating BLE functionality into your React Native project. ```bash npm install react-native-nitro-modules react-native-ble-nitro ``` -------------------------------- ### Initialize BleNitro Instance in TypeScript Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/README.md Demonstrates how to get the singleton instance of BleNitro or create a custom manager instance with state restoration capabilities in TypeScript. ```typescript import { BleNitro, BleNitroManager, BLEState, AndroidScanMode, type BLEDevice } from 'react-native-ble-nitro'; // Get the singleton instance const ble = BleNitro.instance(); // Use custom manager instance (e.g. for iOS state restoration) // It is recommended to create this instance in an extra file seperated from other BLE business logic for better fast-refresh support const ble = new BleNitroManager({ restoreIdentifier: 'my-unique-identifier', onRestoredState: (peripherals) => { console.log('Restored peripherals:', peripherals); }, }); ``` -------------------------------- ### Clean Build Command Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/RELEASE.md Executes a clean build process for the project, removing previous build artifacts. This is typically a prerequisite before starting a new build cycle. ```bash npm run clean ``` -------------------------------- ### Android BLE Manager Implementation Example (Kotlin) Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/CONTRIBUTING.md A Kotlin code snippet illustrating the implementation of a BLE Manager for Android using Android BLE APIs. It includes lazy initialization of the BluetoothAdapter and handling of the Bluetooth state. ```kotlin class BleNitroBleManager(private val context: ReactApplicationContext) : HybridBleManagerSpec { private val bluetoothAdapter: BluetoothAdapter? by lazy { (context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager).adapter } override fun state(): Promise = Promise.resolve { when { bluetoothAdapter == null -> State.Unsupported !bluetoothAdapter.isEnabled -> State.PoweredOff else -> State.PoweredOn } } } ``` -------------------------------- ### Development Build Commands (npm/npx) Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/README.md A set of bash commands for setting up and building the react-native-ble-nitro library during development. These commands cover dependency installation, native code generation, TypeScript compilation, testing, and code linting. ```bash # Install dependencies npm install # Generate native Nitro code npx nitro-codegen # Build TypeScript npm run build # Run tests npm test # Lint code npm run lint ``` -------------------------------- ### CMake Project Setup for BleNitro Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/android/CMakeLists.txt Configures the CMake project for BleNitro, setting the minimum version, package name, verbosity, and C++ standard to 20. It also enables raw props parsing for Nitro Views. ```cmake project(BleNitro) cmake_minimum_required(VERSION 3.9.0) set (PACKAGE_NAME BleNitro) set (CMAKE_VERBOSE_MAKEFILE ON) set (CMAKE_CXX_STANDARD 20) # Enable Raw Props parsing in react-native (for Nitro Views) add_compile_options(-DRN_SERIALIZABLE_STATE=1) # Define C++ library and add all sources add_library(${PACKAGE_NAME} SHARED src/main/cpp/cpp-adapter.cpp ) # Add Nitrogen specs :) include(${CMAKE_SOURCE_DIR}/../nitrogen/generated/android/BleNitro+autolinking.cmake) # Set up local includes include_directories( "src/main/cpp" "../cpp" ) find_library(LOG_LIB log) # Link all libraries together target_link_libraries( ${PACKAGE_NAME} ${LOG_LIB} android # <-- Android core ) ``` -------------------------------- ### Test Example for BleManager in react-native-ble-nitro Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/CONTRIBUTING.md A unit test written in TypeScript using Jest for the BleManager class, verifying its ability to retrieve the Bluetooth state. ```typescript import { BleManager } from '../index'; import { State } from '../specs/types'; describe('BleManager', () => { let manager: BleManager; beforeEach(() => { manager = new BleManager(); }); afterEach(async () => { await manager.destroy(); }); it('should get Bluetooth state', async () => { const state = await manager.state(); expect(typeof state).toBe('number'); expect(Object.values(State)).toContain(state); }); }); ``` -------------------------------- ### Manage Bluetooth State in TypeScript Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/README.md Provides TypeScript examples for checking Bluetooth status, requesting enablement on Android, subscribing to state changes, and opening device settings. ```typescript // Check if Bluetooth is enabled const isEnabled = ble.isBluetoothEnabled(); // Get current Bluetooth state const state = ble.state(); // Returns: BLEState.PoweredOn, BLEState.PoweredOff, etc. // Request to enable Bluetooth (Android only) await ble.requestBluetoothEnable(); // Subscribe to state changes const subscription = ble.subscribeToStateChange((state) => { console.log('Bluetooth state changed:', state); }, true); // true = emit initial state // Unsubscribe from state changes subscription.remove(); // Open Bluetooth settings await ble.openSettings(); ``` -------------------------------- ### Get Singleton BLE Instance (BleNitro.instance()) Source: https://context7.com/zykeco/react-native-ble-nitro/llms.txt Retrieves the singleton instance of the BLE manager using BleNitro.instance(). This provides direct access to BLE functionalities but does not support iOS state restoration. It allows checking Bluetooth status and current state. ```typescript import { BleNitro, BLEState, type BLEDevice } from 'react-native-ble-nitro'; // Get singleton instance const ble = BleNitro.instance(); // Check if Bluetooth is enabled const isEnabled = ble.isBluetoothEnabled(); console.log('Bluetooth enabled:', isEnabled); // true or false // Get current Bluetooth state const state = ble.state(); console.log('Current state:', state); // BLEState.PoweredOn, BLEState.PoweredOff, etc. ``` -------------------------------- ### Pull Request Template Markdown Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/CONTRIBUTING.md A markdown template used for creating pull requests, guiding contributors to provide necessary information about their changes, including description, type of change, testing status, and a checklist. ```markdown ## Description Brief description of the changes ## Type of Change - [ ] Bug fix - [ ] New feature - [ ] Breaking change - [ ] Documentation update ## Testing - [ ] Tests pass locally - [ ] Added tests for new functionality - [ ] Tested on iOS - [ ] Tested on Android ## Checklist - [ ] Code follows style guidelines - [ ] Self-review completed - [ ] Documentation updated - [ ] No breaking changes (or documented) ``` -------------------------------- ### Scan for BLE Devices in TypeScript Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/README.md Illustrates how to start and stop BLE device scanning, check scanning status, and retrieve already connected devices. Includes options for filtering by service UUIDs, RSSI thresholds, duplicate discovery, and Android scan modes. ```typescript // Start scanning for devices ble.startScan({ serviceUUIDs: ['180d'], // Optional: filter by service UUIDs rssiThreshold: -80, // Optional: minimum signal strength allowDuplicates: false, // Optional: allow duplicate discoveries androidScanMode: AndroidScanMode.Balanced // Optional: Android scan mode }, (device) => { console.log('Discovered device:', device); }, (error) => { // only called on Android console.error('Scan error:', error); }); // Stop scanning ble.stopScan(); // Check if currently scanning const isScanning = ble.isScanning(); // Get already connected devices const connectedDevices = ble.getConnectedDevices(['180d']); // Optional: filter by service UUIDs ``` -------------------------------- ### Discover Services and Characteristics (TypeScript) Source: https://context7.com/zykeco/react-native-ble-nitro/llms.txt Discover services on a connected BLE device and retrieve their characteristics. This function first discovers all services, then fetches their UUIDs, and finally retrieves the characteristics for each service. It also shows how to get all services and their characteristics at once. ```typescript import { BleNitro } from 'react-native-ble-nitro'; const ble = BleNitro.instance(); async function exploreDevice(deviceId: string) { // Discover all services (required before reading services) await ble.discoverServices(deviceId); // Get list of service UUIDs (always returns full 128-bit UUIDs) const services = await ble.getServices(deviceId); console.log('Services:', services); // ['0000180d-0000-1000-8000-00805f9b34fb', '0000180f-0000-1000-8000-00805f9b34fb'] // Get characteristics for each service for (const serviceUUID of services) { // Both short and long form UUIDs work as input const characteristics = ble.getCharacteristics(deviceId, serviceUUID); console.log(`Service ${serviceUUID}:`); console.log(' Characteristics:', characteristics); } // Or get everything at once const servicesWithChars = await ble.getServicesWithCharacteristics(deviceId); servicesWithChars.forEach(service => { console.log(`Service: ${service.uuid}`); service.characteristics.forEach(char => { console.log(` Characteristic: ${char}`); }); }); } ``` -------------------------------- ### Release Preparation and Publishing Commands (Bash) Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/RELEASE.md A collection of essential bash commands for preparing, testing, and publishing npm packages. These commands are vital for a smooth release workflow. ```bash # Full release preparation npm run prepublishOnly # Check what will be published npm pack --dry-run # Publish with tag npm publish --tag beta # Check package info npm info react-native-ble-nitro # View published files npm view react-native-ble-nitro files ``` -------------------------------- ### Opening Android Studio on Mac (Terminal) Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/README.md A command to launch Android Studio from the terminal on macOS. This is useful for ensuring that the correct environment variables, such as PATH, are inherited, which can resolve issues with finding Android SDK tools. ```bash open -a Android\ Studio.app ``` -------------------------------- ### Build Package Command Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/RELEASE.md Compiles the project, including the Expo plugin and TypeScript files. This command prepares the package for distribution by creating build artifacts in specified directories like `lib/` and `plugin/build/`. ```bash npm run build ``` -------------------------------- ### Automated Release Commands Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/RELEASE.md Demonstrates the use of automated scripts for version bumping and publishing to npm. The `npm version` command handles both the version update and the creation of a git tag, simplifying the release process. ```bash # Version bump automatically builds and pushes tags npm version patch npm publish ``` -------------------------------- ### Prebuild and Run Expo Project Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/README.md Commands to prebuild the Expo project and run it on Android or iOS after configuring the BLE plugin. This step is necessary to apply native changes. ```bash npx expo prebuild npx expo run:android # or npx expo run:ios ``` -------------------------------- ### BleManager Nitro Specification Interface (TypeScript) Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/CONTRIBUTING.md Defines the BleManager interface for Nitro specifications, outlining the contract between JavaScript and native code. It includes methods for checking Bluetooth state and starting device scans. ```typescript // src/specs/BleManager.nitro.ts export interface BleManager extends HybridObject { state(): Promise; startDeviceScan( uuids: string[] | null, options: ScanOptions | null, listener: (error: NativeBleError | null, device: NativeDevice | null) => void ): Promise; } ``` -------------------------------- ### Hotfix Branch Creation and Publishing (Bash) Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/RELEASE.md This snippet demonstrates the bash commands used to create a hotfix branch, increment the patch version, and publish the package. It's crucial for addressing critical bugs quickly. ```bash git checkout -b hotfix/critical-fix-v1.0.1 # Make fix npm version patch npm publish git push && git push --tags ``` -------------------------------- ### Read BLE Characteristic Values Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/README.md Reads data from a specified characteristic on a Bluetooth Low Energy device. The data is returned as an ArrayBuffer, which can then be processed. An example demonstrates reading the battery level characteristic. ```typescript // Read a characteristic value const data = await ble.readCharacteristic(deviceId, serviceUUID, characteristicUUID); // Returns: ArrayBuffer - binary data // Example: Reading battery level const batteryData = await ble.readCharacteristic(deviceId, '180f', '2a19'); const batteryLevel = batteryData[0]; // First byte is battery percentage console.log('Battery level:', batteryLevel + '%'); ``` -------------------------------- ### iOS State Restoration with Custom BleNitroManager Instance Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/README.md Demonstrates how to enable iOS state restoration by creating a custom instance of BleNitroManager with a unique restore identifier and a callback for handling restored peripherals. This approach is recommended from version 1.7.0 onwards. It requires importing BleNitroManager and BLEDevice from 'react-native-ble-nitro'. ```typescript import { BleNitroManager, BLEDevice } from 'react-native-ble-nitro'; const customBleInstance = new BleNitroManager({ restoreIdentifier: 'my-unique-identifier', // unique identifier for state restoration onRestoredState: (peripherals: BLEDevice[]) => { console.log('Restored peripherals:', peripherals); // Handle restored peripherals } }); ``` -------------------------------- ### Read BLE Characteristic Data (TypeScript) Source: https://context7.com/zykeco/react-native-ble-nitro/llms.txt Read data from a specific BLE characteristic on a connected device. The data is returned as a ByteArray (number[]). This example demonstrates reading battery level and body sensor location, showing how to interpret the returned byte array. ```typescript import { BleNitro } from 'react-native-ble-nitro'; const ble = BleNitro.instance(); const BATTERY_SERVICE = '180f'; const BATTERY_LEVEL_CHAR = '2a19'; const HEART_RATE_SERVICE = '180d'; const BODY_SENSOR_LOCATION = '2a38'; async function readDeviceInfo(deviceId: string) { // Read battery level (single byte, 0-100%) const batteryData = await ble.readCharacteristic( deviceId, BATTERY_SERVICE, BATTERY_LEVEL_CHAR ); const batteryPercent = batteryData[0]; console.log('Battery:', batteryPercent + '%'); // Read body sensor location const locationData = await ble.readCharacteristic( deviceId, HEART_RATE_SERVICE, BODY_SENSOR_LOCATION ); const locations = ['Other', 'Chest', 'Wrist', 'Finger', 'Hand', 'Earlobe', 'Foot']; const location = locations[locationData[0]] || 'Unknown'; console.log('Sensor location:', location); return { batteryPercent, location }; } ``` -------------------------------- ### Development Workflow: Sync and Branch in react-native-ble-nitro Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/CONTRIBUTING.md Bash commands for synchronizing local repository with upstream and creating a new feature branch for development. ```bash git fetch upstream git checkout main git merge upstream/main git checkout -b feature/your-feature-name ``` -------------------------------- ### Run Tests for react-native-ble-nitro Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/CONTRIBUTING.md Command to execute the test suite for the react-native-ble-nitro project. ```bash npm test ``` -------------------------------- ### Get Connected BLE Devices (TypeScript) Source: https://context7.com/zykeco/react-native-ble-nitro/llms.txt Retrieves a list of currently connected Bluetooth Low Energy devices. Optionally filters devices by service UUIDs. Returns an array of device objects, each containing details like ID, name, RSSI, services, and connection status. ```typescript import { BleNitro } from 'react-native-ble-nitro'; const ble = BleNitro.instance(); function checkConnectedDevices() { // Get all connected devices with Heart Rate or Battery service const devices = ble.getConnectedDevices(['180d', '180f']); console.log('Found', devices.length, 'connected device(s)'); devices.forEach(device => { console.log('Device:', device.name || 'Unknown'); console.log(' ID:', device.id); console.log(' RSSI:', device.rssi); console.log(' Services:', device.serviceUUIDs); console.log(' Connected:', device.isConnected); }); return devices; } // Get all connected devices (no filter) function getAllConnectedDevices() { return ble.getConnectedDevices([]); } ``` -------------------------------- ### Repository Structure for react-native-ble-nitro Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/CONTRIBUTING.md Illustrates the directory structure of the react-native-ble-nitro project, highlighting source code, native implementations, generated files, and documentation. ```tree react-native-ble-nitro/ ├── src/ # TypeScript source code │ ├── specs/ # Nitro module specifications │ ├── utils/ # Utility functions │ └── __tests__/ # Unit tests ├── ios/ # iOS native implementation (Swift) ├── android/ # Android native implementation (Kotlin) ├── plugin/ # Expo config plugin ├── nitrogen/generated/ # Generated Nitro code (do not edit) ├── docs/ # Documentation └── examples/ # Example applications ``` -------------------------------- ### Start BLE Device Scan with Filters Source: https://context7.com/zykeco/react-native-ble-nitro/llms.txt Initiates a scan for Bluetooth Low Energy devices. Supports filtering by service UUIDs, RSSI threshold, duplicate discovery, and Android scan modes. It accepts a callback for discovered devices and an error callback for Android. The scan can be stopped using stopScan(). ```typescript import { BleNitro, AndroidScanMode, type BLEDevice, type ScanFilter } from 'react-native-ble-nitro'; const ble = BleNitro.instance(); const discoveredDevices: BLEDevice[] = []; // Start scanning with filters const filter: ScanFilter = { serviceUUIDs: ['180d', '180f'], // Heart Rate and Battery services rssiThreshold: -80, // Minimum signal strength allowDuplicates: false, // Filter duplicate discoveries androidScanMode: AndroidScanMode.Balanced // Power/speed tradeoff }; ble.startScan(filter, (device: BLEDevice) => { console.log('Discovered:', device.name, device.id); console.log('RSSI:', device.rssi); console.log('Services:', device.serviceUUIDs); console.log('Connectable:', device.isConnectable); console.log('Manufacturer Data:', device.manufacturerData); // Track unique devices if (!discoveredDevices.find(d => d.id === device.id)) { discoveredDevices.push(device); } }, (error: string) => { // Error callback (Android only) console.error('Scan error:', error); }); // Check if scanning console.log('Is scanning:', ble.isScanning()); // true // Stop scanning after 10 seconds setTimeout(() => { ble.stopScan(); console.log('Found', discoveredDevices.length, 'devices'); }, 10000); ``` -------------------------------- ### Singleton State Restoration (<= 1.6.0) Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/README.md Illustrates how to enable state restoration using the BleNitro singleton instance for versions prior to 1.7.0. It involves obtaining the singleton instance and attaching a callback to handle restored peripherals. This method is deprecated from version 1.7.0. ```typescript // Enable state restoration in BleNitro singleton const ble = BleNitro.instance(); ble.onRestoredState((peripherals) => { console.log('Restored peripherals:', peripherals); }); ``` -------------------------------- ### Testing: Run Tests with Coverage in react-native-ble-nitro Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/CONTRIBUTING.md Command to run all tests and generate a code coverage report for the react-native-ble-nitro project. ```bash npm run test:coverage ``` -------------------------------- ### Create Custom BLE Manager with State Restoration (BleNitroManager) Source: https://context7.com/zykeco/react-native-ble-nitro/llms.txt Creates a custom BLE manager instance using `new BleNitroManager()`. This is recommended for applications requiring BLE connection maintenance in the background, as it supports iOS state restoration. The `onRestoredState` callback handles re-establishing connections to previously connected devices. ```typescript import { BleNitroManager, type BLEDevice } from 'react-native-ble-nitro'; // Create instance with state restoration (recommended for background BLE) const ble = new BleNitroManager({ restoreIdentifier: 'com.myapp.ble-restore', onRestoredState: (peripherals: BLEDevice[]) => { console.log('Restored peripherals:', peripherals); // Reconnect to previously connected devices peripherals.forEach(device => { if (device.isConnected) { console.log('Device still connected:', device.id); } }); } }); ``` -------------------------------- ### Discover Services and Characteristics Source: https://context7.com/zykeco/react-native-ble-nitro/llms.txt This section details how to discover services and characteristics on a connected BLE device using `discoverServices`, `getServices`, `getCharacteristics`, and `getServicesWithCharacteristics`. ```APIDOC ## discoverServices() / getServices() / getCharacteristics() ### Description Discover and enumerate services and characteristics on a connected device. ### Method `POST` (discoverServices), `GET` (getServices, getCharacteristics) ### Endpoint `/deviceId/services` (discoverServices), `/deviceId/services` (getServices), `/deviceId/services/{serviceUUID}/characteristics` (getCharacteristics) ### Parameters #### Path Parameters - **deviceId** (string) - Required - The unique identifier of the BLE device. - **serviceUUID** (string) - Required - The UUID of the service to get characteristics for. #### Query Parameters None #### Request Body None for `getServices` and `getCharacteristics`. `discoverServices` may implicitly take deviceId. ### Request Example ```typescript import { BleNitro } from 'react-native-ble-nitro'; const ble = BleNitro.instance(); async function exploreDevice(deviceId: string) { // Discover all services (required before reading services) await ble.discoverServices(deviceId); // Get list of service UUIDs (always returns full 128-bit UUIDs) const services = await ble.getServices(deviceId); console.log('Services:', services); // Get characteristics for each service for (const serviceUUID of services) { const characteristics = ble.getCharacteristics(deviceId, serviceUUID); console.log(`Service ${serviceUUID}:`); console.log(' Characteristics:', characteristics); } // Or get everything at once const servicesWithChars = await ble.getServicesWithCharacteristics(deviceId); servicesWithChars.forEach(service => { console.log(`Service: ${service.uuid}`); service.characteristics.forEach(char => { console.log(` Characteristic: ${char}`); }); }); } ``` ### Response #### Success Response (200) - **services** (string[]) - An array of service UUIDs. - **characteristics** (string[]) - An array of characteristic UUIDs for a given service. - **servicesWithChars** ({ uuid: string, characteristics: string[] }) - An array of objects, each containing a service UUID and its associated characteristics. #### Response Example ```json { "services": [ "0000180d-0000-1000-8000-00805f9b34fb", "0000180f-0000-1000-8000-00805f9b34fb" ] } ``` ```json { "characteristics": [ "00002a37-0000-1000-8000-00805f9b34fb", "00002a38-0000-1000-8000-00805f9b34fb" ] } ``` ```json { "servicesWithChars": [ { "uuid": "0000180d-0000-1000-8000-00805f9b34fb", "characteristics": [ "00002a37-0000-1000-8000-00805f9b34fb", "00002a38-0000-1000-8000-00805f9b34fb" ] } ] } ``` ``` -------------------------------- ### Testing: Run Specific Test File in react-native-ble-nitro Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/CONTRIBUTING.md Command to execute a specific test file within the react-native-ble-nitro project's test suite. ```bash npm test -- BleManager.test.ts ``` -------------------------------- ### Configure Expo for react-native-ble-nitro Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/README.md Sets up the react-native-ble-nitro plugin in the Expo configuration file (`app.json` or `app.config.js`). This enables background operation, specifies operating modes, and customizes the Bluetooth permission prompt. ```json { "expo": { "plugins": [ [ "react-native-ble-nitro", { "isBackgroundEnabled": true, "modes": ["peripheral", "central"], "bluetoothAlwaysPermission": "Allow $(PRODUCT_NAME) to connect to bluetooth devices" } ] ] } } ``` -------------------------------- ### Write Custom Command to Characteristic (TypeScript) Source: https://github.com/zykeco/react-native-ble-nitro/blob/main/README.md Illustrates how to send a custom command to a device's characteristic. This involves defining the service and characteristic UUIDs, preparing the command data as a byte array, and using the `writeCharacteristic` method. ```typescript const CUSTOM_SERVICE = 'your-custom-service-uuid'; const COMMAND_CHARACTERISTIC = 'your-command-characteristic-uuid'; // Send a custom command const enableLedCommand = [0x01, 0x1f, 0x01]; // Your protocol await ble.writeCharacteristic( deviceId, CUSTOM_SERVICE, COMMAND_CHARACTERISTIC, enableLedCommand ); ```