React Native 蓝牙4.0 BLE开发
生活随笔
收集整理的這篇文章主要介紹了
React Native 蓝牙4.0 BLE开发
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
使用react-native-ble-plx庫進(jìn)行開發(fā)
安裝
yarn add react-native-ble-plx // 輔助數(shù)據(jù)發(fā)送接收buffer工具類 yarn add buffer react-native link react-native-ble-plx 復(fù)制代碼android
修改build.gradle中的最低sdk版本為18
android {...defaultConfig {minSdkVersion 18... 復(fù)制代碼添加權(quán)限
<uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> <uses-permission-sdk-23 android:name="android.permission.ACCESS_COARSE_LOCATION"/><!-- Add this line if your application always requires BLE. More info can be found on:https://developer.android.com/guide/topics/connectivity/bluetooth-le.html#permissions--> <uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/> 復(fù)制代碼使用
android權(quán)限申請(qǐng)
const permissions: Permission[] = ['android.permission.ACCESS_COARSE_LOCATION'];if (Platform.OS == "android") {for (const permission of permissions) {const check = await PermissionsAndroid.check(permission);console.log(`permission ${permission} check ${check}`);if (!check) {await PermissionsAndroid.request(permission);}} } 復(fù)制代碼實(shí)例初始化
const bleManager = new BleManager(); 復(fù)制代碼打開藍(lán)牙
const state = await this.bleManager.state(); if (state == State.PoweredOff) {if (Platform.OS == 'android') {const enable = await this.bleManager.enable();console.log(await this.bleManager.state());} else if (Platform.OS == 'ios') {// ios不能直接打開,用對(duì)話框提示打開藍(lán)牙} } 復(fù)制代碼掃描設(shè)備
bleManager.startDeviceScan(null, null, async (error, device) => {if (error) return console.error(error);// 打印設(shè)備名稱console.log(device.name); }); 復(fù)制代碼連接設(shè)備
uuid連接
bleManager.connectToDevice(id); 復(fù)制代碼device連接
device.connect(); 復(fù)制代碼獲取characteristic
const serviceDevice = await device.discoverAllServicesAndCharacteristics(); const services = await serviceDevice.services(); for (const service of services) {const serviceUUID = service.uuid;// 判斷service是否符合if (match) {const characteristics = await service.characteristics();for (const characteristic of characteristics) {const characteristicUUID = characteristic.uuid;// 判斷characteristic是否符合if (match) {// 獲取讀或者寫characteristic}}} } 復(fù)制代碼數(shù)據(jù)發(fā)送
const array = [0x00, 0x01, ...]; const openValueBase64 = new Buffer(array).toString('base64'); await writeCharacteristic!.writeWithoutResponse(openValueBase64); 復(fù)制代碼數(shù)據(jù)接收
// 監(jiān)聽 readCharacteristic.monitor((error, characteristic) => {if (error) return console.error(error);const value = characteristic!.value!;const buffer = Buffer.from(value, 'base64');// 打印讀取到的數(shù)據(jù)console.log('read', buffer); }); 復(fù)制代碼總結(jié)
以上是生活随笔為你收集整理的React Native 蓝牙4.0 BLE开发的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 重学JavaScript(1)--Jav
- 下一篇: UCloud想吃科创板的“第一个螃蟹”