Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions android/src/main/java/so/onekey/lib/ble/utils/BleUtilsModule.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
36 changes: 36 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -19,6 +23,38 @@ class BleUtils {
});
}

/**
* [Android only]
* @param macAddress
* @returns
*/
pairDevice(macAddress: string): Promise<PairDeviceResult> {
if (Platform.OS !== 'android')
return Promise.resolve({
bonded: true,
bonding: false,
});
return new Promise<PairDeviceResult>((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.
Expand Down
Loading