0

首先,我想说我是连接蓝牙和 BLE 的新手,所以我的问题旨在了解它是如何工作的。

我正在开发一个必须连接到 BLE 设备的 React Native APP。

我使用 react-native-ble-plx 来管理连接。

现在,我可以连接到我的设备、读取服务并获取特征和描述符。

我需要从 BLE 控制器接收 JSON 字符串(我假设特性应该完成这项工作,但我不确定)并且我还需要发送 JSON 以与 BLE 对话。

所以,我以这种方式连接我的设备:

this.manager.stopDeviceScan();
mDevice = await device.connect();

然后,我得到所有服务:

mDevice = await mDevice.discoverAllServicesAndCharacteristics();
const discoveredServices = await mDevice.services();

我可以找到我需要实现的服务及其特点:

const mainService = discoveredServices.filter(service => service.uuid === MY_SERVICE)[0];
const characteristics = await mDevice.characteristicsForService(mainService.uuid);

从这一点开始,一切都是黑色的......我的意思是,我可以读取字符描述符,其中一些有一个值,例如 AAA= 或 AQA=,假设它是 base64,但解码什么也没给我。

我想做的是从某个地方读取一个 JSON 字符串,但我找不到它。

我尝试了多种方法,最后一种:

 // FOREACH CHARACTERISTIC
 for (let i = 0; i < characteristics.length; i++) {
    const char = characteristics[i];
    let value = '';
    // GET DESCRIPTORS
    const descriptors = await char.descriptors();
    for (let e = 0; e < descriptors.length; e++) {
      const descriptor = descriptors[e];
      // READING THE DESCRIPTOR
      const descRead = await descriptor.read();
      if (descRead) {
        // GET VALUE
        value += 'ORIGINAL: ' + descRead.value + '; DECODED: ' + base64.decode(descRead.value);
      }
    }
    
    // VALUES ARE ALWAYS: AAA= OR AQA=
    Alert.alert('Valor', value);
    ...
}

所以在描述符中我找不到我需要的信息,所以我尝试使用监视器和写入特性以便使用 BLE 登录。

  // TRYING TO GET NOTIFICATIONS OR I DONT KNOW...
  const monitor = char.monitor((error, characteristic) => {
      if (error) {
        console.warn(error);
        monitor.remove();
        return;
      }
      // THERES NO VALUES...
      console.log('MONITOR: ' + characteristic?.value);
    });

    // TRYING TO WRITE JSON LOGIN STRING TO CHAR
    const status = await this.manager
      .writeCharacteristicWithResponseForDevice(
        mDevice.id,
        char.serviceUUID,
        char.uuid,
        JSON.stringify(MY_LOGIN_DATA),
      )
      .catch(err => console.log(err));
    // NORMALLY EMPTY BUT SOMETIMES HAS A CHAR OBJECT AS A VALUE 
    if (status) {
      const read = await char.read().catch(err => console.log(err));
    }
  }

我认为我真正的问题是我不明白它是如何工作的,我认为这就像将数据发送到 REST 服务或类似的东西,但我很迷茫......

我检查了 GATT 文档,那里的一切都清楚了,但实践让我很生气。

有什么好的教程吗?有什么推荐吗?

提前致谢。

4

0 回答 0