我正在 native react 中开发一个蓝牙项目,我试图从其他设备读取数据。使用以下代码读取数据
BluetoothSerial.readFromDevice().then((data) => {
console.log(data)
}
运行完美。 但我想使用事件监听器来收集其他设备在任意时间发送的数据。 我正在使用 https://github.com/rusel1989/react-native-bluetooth-serial/issues/16 中找到的监听器由@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 的帮助。
关于javascript - 读取事件监听器未在 native react 中触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60365323/