react-web-bluetooth
v1.0.0
Published
React hooks wrapper for the Web Bluetooth API
Downloads
159
Readme
React Hooks for Web Bluetooth
This is a package that provides a hooks wrapper around the new Web Bluetooth API
It is an experimental feature implemented under a flag in Chrome. In order to use this feature in Chrome, enable:
chrome://flags/#enable-experimental-web-platform-features
The getDevices
method requires also to enable the new permissions backend experimental feature.
chrome://flags/#enable-web-bluetooth-new-permissions-backend
getDevices
is used to retrieve already paired Bluetooth devices from the browser, for example after a refresh instead of pairing a device again getDevices
can be used to connect to it without pairing.
Example
const { onClick, device } = useRequestDevice({
acceptAllDevices: true,
});
// ...
return <>
{!device && <button onClick={onClick}>Connect</button>}
{device && <span>{device.name}</span>}
</>
API
useGetServer
Params:
device
: BluetoothDevice
Returns:
server
: BluetoothRemoteGATTServer
useGetCharacteristic
Params:
service
: BluetoothRemoteGATTService
bluetoothCharacteristicUUID
: string
Returns:
characteristic
: BluetoothRemoteGATTCharacteristic
useGetDevices
Returns: devices[]
: BluetoothDevice[]
useRequestDevice
Params:
options
: https://developer.mozilla.org/en-US/docs/Web/API/Bluetooth/requestDevice#parameters
Returns:
onClick
: (event) => void // returns a onClick function that can be used to trigget the browser's pairing window and list the scanned Bluetooth devices.
device
: BluetoothDevice // returns a device chosen from the Bluetooth pairing dialogue.
useGetPrimaryService
Params:
device
: BluetoothDevice
Returns:
service
: BluetoothRemoteGATTService
useReadValue
Params:
characteristic
: BluetoothRemoteGATTCharacteristic
Returns::
value
: DataView
writeValue
Params:
characteristic
: BluetoothRemoteGATTCharacteristic
value
: ArrayBuffer