Skip to content

useBluetooth

扫描和连接蓝牙设备,访问 GATT 服务和特征值。

前置依赖

依赖参数

参数名类型说明
deps.vue.ref<T>(value: T) => Ref<T>Vue ref 函数
deps.vue.onMounted(fn: () => void) => voidVue onMounted 钩子
deps.vue.onUnmounted(fn: () => void) => voidVue onUnmounted 钩子
deps.bluetoothBluetooth蓝牙 API

环境要求

浏览器 API: Web Bluetooth API

平台支持:

  • macOS (Chrome/Edge) - 完全支持
  • Windows (Chrome/Edge) - 完全支持
  • Linux (Chrome) - 完全支持
  • Android (Chrome) - 完全支持
  • iOS/iPadOS (所有浏览器) - 不支持

注意:

  • 需要 HTTPS 环境(本地开发可使用 localhost
  • 仅支持蓝牙低功耗(BLE)设备
  • iPhone 和 iPad 上的所有浏览器都不支持 Web Bluetooth API

函数签名

typescript
function useBluetooth(
  deps: UseBluetoothDeps
): UseBluetoothReturn

interface UseBluetoothDeps {
  vue: VueCompositionAPI
  bluetooth: Bluetooth
}

interface UseBluetoothReturn {
  isSupported: Ref<boolean>
  device: Ref<BluetoothDevice | null>
  isRequesting: Ref<boolean>
  error: Ref<string | null>
  requestDevice: (options?: BluetoothRequestOptions) => Promise<void>
  disconnect: () => void
}

interface BluetoothRequestOptions {
  filters?: Array<{
    name?: string
    namePrefix?: string
    services?: string[]
  }>
  optionalServices?: string[]
  acceptAllDevices?: boolean
}

参数

参数名类型必填说明
depsUseBluetoothDeps依赖注入对象

返回值

属性类型说明
isSupportedRef<boolean>是否支持蓝牙 API
deviceRef<BluetoothDevice | null>当前连接的设备
isRequestingRef<boolean>是否正在请求设备
errorRef<string | null>错误信息
requestDevice(options?) => Promise<void>请求蓝牙设备
disconnect() => void断开设备连接

设备过滤选项

按设备名称过滤

typescript
await requestDevice({
  filters: [{ name: 'My Device' }]
})

按服务类型过滤

typescript
await requestDevice({
  filters: [{ services: ['battery_service'] }],
  optionalServices: ['battery_service']
})

常用服务:

  • battery_service - 电池服务
  • heart_rate - 心率服务
  • device_information - 设备信息
  • generic_access - 通用访问

接受所有设备

typescript
await requestDevice({
  acceptAllDevices: true
})

工作原理

  1. 检查浏览器是否支持 Web Bluetooth API
  2. 调用 requestDevice 显示设备选择器
  3. 用户选择设备后自动连接到 GATT 服务器
  4. 自动监听设备断开事件 - 当设备断开连接时会自动更新状态
  5. 可通过 device.value.gatt 访问服务和特征值
  6. 读取/写入设备数据
  7. 组件卸载时自动断开连接并清理事件监听

重要特性:

  • ✅ 调用 requestDevice() 后会自动连接设备
  • ✅ 自动监听 gattserverdisconnected 事件
  • ✅ 设备断开时会实时更新状态(如操作系统断开蓝牙)
  • ✅ 断开时会设置 error.value = '设备已断开连接'

连接后的操作

连接设备后,可以通过 device.value.gatt 访问 GATT 服务和特征值:

typescript
// 1. 获取 GATT 服务
const server = await bluetooth.device.value.gatt.connect()
const service = await server.getPrimaryService('battery_service')

// 2. 获取特征值
const characteristic = await service.getCharacteristic('battery_level')

// 3. 读取数据
const value = await characteristic.readValue()
const batteryLevel = value.getUint8(0)
console.log(`电池电量: ${batteryLevel}%`)

// 4. 写入数据
const data = new Uint8Array([0x01, 0x02, 0x03])
await characteristic.writeValue(data)

// 5. 监听通知
characteristic.addEventListener('characteristicvaluechanged', (event) => {
  const value = event.target.value
  console.log('数据变化:', value)
})
await characteristic.startNotifications()

重要限制:

  • 不支持文件传输 - 只用于小数据包通信(最多 512 字节)
  • 不支持经典蓝牙 - 只支持蓝牙低功耗(BLE)设备
  • 不能控制手机/电脑 - 无法控制音量、通话等系统功能
  • 手机不会暴露服务 - 手机作为被控端不会暴露系统级 GATT 服务
  • ✅ 支持读取传感器数据(心率、温度等)
  • ✅ 支持写入控制指令(开关灯、调节参数等)
  • ✅ 支持实时通知接收

适用设备:

  • 健康设备:心率监测器、血压计、体温计、血糖仪
  • 可穿戴设备:智能手表、健身手环、智能眼镜
  • 智能家居:智能灯泡、温控器、门锁、开关
  • 传感器:温湿度传感器、运动传感器、空气质量监测器
  • 其他 BLE 设备:电子秤、遥控器、游戏手柄

不适用设备:

  • 手机/电脑:不会作为 BLE 外设暴露服务
  • 蓝牙耳机:使用经典蓝牙协议(A2DP),不是 BLE
  • 蓝牙音箱:使用经典蓝牙协议
  • 需要控制系统功能:音量、通话、通知等无法通过 Web API 控制