React Native 蓝牙4.0 BLE开发

使用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
        ...
复制代码

添加权限

"android.permission.BLUETOOTH"/>
"android.permission.BLUETOOTH_ADMIN"/>
"android.permission.ACCESS_COARSE_LOCATION"/>


"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);
});
复制代码

你可能感兴趣的:(React Native 蓝牙4.0 BLE开发)