VueUse useBluetooth 响应式Web蓝牙API。提供与低功耗蓝牙外设连接和交互的能力。
Web蓝牙API允许网站使用通用属性配置文件(GATT)通过蓝牙4无线标准发现并与设备通信。
注:它目前在Android M, Chrome OS, Mac和Windows 10中部分实现。有关浏览器兼容性的完整概述,请参阅Web蓝牙API浏览器兼容性
注意:关于web蓝牙API规范,需要注意一些注意事项。请参阅Web蓝牙W3C草案报告,了解有关设备检测和连接的许多警告。
注:此API在Web Workers中不可用(未通过WorkerNavigator暴露)。
import { useBluetooth } from '@vueuse/core'
const {
isSupported,//是否支持蓝牙
isConnected,//是否连接
device,//蓝牙设备
requestDevice,//请求连接蓝牙
server, //蓝牙相关的服务接口
} = useBluetooth({
acceptAllDevices: true,
})
请求连接蓝牙
<template>
<button @click="requestDevice()">
Request Bluetooth Device
</button>
</template>
举一个获取电池电量的例子
import { pausableWatch, useBluetooth } 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:
batteryLevelCharacteristic.addEventListener('characteristicvaluechanged', (event) => {
batteryPercent.value = event.target.value.getUint8(0)
})
// 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()
})
蓝牙相关的函数和方法太多了,请访问Chrome 官方文档 https://googlechrome.github.io/samples/web-bluetooth/battery-level.html