跳到主要内容

useBluetooth

分类
导出大小
1.04 kB
上次更改
3 个月前

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

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

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

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

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

演示

您的浏览器不支持 Web 蓝牙 API

未连接

默认用法

vue
<script setup lang="ts">
import { 
useBluetooth
} from '@vueuse/core'
const {
isSupported
,
isConnected
,
device
,
requestDevice
,
server
,
} =
useBluetooth
({
acceptAllDevices
: true,
}) </script> <template> <
button
@
click
="
requestDevice
()">
Request Bluetooth Device </
button
>
</template>

设备配对并连接后,您就可以随心所欲地使用服务器对象。

电池电量示例用法

此示例演示了如何使用 Web 蓝牙 API 读取电池电量并接收附近广播电池信息并支持低功耗蓝牙的蓝牙设备的更改通知。

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

vue
<script setup lang="ts">
import { 
useBluetooth
,
useEventListener
,
watchPausable
} 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
} =
watchPausable
(
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
()
}) </script> <template> <
button
@
click
="
requestDevice
()">
Request Bluetooth Device </
button
>
</template>

更多示例可在 Google Chrome 的 Web 蓝牙示例中找到。

类型声明

显示类型声明
ts
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
SerKo
IlyaL
Anthony Fu
Jelf
Vida Xie
Robin
Fernando Fernández
Alex Liu
ByMykel
Michael J. Roberts

更新日志

v13.6.0
d32f8 - refactor: 为所有纯函数添加 @__NO_SIDE_EFFECTS__ 注释 (#4907)
v12.5.0
c6c6e - feat: 在未使用 useEventListener 的地方使用它 (#4479)
v12.4.0
fcc6e - 修复:断开连接时 isConnected 状态未更改 (#4460)
0a9ed - feat!: 放弃对 Vue 2 的支持,优化打包并清理 (#4349)

根据 MIT 许可证发布。