我正在使用 ble-plx
库通过蓝牙连接到设备。
我编写了这段代码,但我不明白为什么有时会失败,而有时却可以完美地工作。
错误在哪里,这意味着我的代码有时会失败,但在其他方面却可以正常工作?
(我正在连接到两个设备,因此我不知道扫描中首先找到哪一个。)。
scansione1() {
this.manager.startDeviceScan(null, null, (error, device) => {
if (error) {
// This is used if failed immediately the scan
this.manager.stopDeviceScan();
Alert.alert("Error.")
Actions.homepageutente()
return; }
console.log("Start Scan 1");
if ((device.name == this.model_dx(this.props.Model)) || (device.name == this.model_sx(this.props.Model)))
{
this.manager.stopDeviceScan();
this.setState({dispositivo1: device.name})
// I set this variable device1 because I'll use it in other page.
this.setState({device1: device})
device
.connect()
.then( () => {
console.log("Launch scansione 2")
this.scansione2();
})
.catch(() => {
// --> When My connection fails I receive this error <--
Alert.alert("Connection bluetooth device 1 not working");
Actions.homepage();
});
}
else if ((device.name == null )) {
this.manager.stopDeviceScan();
this.scansione1();
} else {
this.manager.stopDeviceScan();
Alert.alert("Device " + device.name + " Not find.");
Actions.homepage();
}
});
}
非常感谢:)
最佳答案
您的代码似乎可以工作!特别是你可以连接到设备,但只需要几次尝试。我会检查以下内容来解决您的问题。
- 尝试不同的设备 - 这将告诉您问题是否出在您的连接或您所连接的设备上。
- 更换您的设备或运行应用程序的设备中的蓝牙芯片 - 这将为您提供一个全新的开始,帮助您解决问题。
- 将您的问题报告给设备问题,看看其他人是否也遇到过类似的连接问题。
或者,添加失败后重试连接的方法。我会这样实现:
let i=1;
while (i=1) {
if ((device.name == this.model_dx(this.props.Model)) || (device.name == this.model_sx(this.props.Model)))
{
this.manager.stopDeviceScan();
this.setState({dispositivo1: device.name})
// I set this variable device1 because I'll use it in other page.
this.setState({device1: device})
device
.connect()
.then( () => {
console.log("Launch scansione 2")
this.scansione2();
i++
})
.catch(() => {
// --> When My connection fails I receive this error <--
Alert.alert("Connection bluetooth device 1 not working");
});
}
}
关于javascript - 通过蓝牙连接设备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58130478/