React Native 藍芽4.0 BLE開發

qiushijie發表於2019-04-02

使用react-native-ble-plx庫進行開發

安裝

yarn add react-native-ble-plx
// 輔助資料傳送接收buffer工具類
yarn add buffer
react-native link react-native-ble-plx
複製程式碼

android

修改build.gradle中的最低sdk版本為18

android {
    ...
    defaultConfig {
        minSdkVersion 18
        ...
複製程式碼

新增許可權

<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"/>
複製程式碼

使用

android許可權申請

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);
    }
  }
}
複製程式碼

例項初始化

const bleManager = new BleManager();
複製程式碼

開啟藍芽

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不能直接開啟,用對話方塊提示開啟藍芽
  }
}
複製程式碼

掃描裝置

bleManager.startDeviceScan(null, null, async (error, device) => {
    if (error) return console.error(error);
    // 列印裝置名稱
    console.log(device.name);
});
複製程式碼

連線裝置

uuid連線

bleManager.connectToDevice(id);
複製程式碼

device連線

device.connect();
複製程式碼

獲取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
          }
        }
  }
}
複製程式碼

資料傳送

const array = [0x00, 0x01, ...];
const openValueBase64 = new Buffer(array).toString('base64');
await writeCharacteristic!.writeWithoutResponse(openValueBase64);
複製程式碼

資料接收

// 監聽
readCharacteristic.monitor((error, characteristic) => {
    if (error) return console.error(error);
    const value = characteristic!.value!;
    const buffer = Buffer.from(value, 'base64');
    // 列印讀取到的資料
    console.log('read', buffer);
});
複製程式碼

相關文章