【问题标题】:Web-Bluetooth API, can not update characteristics. time-dependent updating possible?Web-Bluetooth API,不能更新特性。时间相关的更新可能吗?
【发布时间】:2021-12-16 21:10:43
【问题描述】:

我尝试在每次更改时获取特征,问题是,它们发生了变化,但 eventListener 无法识别。因此,在连接到我的 BLE 后,我只获得了第一个值,但之后什么也没有发生。我的代码有问题吗?

另一个问题,有没有办法更新特性,例如,我不知道 5 秒?你会怎么做,有代码示例吗?(也许有 setInterval() ?)

谢谢!

function test() {
  console.log('Requesting Bluetooth Device...');
  navigator.bluetooth.requestDevice({
    acceptAllDevices: true,
    optionalServices: ['af07ecb8-e525-f189-9043-0f9c532a02c7']
    })                     //c7022a53-9c0f-4390-89f1-25e5b8ec07af
  .then(device => {
    console.log('Gatt Server Verbindung');
    return device.gatt.connect();
  })
  .then(server => {
    console.log('Dose Service...');
    return server.getPrimaryService('af07ecb8-e525-f189-9043-0f9c532a02c7');
  })
  .then(service => {
    console.log('mgyh Characteristic...');
    return service.getCharacteristic('a99e0be6-f705-f59c-f248-230f7d55c3c1');
  })
  .then(characteristic => {
    // Set up event listener for when characteristic value changes.
    characteristic.addEventListener('characteristicvaluechanged',dosechanged);
    
    return characteristic.readValue();
  })
  .catch(error => {
    console.log('Das geht nicht: ' + error);
  });
}

function dosechanged(event) {
  
  let dose = event.target.value.getUint8(0)+event.target.value.getUint8(1)*10+event.target.value.getUint8(2)*100 + event.target.value.getUint8(3)*1000+ event.target.value.getUint8(4)*10000;
  console.log('Received ' + dose);

} 

【问题讨论】:

    标签: javascript bluetooth-lowenergy web-bluetooth


    【解决方案1】:
    1. 您错过了开始接收通知的characteristic.startNotifications() 呼叫。 example
    2. setInterval 可以每隔 5 秒调用一次 readValue()

    【讨论】:

    • 感谢您的回答。我只是遇到了startNotification() 的安全问题,我不知道如何解决它。它不允许通知,我不知道为什么,因为我的 BLE 允许它。很抱歉这个愚蠢的问题,但你会如何添加readValue():喜欢.then(characteristic => { // Set up event listener for when characteristic value changes. characteristic.addEventListener('characteristicvaluechanged',dosechanged); setInterval(characteristic.readValue(),5000); return characteristic.readValue(); })
    • 是的,let tm = setInterval(()=> characteristic.readValue(), 5000);
    • 当我像你告诉我的那样:.then(characteristic => characteristic.startNotifications()) .then(characteristic => { characteristic.addEventListener('characteristicvaluechanged', dosechanged); console.log('Notifications have been started.'); }) 我从控制台得到:SecurityError: GATT operation not authorized。您对此错误也有任何建议吗? :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-06
    • 2012-09-12
    • 1970-01-01
    相关资源
    最近更新 更多