首页 > 解决方案 > 无法使用 react-native-ble-plx 从 BLE 读取

问题描述

我在我的 Ubuntu 机器上使用 React Native 和 BLE 包 react-native-ble-plx。

根据文档,我做了以下事情:

  1. 已扫描设备
  2. 连接到设备
  3. device.discoverAllServicesAndCharacteristics
  4. writeCharacteristicWithResponseForDevice

我的问题在于阅读我从发送命令中得到的响应。

RX 特性是可写的,但 TX 只是可通知的而不是可读的。因此我需要使用 monitorCharacteristicForDevice 来监控特性,但是我无法让它发挥作用。

在下面的代码中,我从未收到过“监控成功”、“从设备接收数据时出错”或“监控失败”。

我如何阅读回报?

monitorDevice = () => {
    this.setState({monitoring: true})
    console.log(this.state.servicesDiscovered)
    if(this.state.servicesDiscovered){
        {this.manager.monitorCharacteristicForDevice(this.state.connectedTo,
            SERVICE_UUID,
            TX_CHARACTERISTIC,
            (error, characteristic) => {
                if (error) {
                    console.error("Error at receiving data from device", error);
                    return     
                }
                else {
                    this.setState({monitoring: true})
                    console.log('monitor success')
                    console.log('monitor success' + characteristic.value);
                    this.state.messagesRecieved.push(characteristic.value)
                }
            })
        }
      }
      else{
          console.log("Monitor failure")
    }
}

checkBattery = () => {
    if(this.state.monitoring){
        this.manager.writeCharacteristicWithResponseForDevice(this.state.connectedTo,
            SERVICE_UUID,
            RX_CHARACTERISTIC,
            "YmF0dGVyeQ==")
        .then(characteristic => {
            console.log("Successfully sent: " + characteristic.value)
            return
        })
        .catch(err => {
            console.log(err)
        })
    }
    else{
        alert("Not monitoring")
    }
}

标签: react-nativebluetooth-lowenergyreact-native-ble-plx

解决方案


推荐阅读