Skip to content

useBluetooth

Category
Last Changed
last week

A reactive for working with the Web Bluetooth API which provides the ability to connect and interact with Bluetooth Low Energy peripherals.

The Web Bluetooth API lets websites discover and communicate with devices over the Bluetooth 4 wireless standard using the Generic Attribute Profile (GATT).

N.B. It is currently partially implemented in Android M, Chrome OS, Mac, and Windows 10. For a full overview of browser compatibility please see Web Bluetooth API Browser Compatibility

N.B. There are a number of caveats to be aware of with the web bluetooth API specification. Please refer to the Web Bluetooth W3C Draft Report for numerous caveats around device detection and connection.

N.B. This API is not available in Web Workers (not exposed via WorkerNavigator).

Demo

Your browser does not support the Bluetooth Web API

Not Connected

Usage Default

import { useBluetooth } from '@vueuse/core'

const {
  isSupported,
  isConnected,
  device,
  requestDevice,
  server,
} = useBluetooth({
  acceptAllDevices: true,
})
import { useBluetooth } from '@vueuse/core'

const {
  isSupported,
  isConnected,
  device,
  requestDevice,
  server,
} = useBluetooth({
  acceptAllDevices: true,
})
<template>
  <button @click="requestDevice()">
    Request Bluetooth Device
  </button>
</template>
<template>
  <button @click="requestDevice()">
    Request Bluetooth Device
  </button>
</template>

When the device has paired and is connected, you can then work with the server object as you wish.

Usage Battery Level Example

This sample illustrates the use of the Web Bluetooth API to read battery level and be notified of changes from a nearby Bluetooth Device advertising Battery information with Bluetooth Low Energy.

Here, we use the characteristicvaluechanged event listener to handle reading battery level characteristic value. This event listener will optionally handle upcoming notifications as well.

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)

const getBatteryLevels = async () => {
  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 a 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<undefined | number>()

const isGettingBatteryLevels = ref(false)

const getBatteryLevels = async () => {
  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 a event listener to handle updates:
  stop()
})
<template>
  <button @click="requestDevice()">
    Request Bluetooth Device
  </button>
</template>
<template>
  <button @click="requestDevice()">
    Request Bluetooth Device
  </button>
</template>

More samples can be found on Google Chrome's Web Bluetooth Samples.

Type Declarations

Show Type Declarations
/// <reference types="@types/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): {
  isSupported: boolean | undefined
  isConnected: ComputedRef<boolean>
  device: Ref<
    | {
        readonly id: string
        readonly name?: string | undefined
        readonly gatt?:
          | {
              readonly device: any
              readonly connected: boolean
              connect: () => Promise<BluetoothRemoteGATTServer>
              disconnect: () => void
              getPrimaryService: (
                service: BluetoothServiceUUID
              ) => Promise<BluetoothRemoteGATTService>
              getPrimaryServices: (
                service?: BluetoothServiceUUID | undefined
              ) => Promise<BluetoothRemoteGATTService[]>
            }
          | undefined
        readonly uuids?: string[] | undefined
        forget: () => Promise<void>
        watchAdvertisements: (
          options?: WatchAdvertisementsOptions | undefined
        ) => Promise<void>
        unwatchAdvertisements: () => void
        readonly watchingAdvertisements: boolean
        addEventListener: {
          (
            type: "gattserverdisconnected",
            listener: (this: BluetoothDevice, ev: Event) => any,
            useCapture?: boolean | undefined
          ): void
          (
            type: "advertisementreceived",
            listener: (
              this: BluetoothDevice,
              ev: BluetoothAdvertisingEvent
            ) => any,
            useCapture?: boolean | undefined
          ): void
          (
            type: string,
            listener: EventListenerOrEventListenerObject,
            useCapture?: boolean | undefined
          ): void
        }
        dispatchEvent: (event: Event) => boolean
        removeEventListener: (
          type: string,
          callback: EventListenerOrEventListenerObject | null,
          options?: boolean | EventListenerOptions | undefined
        ) => void
        onadvertisementreceived: (
          this: BluetoothDevice,
          ev: BluetoothAdvertisingEvent
        ) => any
        ongattserverdisconnected: (this: BluetoothDevice, ev: Event) => any
        oncharacteristicvaluechanged: (this: BluetoothDevice, ev: Event) => any
        onserviceadded: (this: BluetoothDevice, ev: Event) => any
        onservicechanged: (this: BluetoothDevice, ev: Event) => any
        onserviceremoved: (this: BluetoothDevice, ev: Event) => any
      }
    | undefined
  >
  requestDevice: () => Promise<void>
  server: Ref<BluetoothRemoteGATTServer | undefined>
  error: Ref<unknown>
}
/// <reference types="@types/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): {
  isSupported: boolean | undefined
  isConnected: ComputedRef<boolean>
  device: Ref<
    | {
        readonly id: string
        readonly name?: string | undefined
        readonly gatt?:
          | {
              readonly device: any
              readonly connected: boolean
              connect: () => Promise<BluetoothRemoteGATTServer>
              disconnect: () => void
              getPrimaryService: (
                service: BluetoothServiceUUID
              ) => Promise<BluetoothRemoteGATTService>
              getPrimaryServices: (
                service?: BluetoothServiceUUID | undefined
              ) => Promise<BluetoothRemoteGATTService[]>
            }
          | undefined
        readonly uuids?: string[] | undefined
        forget: () => Promise<void>
        watchAdvertisements: (
          options?: WatchAdvertisementsOptions | undefined
        ) => Promise<void>
        unwatchAdvertisements: () => void
        readonly watchingAdvertisements: boolean
        addEventListener: {
          (
            type: "gattserverdisconnected",
            listener: (this: BluetoothDevice, ev: Event) => any,
            useCapture?: boolean | undefined
          ): void
          (
            type: "advertisementreceived",
            listener: (
              this: BluetoothDevice,
              ev: BluetoothAdvertisingEvent
            ) => any,
            useCapture?: boolean | undefined
          ): void
          (
            type: string,
            listener: EventListenerOrEventListenerObject,
            useCapture?: boolean | undefined
          ): void
        }
        dispatchEvent: (event: Event) => boolean
        removeEventListener: (
          type: string,
          callback: EventListenerOrEventListenerObject | null,
          options?: boolean | EventListenerOptions | undefined
        ) => void
        onadvertisementreceived: (
          this: BluetoothDevice,
          ev: BluetoothAdvertisingEvent
        ) => any
        ongattserverdisconnected: (this: BluetoothDevice, ev: Event) => any
        oncharacteristicvaluechanged: (this: BluetoothDevice, ev: Event) => any
        onserviceadded: (this: BluetoothDevice, ev: Event) => any
        onservicechanged: (this: BluetoothDevice, ev: Event) => any
        onserviceremoved: (this: BluetoothDevice, ev: Event) => any
      }
    | undefined
  >
  requestDevice: () => Promise<void>
  server: Ref<BluetoothRemoteGATTServer | undefined>
  error: Ref<unknown>
}

Source

SourceDemoDocs

Contributors

Michael J. Roberts

Changelog

v8.7.4 on 6/18/2022
06230 - feat: new function (#1694)
useBluetooth has loaded