// Request access to Bluetooth devices
navigator.bluetooth
.requestDevice({
filters: [{ services: ["battery_service"] }],
})
.then((device) => {
// Connect to the selected device
return device.gatt.connect();
})
.then((server) => {
// Get the Battery Service
return server.getPrimaryService("battery_service");
})
.then((service) => {
// Get the Battery Level Characteristic
return service.getCharacteristic("battery_level");
})
.then((characteristic) => {
// Read the Battery Level
return characteristic.readValue();
})
.then((value) => {
// Convert the value to a number
const batteryLevel = value.getUint8(0);
console.log(`Battery Level: ${batteryLevel}%`);
});


article

Tagged: