首页 > 解决方案 > 在 chrome web BLE 中调用 startNotifications() 后未收到值

问题描述

我正在尝试用 chrome 连接Muse 头带,这样我就可以流式传输实时脑电波数据。

我可以使用端口在 python 中很好地连接和流式传输数据,但是无法通过 web BLE 流式传输数据。

使用下面的代码,我可以连接到设备并 startNotifications(),但是“characteristicvaluechanged”的事件侦听器没有被触发。我也尝试过连接其他蓝牙设备,但没有读取任何值,所以我认为这不是 Muse 问题。

<h1>Test HTML</h1>
<button id="read" onclick="onButtonClick(event)">Connect with the BLE device</button>

<script>
function onButtonClick(event){
    connectBLE()
}

async function connectBLE() {
  let serviceUuid = '5052494d-2dab-0341-6972-6f6861424c45'
  let characteristicUuid = '43484152-2dab-3141-6972-6f6861424c45' 

  try {
    console.log('Requesting Bluetooth Device...');
    const device = await navigator.bluetooth.requestDevice({
        filters: [{services: [serviceUuid]}]});

    console.log('Connecting to GATT Server...');
    const server = await device.gatt.connect();

    console.log('Getting Service...');
    const service = await server.getPrimaryService(serviceUuid);

    console.log('Getting Characteristic...');
    myCharacteristic = await service.getCharacteristic(characteristicUuid);

    await myCharacteristic.startNotifications();

    console.log(myCharacteristic)

    console.log('> Notifications started');
    myCharacteristic.addEventListener('characteristicvaluechanged',
        handleNotifications);
  } catch(error) {
    console.log('Argh! ' + error);
  }
}


function handleNotifications(event) {
  console.log('YEAH!')
  let value = event.target.value;
  let a = [];
  // Convert raw data bytes to hex values just for the sake of showing something.
  // In the "real" world, you'd use data.getUint8, data.getUint16 or even
  // TextDecoder to process raw data bytes.
  for (let i = 0; i < value.byteLength; i++) {
    a.push('0x' + ('00' + value.getUint8(i).toString(16)).slice(-2));
  }
  console.log('> ' + a.join(' '));
}

</script>

有人遇到过类似的问题吗?我在网上找不到任何解决方案,所以这是我最后的手段。

PS:我正在运行 Ubuntu 18.04 和 Chromium 83.0.4103.61

标签: javascriptgoogle-chromebluetoothbluetooth-lowenergymuse

解决方案


推荐阅读