Javascript 读取事件侦听器未在react native中触发

Javascript 读取事件侦听器未在react native中触发,javascript,reactjs,react-native,bluetooth,Javascript,Reactjs,React Native,Bluetooth,我正在react native中进行蓝牙项目,尝试从其他设备读取数据。使用以下代码读取数据 BluetoothSerial.readFromDevice().then((data) => { console.log(data) } 这是完美的工作。 但是我想使用一个事件侦听器来收集其他设备在任意时间发送的数据。 我使用的侦听器位于,由@andrescheca回答。代码如下所示 BluetoothSerial.withDelimiter('\r').then(() =&

我正在react native中进行蓝牙项目,尝试从其他设备读取数据。使用以下代码读取数据

BluetoothSerial.readFromDevice().then((data) => {
      console.log(data)
}
这是完美的工作。 但是我想使用一个事件侦听器来收集其他设备在任意时间发送的数据。 我使用的侦听器位于,由@andrescheca回答。代码如下所示

    BluetoothSerial.withDelimiter('\r').then(() => {
    Promise.all([
      BluetoothSerial.isEnabled(),
      BluetoothSerial.list()
    ])
    .then((values) => {
      const [ isEnabled, devices ] = values
      this.setState({ isEnabled, devices })
    })

    BluetoothSerial.on('bluetoothEnabled', () => console.log('Bluetooth enabled'))
    BluetoothSerial.on('bluetoothDisabled', () => console.log('Bluetooth disabled'))
    BluetoothSerial.on('read', (data) => {

       console.log(`DATA FROM BLUETOOTH: ${data.data}`);
       Toast.show(data.data);
   })
    BluetoothSerial.on('error', (err) => console.log(`Error: ${err.message}`))
    BluetoothSerial.on('connectionLost', () => {
      if (this.state.device) {
        console.log(`Connection to device ${this.state.device.name} has been lost`)
      }
      this.setState({ connected: false })
    })
  });
当我启用和禁用蓝牙时,所有侦听器(即bluetoothEnabled、bluetoothDisabled)都会触发。但是读取侦听器在接收数据时没有启动。我假设它应该在另一个设备发送一些数据后立即启动。
如果有人能帮我解决这个问题,我将不胜感激。

我解决了这个问题,只是在试图从Linux服务器发送到设备的数据末尾添加了\r。
感谢@kendavidson的帮助。

我解决了这个问题,只是在试图从Linux服务器发送到设备的数据末尾添加了\r。
感谢@kendavidson的帮助。

您确定您的设备正在发送“\r”作为分隔符吗?我发现停止读取事件的唯一原因是数据没有正确编码,因此
String completeData=readUntil(this.delimiter)
没有返回任何内容。您确定您的设备正在发送“\r”作为分隔符吗?我发现停止读取事件的唯一原因是数据没有正确编码,因此
String completeData=readUntil(this.delimiter)
没有返回任何内容。