【问题标题】:Web BLE Characteristic startNotifications sometimes doesn't bindWeb BLE 特性 startNotifications 有时不绑定
【发布时间】:2019-03-23 21:00:36
【问题描述】:

我正在使用网络 BLE。我根据心率测量的例子来建立我的代码。

大部分时间一切正常。但有时,即使连接成功,当我尝试绑定通知时,它也不起作用。

链接是在这个函数中建立的:

    _startNotifications(characteristicUuid) {
      let characteristic = this._characteristics.get(characteristicUuid);
      console.log(characteristic);
      return characteristic.startNotifications().then(() => characteristic);
    }

当一切正常时,我可以在控制台中看到BluetoothRemoteGATTCharacteristic 有一个value : DataView(2) {} 否则,当它不工作时,它有一个value : null

如果我检测到该值为空,我希望能够自动重试。但是我对 Promise 不熟悉(我想就是这样),console.log(characteristic.value) 在这里不起作用。

你会如何处理这个?

【问题讨论】:

    标签: javascript promise web-bluetooth


    【解决方案1】:

    我最终做的是“绕过”这个问题。所以它比纯 Javascript 的算法分辨率更高。

    连接函数我没有改,所以还是这样调用的:

    device._startNotifications(some_uuid).then(handleHeartRateMeasurement)
    

    我检查了handleHeartRateMeasurement 函数中的所有内容:

    var ready = false;
    
    function handleHeartRateMeasurement(heartRateMeasurement) {
      console.log("Hold on...");
      heartRateMeasurement.addEventListener("characteristicvaluechanged", event => {
        // Everytime the value change, this should be triggered
        // If it did not, variable "ready" will stay false
        ready = true;
        var value = device.parseValue(event.target.value);
        // Do something with value here
      });
    
      var check = function(){
        // If we have received data from characteristic, we are ready to go !
        if(ready === false){
          console.log("Device connected but not receiving data");
    
          // Stop the current notification subscription
          device.stopNotificationsHeartRateMeasurement();
    
          // Start a new one
          device._startNotifications(some_uuid).then(handleHeartRateMeasurement);
    
          setTimeout(check, 1000); // check again in a 1s
        }
        else{
          console.log("Device connected and receiving data");
        }
      }
    
      setTimeout(() => {
        check();
      }, 500);
    }
    

    【讨论】:

      猜你喜欢
      • 2019-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 2014-12-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多