Skip to content

useBluetooth

类别
导出体积
1.04 kB
上次更改
2 months ago

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

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

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

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

注意:此 API 在 Web Workers 中不可用 (不通过 WorkerNavigator 暴露)。

示例

Your browser does not support the Bluetooth 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
()">
请求蓝牙设备 </
button
>
</template>

当设备已配对并连接时,你可以自由地使用 server 对象。

电池电量示例用法

此示例演示了使用 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
()">
请求蓝牙设备 </
button
>
</template>

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

类型声明

显示类型声明
ts
export interface UseBluetoothRequestDeviceOptions {
  /**
   *
   * BluetoothScanFilters 的数组。
   * 此过滤器由 BluetoothServiceUUIDs 数组、名称参数和名称前缀参数组成。
   *
   */
  
filters
?: BluetoothLEScanFilter[] | undefined
/** * * BluetoothServiceUUIDs 的数组。 * * @see https://developer.mozilla.org/en-US/docs/Web/API/BluetoothRemoteGATTService/uuid * */
optionalServices
?:
BluetoothServiceUUID
[] | undefined
} export interface UseBluetoothOptions extends UseBluetoothRequestDeviceOptions, ConfigurableNavigator { /** * * 一个布尔值,指示请求脚本是否可以接受所有蓝牙设备。 * 默认值为 false。 * * !! 这可能导致选择器中显示大量无关的设备, * 并因为没有过滤器而浪费能量。 * * * 使用时要谨慎。 * * @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

更新日志

d32f8 - refactor: add @__NO_SIDE_EFFECTS__ annotations to all pure functions (#4907)
c6c6e - feat: use useEventListener where it was not being used (#4479)
fcc6e - fix: isConnected state not changed when disconnected (#4460)
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)