useBluetooth

useBluetooth

リアクティブな Web Bluetooth API。Bluetooth Low Energy 周辺機器と接続し、対話する機能を提供します。

Web Bluetooth API は、Generic Attribute Profile (GATT) を使用して、Bluetooth 4 ワイヤレス標準を介してデバイスを発見し、通信することをウェブサイトに許可します。

注意:現在、Android M、Chrome OS、Mac、および Windows 10 で部分的に実装されています。ブラウザの互換性の全体像については、Web Bluetooth API Browser Compatibility を参照してください。

注意:Web Bluetooth API の仕様には、注意すべき点がいくつかあります。デバイスの検出と接続に関する多くの注意点については、Web Bluetooth W3C Draft Report を参照してください。

注意:この API は Web Workers では利用できません(WorkerNavigator 経由で公開されていません)。

使用方法 デフォルト

<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 Bluetooth API を使用して、Bluetooth Low Energy でバッテリー情報を広告している近くの Bluetooth デバイスからバッテリーレベルを読み取り、変更を通知する方法を示しています。

ここでは、characteristicvaluechanged イベントリスナーを使用して、バッテリーレベルの特性値を読み取ります。このイベントリスナーは、今後の通知もオプションで処理します。

<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

  // バッテリーサービスを取得:
  const batteryService = await server.getPrimaryService('battery_service')

  // 現在のバッテリーレベルを取得
  const batteryLevelCharacteristic = await batteryService.getCharacteristic(
    'battery_level',
  )

  // `characteristicvaluechanged` イベントで特性値が変更されたときにリッスン:
  useEventListener(batteryLevelCharacteristic, 'characteristicvaluechanged', (event) => {
    batteryPercent.value = event.target.value.getUint8(0)
  }, { passive: true })

  // 受信したバッファを数値に変換:
  const batteryLevel = await batteryLevelCharacteristic.readValue()

  batteryPercent.value = await batteryLevel.getUint8(0)
}

const { stop } = watchPausable(isConnected, (newIsConnected) => {
  if (!newIsConnected || !server.value || isGettingBatteryLevels.value)
    return
  // デバイスのバッテリーレベルを取得しようとする:
  getBatteryLevels()
  // 更新を処理するためにイベントリスナーを使用するので、初回接続時のみ実行したい:
  stop()
})
</script>

<template>
  <button @click="requestDevice()">
    Request Bluetooth Device
  </button>
</template>

より多くのサンプルは Google Chrome's Web Bluetooth Samples で見つけることができます。