useBluetooth
リアクティブなWeb Bluetooth API。Bluetooth Low Energy周辺機器との接続およびインタラクション機能を提供します。
Web Bluetooth APIを使用すると、WebサイトはGeneric Attribute Profile(GATT)を使用してBluetooth 4ワイヤレス規格を介してデバイスを検出および通信できます。
注:現在、Android M、Chrome OS、Mac、およびWindows 10で部分的に実装されています。ブラウザの互換性の詳細については、Web Bluetooth APIブラウザの互換性を参照してください。
注:Web Bluetooth APIの仕様には、注意すべき点がいくつかあります。デバイスの検出と接続に関する多くの注意点については、Web Bluetooth W3Cドラフトレポートを参照してください。
注:このAPIはWebワーカーでは利用できません(WorkerNavigator経由で公開されていません)。
デモ
未接続
デフォルトの使用法
import { useBluetooth } from '@vueuse/core'
const {
isSupported,
isConnected,
device,
requestDevice,
server,
} = useBluetooth({
acceptAllDevices: true,
})
<template>
<button @click="requestDevice()">
Request Bluetooth Device
</button>
</template>
デバイスがペアリングされ、接続されたら、必要に応じてサーバーオブジェクトを操作できます。
バッテリーレベルの例
このサンプルは、Web Bluetooth APIを使用して、バッテリー情報をBluetooth Low Energyでアドバタイズする近くのBluetoothデバイスからバッテリーレベルを読み取り、変更を通知する方法を示しています。
ここでは、characteristicvaluechangedイベントリスナーを使用して、バッテリーレベルの特性値を読み取る処理を行います。このイベントリスナーは、必要に応じて今後の通知も処理します。
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()
})
import { pausableWatch, useBluetooth } from '@vueuse/core'
const { isSupported, isConnected, device, requestDevice, server } =
useBluetooth({
acceptAllDevices: true,
optionalServices: ['battery_service'],
})
const batteryPercent = ref()
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()
})
<template>
<button @click="requestDevice()">
Request Bluetooth Device
</button>
</template>
その他のサンプルは、Google ChromeのWeb Bluetoothサンプルにあります。
型宣言
型宣言を表示
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://developer.mozilla.org/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: Ref<boolean>
isConnected: ComputedRef<boolean>
device: Ref<BluetoothDevice | undefined>
requestDevice: () => Promise<void>
server: Ref<BluetoothRemoteGATTServer | undefined>
error: Ref<unknown | null>
}