I'd like to read the battery level of the connected Bluetooth devices. I found this web API and almost have it running. It asks permission to access bluetooth, but then gives an error when connecting to the API I think.
Here's the Google Web Bluetooth API: https://googlechrome.github.io/samples/web-bluetooth/battery-level.html
Here's the first error: Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules
My javascript code:
const button = document.getElementById("getDetails");
const details = document.getElementById("details");
button.addEventListener("click", async () => {
try {
// Request the Bluetooth device through the browser
const device = await navigator.bluetooth.requestDevice({
optionalServices: ["battery_service", "device_information"],
acceptAllDevices: true,
});
// Connect to the GATT server and get the name of the Bluetooth device
const server = await device.gatt.connect();
let deviceName = device.gatt.device.name;
// Getting the services we mentioned before through GATT server
const batteryService = await server.getPrimaryService("battery_service");
const infoService = await server.getPrimaryService("device_information");
// Getting the current battery level
const batteryLevelCharacteristic = await batteryService.getCharacteristic(
"battery_level"
);
// Convert received buffer to number
const batteryLevelValue = await batteryLevelCharacteristic.readValue();
const batteryPercent = batteryLevelValue.getUint8(0);
// Getting device information
// We will get all characteristics from device_information
const infoCharacteristics = await infoService.getCharacteristics();
// Store promises in an array for parallel execution
const infoPromises = infoCharacteristics.map(async (characteristic) => {
// Returns a buffer
const value = await characteristic.readValue();
// Convert the buffer to string
return new TextDecoder().decode(value);
});
// Await all promises to resolve
const infoValues = await Promise.all(infoPromises);
console.log(infoValues);
// Display all the information on the screen
// use innerHTML
details.innerHTML = `
Device Name - ${deviceName}<br />
Battery Level - ${batteryPercent}%<br />
Device Information:
<ul>
${infoValues.map((value) => `<li>${value}</li>`).join("")}
</ul>
`;
} catch (err) {
console.error(err);
alert("An error occurred while fetching device details");
}
});
I tried applying this stack overflow answer, but have been unsuccessful.