Lzh on GitHub

响应式 Web Bluetooth API

Web Bluetooth API 提供了连接和与低功耗蓝牙 (Bluetooth Low Energy) 外围设备交互的能力。

Web Bluetooth API 允许网站使用通用属性配置文件 (GATT) 通过蓝牙 4 无线标准发现设备并与之通信。

注意: 目前它仅在 Android M、Chrome OS、Mac 和 Windows 10 中部分实现。有关浏览器兼容性的完整概览,请参见 Web Bluetooth API 浏览器兼容性

注意: Web Bluetooth API 规范有许多需要注意的限制。有关设备检测和连接的众多注意事项,请参考 Web Bluetooth W3C 草案报告

注意:此 API 不适用于 Web Workers(未通过 WorkerNavigator 公开)。

Demo

使用 Default

import { useBluetooth } from '@vueuse/core'

const {
  isSupported,
  isConnected,
  device,
  requestDevice,
  server,
} = useBluetooth({
  acceptAllDevices: true,
})
<template>
  <button @click="requestDevice()">
    Request Bluetooth Device
  </button>
</template>

当设备已配对并连接后,你就可以随意操作 服务器对象 (server object) 了。

电池电量使用示例

此示例演示了如何使用 Web Bluetooth API 从附近的低功耗蓝牙设备读取电池电量,并在电池信息发生变化时接收通知。

在这里,我们使用 characteristicvaluechanged 事件监听器 来处理电池电量特征值的读取。这个事件监听器也会(可选地)处理后续的通知。

import { pausableWatch, useBluetooth, useEventListener } from '@vueuse/core'

const {
  isSupported,
  isConnected,
  device,
  requestDevice,
  server,
} = useBluetooth({
  acceptAllDevices: true,
  optionalServices: [
    'battery_service',
  ],
})

const batteryPercent = ref<undefined | number>()

const isGettingBatteryLevels = ref(false)

async function getBatteryLevels() {
  isGettingBatteryLevels.value = true

  // Get the battery service:
  const batteryService = await server.getPrimaryService('battery_service')

  // Get the current battery level
  const batteryLevelCharacteristic = await batteryService.getCharacteristic(
    'battery_level',
  )

  // Listen to when characteristic value changes on `characteristicvaluechanged` event:
  useEventListener(batteryLevelCharacteristic, 'characteristicvaluechanged', (event) => {
    batteryPercent.value = event.target.value.getUint8(0)
  }, { passive: true })

  // Convert received buffer to number:
  const batteryLevel = await batteryLevelCharacteristic.readValue()

  batteryPercent.value = await batteryLevel.getUint8(0)
}

const { stop } = pausableWatch(isConnected, (newIsConnected) => {
  if (!newIsConnected || !server.value || isGettingBatteryLevels.value)
    return
  // Attempt to get the battery levels of the device:
  getBatteryLevels()
  // We only want to run this on the initial connection, as we will use an event listener to handle updates:
  stop()
})
<template>
  <button @click="requestDevice()">
    Request Bluetooth Device
  </button>
</template>

更多示例可以在 Google Chrome 的 Web Bluetooth 示例 中找到。

类型声明

export interface UseBluetoothRequestDeviceOptions {
  /**
   *
   * An array of BluetoothScanFilters. This filter consists of an array
   * of BluetoothServiceUUIDs, a name parameter, and a namePrefix parameter.
   *
   */
  filters?: BluetoothLEScanFilter[] | undefined
  /**
   *
   * An array of BluetoothServiceUUIDs.
   *
   * @see https://developer.mozilla.org/en-US/docs/Web/API/BluetoothRemoteGATTService/uuid
   *
   */
  optionalServices?: BluetoothServiceUUID[] | undefined
}
export interface UseBluetoothOptions
  extends UseBluetoothRequestDeviceOptions,
    ConfigurableNavigator {
  /**
   *
   * A boolean value indicating that the requesting script can accept all Bluetooth
   * devices. The default is false.
   *
   * !! This may result in a bunch of unrelated devices being shown
   * in the chooser and energy being wasted as there are no filters.
   *
   *
   * Use it with caution.
   *
   * @default false
   *
   */
  acceptAllDevices?: boolean
}
export declare function useBluetooth(
  options?: UseBluetoothOptions,
): UseBluetoothReturn
export interface UseBluetoothReturn {
  isSupported: ComputedRef<boolean>
  isConnected: Readonly<ShallowRef<boolean>>
  device: ShallowRef<BluetoothDevice | undefined>
  requestDevice: () => Promise<void>
  server: ShallowRef<BluetoothRemoteGATTServer | undefined>
  error: ShallowRef<unknown | null>
}