我正在React Native上的Bluetooth项目中工作,我正在尝试从其他设备读取数据。使用以下代码读取数据
BluetoothSerial.readFromDevice().then((data) => {
console.log(data)
}
运作良好。但是我想使用事件监听器来收集其他任何设备在任何随机时间发送的数据。我正在使用在@andrescheca回答的https://github.com/rusel1989/react-native-bluetooth-serial/issues/16找到的监听器。该代码如下所示
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)都会触发。但是读取的Listener不会在接收数据时触发。我假设它应该在另一台设备发送一些数据后立即启动。如果有人可以帮助我解决此问题,我将不胜感激。
我解决了这个问题,只是在试图从Linux服务器发送到设备的数据末尾添加了\ r。感谢@kendavidson的帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句