Web Bluetooth API in React
npm install react-bluetooth
---
> WIP: This library is not ready for use in any projects
Tools to integrate the current web Bluetooth API spec in your React web applications.
The goal of this project is to create a unified API for working with Bluetooth across browser, iOS, Android, and PWAs.
References
- Interact with Bluetooth
- Bluetooth GATT spec
- Bluetooth
``sh`
yarn add react-bluetooth
Import the library into your JavaScript file:
`js`
import * as Bluetooth from 'react-bluetooth';
`ts`
requestDeviceAsync(
options: RequestDeviceOptions = { acceptAllDevices: true }
): Promise<{ type: 'cancel' } | { type: 'success'; device: BluetoothDevice }>
`ts
try {
const result = await Bluetooth.requestDeviceAsync();
if (result.type === 'cancel') {
return;
}
const device: BluetoothDevice = result.device;
} catch ({ message, code }) {
console.log('Error:', message, code);
}
`
`ts`
getAvailabilityAsync(): Promise
Returns a boolean that denotes bluetooth availability on the current device. This will also polyfill instances where navigator.bluetooth.getAvailability() is not supported.
`ts`
if (await Bluetooth.getAvailabilityAsync()) {
// Is Available
}
`ts`
getReferringDevice(): BluetoothDevice | undefined
`ts`
addPlatformHandler(eventName: BluetoothEvent, handler: PlatformHandler): Subscription
`ts`
const subscription = addPlatformHandler(BluetoothEvent.onServiceAdded, event => {
console.log('addPlatformHandler');
});
`ts`
addEventListener(
listener: EventListenerOrEventListenerObject,
useCapture?: boolean
): void
`ts`
dispatchEvent(event: Event): boolean
`ts`
removeEventListener(
callback: EventListenerOrEventListenerObject | null,
options?: EventListenerOptions | boolean
): void
Used with Bluetooth.setPlatformHandler.
`ts`
enum BluetoothEvent {
onAvailabilityChanged = 'onavailabilitychanged',
onGATTServerDisconnected = 'ongattserverdisconnected',
onCharacteristicValueChanged = 'oncharacteristicvaluechanged',
onServiceAdded = 'onserviceadded',
onServiceChanged = 'onservicechanged',
onServiceRemoved = 'onserviceremoved',
}
`tsError: Couldn't get any device
async function example_GetAnyDeviceAsync() {
const isAvailable = await Bluetooth.getAvailabilityAsync();
if (!isAvailable) {
return;
}
try {
const device = await Bluetooth.requestDeviceAsync();
console.log('Success: Got any device: ', device);
} catch (error) {
console.log(, error);Error: Couldn't get any device
console.error(, error);
}
}
async function example_GetBatteryLevelAsync() {
const isAvailable = await Bluetooth.getAvailabilityAsync();
if (!isAvailable) {
return;
}
const options = {
filters: [{ services: ['battery_service'] }],
};
try {
const result = await Bluetooth.requestDeviceAsync(options);
if (result.type === 'cancel') {
return;
}
const { device } = result;
console.log(Bluetooth: Got device:, device);Bluetooth: Got server:
if (device.gatt) {
const server = await device.gatt.connect();
console.log(, server);Bluetooth: Got service:
const service = await server.getPrimaryService('battery_service');
console.log(, service);Bluetooth: Got characteristic:
const characteristic = await service.getCharacteristic('battery_level');
console.log(, characteristic);Bluetooth: Got value:
const value = await characteristic.readValue();
console.log(, value);Success: Got battery:
const battery = value.getUint8(0);
console.log(, battery);Error: connected device did not have a GATT
} else {
// TODO: Bacon: Can we connect to the GATT or is that a no-op?
console.error();Error: Couldn't get battery level: ${message}
}
} catch ({ message }) {
console.error();``
}
}