diff --git a/android/src/main/java/so/onekey/lib/ble/utils/BleUtilsModule.kt b/android/src/main/java/so/onekey/lib/ble/utils/BleUtilsModule.kt index 36c0ba7..a07115f 100644 --- a/android/src/main/java/so/onekey/lib/ble/utils/BleUtilsModule.kt +++ b/android/src/main/java/so/onekey/lib/ble/utils/BleUtilsModule.kt @@ -124,6 +124,49 @@ class BleUtilsModule(private val reactContext: ReactApplicationContext) : callback.invoke(state) } + @SuppressLint("MissingPermission") + @ReactMethod + fun pairDevice(macAddress: String, callback: Callback) { + val adapter = getBluetoothAdapter() + if (adapter == null) { + callback.invoke("Bluetooth not supported", null) + return + } + + try { + val device = adapter.getRemoteDevice(macAddress) + + var bonded = false + var bonding = false + + when (device.bondState) { + BluetoothDevice.BOND_BONDED -> { + bonded = true + bonding = false + } + + BluetoothDevice.BOND_BONDING -> { + bonded = false + bonding = true + } + + BluetoothDevice.BOND_NONE -> { + val started = device.createBond() + bonded = false + bonding = started + } + } + + val map: WritableMap = Arguments.createMap() + map.putBoolean("bonded", bonded) + map.putBoolean("bonding", bonding) + callback.invoke(null, map) + } catch (e: Exception) { + Log.e(LOG_TAG, "pairDevice error: ${e.message}") + callback.invoke(e.message, null) + } + } + @SuppressLint("MissingPermission") @ReactMethod fun getBondedPeripherals(callback: Callback) { diff --git a/package.json b/package.json index ecd823e..c5f582b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@onekeyfe/react-native-ble-utils", - "version": "0.1.2", + "version": "0.1.3", "description": "ble uilts", "source": "./src/index.tsx", "main": "./dist/commonjs/index.js", diff --git a/src/index.ts b/src/index.ts index e567d71..fd379e0 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2,6 +2,10 @@ import { NativeEventEmitter, NativeModules, Platform } from 'react-native'; import type { BleState, Peripheral, BondState, AdvertisingData } from './type'; const { BleUtilsModule } = NativeModules; +type PairDeviceResult = { + bonded: boolean; + bonding: boolean; +}; class BleUtils { UiEventEmitter: NativeEventEmitter | null = null; @@ -19,6 +23,38 @@ class BleUtils { }); } + /** + * [Android only] + * @param macAddress + * @returns + */ + pairDevice(macAddress: string): Promise { + if (Platform.OS !== 'android') + return Promise.resolve({ + bonded: true, + bonding: false, + }); + return new Promise((fulfill, reject) => { + BleUtilsModule.pairDevice( + macAddress, + (error: string | null, result: PairDeviceResult | null) => { + if (error) { + reject(error); + } else { + if (result) { + fulfill(result); + } else { + fulfill({ + bonded: false, + bonding: false, + }); + } + } + } + ); + }); + } + /** * * @param serviceUUIDs [optional] not used on android, optional on ios.