通过蓝牙连接设备

Connection device through bluetooth

我正在使用 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");
              });
          }
}