useBluetooth 是 vueuse 提供的响应式 Web Bluetooth API。用于处理与蓝牙设备相关的任务,如连接蓝牙设备、读取设备特征值等, 它可以帮助简化蓝牙相关功能的开发。
该函数的使用方式如下:
import { useBluetooth } from '@vueuse/core'
const {
isSupported,
isConnected,
device,
requestDevice,
server,
} = useBluetooth({
acceptAllDevices: true,
})
<template>
<button @click="requestDevice()">
Request Bluetooth Device
</button>
</template>
源码分析
- 定义两个 ts 接口
UseBluetoothRequestDeviceOptions和UseBluetoothOptions,它们分别表示了请求蓝牙设备的选项和整个useBluetoothHook 的选项。这些选项包括了一些用于配置请求的属性,如过滤器、可选服务等。 - 定义了一个名为
useBluetooth的函数。这个函数接受一个选项对象,包含了用于配置请求和处理蓝牙设备的逻辑。函数中主要的逻辑包括:- 使用
useSupportedHook 来检测当前环境是否支持蓝牙功能。 - 使用
shallowRef来创建了一个存储蓝牙设备的引用变量device。 - 使用
watch监听device的变化,一旦设备发生变化,就会调用connectToBluetoothGATTServer函数。 - 定义了
requestDevice函数,用于请求蓝牙设备。根据配置参数和过滤器,尝试请求蓝牙设备,并在成功或失败时设置device或error变量。 - 使用
computed创建了一个isConnected计算属性,用于判断蓝牙设备是否已连接。 - 定义了
connectToBluetoothGATTServer函数,用于连接蓝牙 GATT 服务器。这个函数尝试连接设备的 GATT 服务器,如果成功则设置server变量,否则设置error。 - 使用
tryOnMounted和tryOnScopeDispose来在组件挂载和销毁时分别连接和断开蓝牙设备的 GATT 服务器。
- 使用
useBluetooth 函数返回一个对象,其中包含了一些属性和方法,如 isSupported、isConnected、device、requestDevice、server 和 error。
相关知识 navigator?.bluetooth.requestDevice