跳到主要内容

useBluetooth

分类
导出大小
627 B
最近更改
3 周前

响应式 Web Bluetooth API。提供连接和与蓝牙低功耗外围设备交互的能力。

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

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

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

注意:此 API 在 Web Workers 中不可用(不通过 WorkerNavigator 公开)。

演示

您的浏览器不支持 Bluetooth Web API

未连接

默认用法

ts
import { useBluetooth } from '@vueuse/core'

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

当设备已配对并连接后,您可以根据需要使用 server 对象。

用法:电池电量示例

此示例说明了如何使用 Web Bluetooth API 读取电池电量,并接收来自附近通过蓝牙低功耗广播电池信息的蓝牙设备的电量变化通知。

在这里,我们使用 characteristicvaluechanged 事件监听器来处理读取电池电量特征值。此事件监听器还将可选地处理即将到来的通知。

ts
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()
})
js
import { pausableWatch, useBluetooth, useEventListener } from '@vueuse/core'
const { isSupported, isConnected, device, requestDevice, server } =
  useBluetooth({
    acceptAllDevices: true,
    optionalServices: ['battery_service'],
  })
const batteryPercent = ref()
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()
})
vue
<template>
  <button @click="requestDevice()">
    Request Bluetooth Device
  </button>
</template>

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

类型声明

显示类型声明
typescript
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://mdn.org.cn/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>
}

源代码

源代码演示文档

贡献者

Anthony Fu
IlyaL
Anthony Fu
Jelf
Fernando Fernández
Alex Liu
ByMykel
Michael J. Roberts

更新日志

v12.5.0 于 1/22/2025
c6c6e - 特性:在未使用 useEventListener 的地方使用它 (#4479)
v12.4.0 于 1/10/2025
fcc6e - 修复:断开连接时 isConnected 状态未更改 (#4460)
v12.0.0-beta.1 于 11/21/2024
0a9ed - 特性!: 移除 Vue 2 支持,优化捆绑包并清理代码 (#4349)

根据 MIT 许可证发布。