1

我正在使用网络 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)在这里不起作用。

你会如何处理这个?

4

1 回答 1

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);
}
于 2019-03-23T13:00:36.657 回答