I'm using ble-plx
library to connect to a device through Bluetooth.
I wrote this code but I don't understand why sometimes it fails while other time it works perfectly.
Where is the error which means my code sometimes fails but otherwise works perfectly?
(I am connecting to two devices, so I don't know which one is found first in the scan. ).
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();
}
});
}
Thank you so much :)
Your code appears to work! Especially as you can connect to the device, but it just takes a couple of attempts. I would check the following things to get rid of your problem.
Alternatively, add a way of retrying to connect after a failure. I would implement that like this:
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");
});
}
}