使用WebBluetooth访问多个服务和特征

问题描述

我正在尝试读取体重秤的特性以及电池服务中当前的电池电量。

我有以下适用于体重秤服务和体重测量特性的产品,但是我正在努力寻找如何向其添加电池服务(我对诺言不太熟悉)

function connectGATT() {
  if (bluetoothDeviceDetected.gatt.connected && gattCharacteristic) {
    return Promise.resolve()
  }

  return bluetoothDeviceDetected.gatt.connect()
  .then(server => {
    console.log('Getting GATT Service...')
    return server.getPrimaryService(wsService)
    console.log(wsService)
  })
  .then(service => {
    console.log('Getting GATT Characteristic...')
    return service.getCharacteristic(wsCharacteristic)
    console.log(wsCharacteristic)
  })
  .then(characteristic => {
    gattCharacteristic = characteristic
    gattCharacteristic.addEventListener('characteristicvaluechanged',handleNotifications)
    document.querySelector('#start').disabled = false
    document.querySelector('#stop').disabled = true
  })
}

解决方法

要访问电池服务,您需要调用getCharacteristic('battery_level'),然后在生成的BluetoothGATTRemoteService对象上调用server。请参阅完整示例here

您已经确定的挑战是,当前使用Promises编写的console.log('Connecting to GATT Server...'); const server = await device.gatt.connect(); console.log('Getting Battery Service...'); const service = await server.getPrimaryService('battery_service'); console.log('Getting Battery Level Characteristic...'); const characteristic = await service.getCharacteristic('battery_level'); 变量在此Promise链的末尾不再可用。有两种解决方案。一种是像这样使用async / await,

server

Source

或者您可以将then()变量带入函数的顶层,并在调用connect()之后在then()回调中进行分配,以便可以从多个{ {1}}回调。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...