跳到主要內容

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 Worker 中不可用(未透過 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>

當裝置配對並連線後,您就可以隨意使用伺服器物件。

電池電量範例

此範例說明如何使用 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://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>
}

原始碼

原始碼範例文件

貢獻者

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

更新日誌

v12.5.0 on 1/22/2025
c6c6e - feat: 在未使用的地方使用 useEventListener (#4479)
v12.4.0 on 1/10/2025
fcc6e - fix: 斷線時 isConnected 狀態未變更 (#4460)
v12.0.0-beta.1 on 11/21/2024
0a9ed - feat!: 移除 Vue 2 支援,最佳化 bundle 並清理 (#4349)

以 MIT 授權條款發布。