Web BLE特征startNotifications有时不绑定

时间:2019-03-22 18:21:00

标签: javascript promise web-bluetooth

我正在使用Web BLE。我已经根据心率测量示例创建了代码。

大多数情况下,一切正常。但是有时候,即使连接成功完成,当我尝试绑定到通知时,它也无法正常工作。

通过此函数建立链接:

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

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

enter image description here

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

您将如何处理?

1 个答案:

答案 0 :(得分:0)

我最终要做的是“绕过”问题。因此,它比纯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);
}