Web Bluetooth API
This feature is not (yet) supported on your device
The Web Bluetooth API enables apps to connect to Bluetooth Low Energy (BLE) devices and read values from or write
values to it.
To test, connect to a BLE device that advertises the "battery_service" service.
The easiest way is to download the
BLE Peripheral Simulator app on another Android device and start the Battery service. Then change
the battery level and tap the "Notify" button. This app will then show the current battery level of the BLE device.
Tap "Scan" below to start scanning for BLE devices.
Battery level:
if('bluetooth' in navigator) {
const scan = document.querySelector('#scan');
const batteryIndicator = document.querySelector('#battery-indicator');
scan.addEventListener('click', async () => {
const connectToDevice = async ({bleService, bleCharacteristic}) => {
try {
const device = await navigator.bluetooth.requestDevice({
filters: [{
services: [bleService]
}]
});
device.addEventListener('gattserverdisconnected', () => {
batteryIndicator.value = 0;
});
const server = await device.gatt.connect();
const service = await server.getPrimaryService(bleService);
const characteristic = await service.getCharacteristic(bleCharacteristic);
await characteristic.startNotifications();
characteristic.addEventListener('characteristicvaluechanged', e => {
const value = e.target.value.getUint8(0);
console.log(\`$\{bleCharacteristic\} changed\`, value);
batteryIndicator.value = value;
});
characteristic.readValue();
return characteristic;
}
catch(err) {
console.error(err);
}
};
await connectToDevice({bleService: 'battery_service', bleCharacteristic: 'battery_level'});
});
}