Web Bluetooth / Battery Level (Async Await) Sample

Available in Chrome 55+ | View on GitHub | Browse Samples

The Web Bluetooth API lets websites discover and communicate with devices over the Bluetooth 4 wireless standard using the Generic Attribute Profile (GATT). It is currently partially implemented in Android M, Chrome OS, Mac, and Windows 10.

This sample illustrates the use of the Web Bluetooth API to retrieve battery information from a nearby Bluetooth Device advertising Battery information with Bluetooth Low Energy. You may want to try this demo with the BLE Peripheral Simulator App from the Google Play Store and check out the Battery Level (Promises) sample.

Live Output


JavaScript Snippet

async function onButtonClick() {
  try {
    log('Requesting Bluetooth Device...');
    const device = await navigator.bluetooth.requestDevice({
        filters: [{services: ['battery_service']}]});

    log('Connecting to GATT Server...');
    const server = await device.gatt.connect();

    log('Getting Battery Service...');
    const service = await server.getPrimaryService('battery_service');

    log('Getting Battery Level Characteristic...');
    const characteristic = await service.getCharacteristic('battery_level');

    log('Reading Battery Level...');
    const value = await characteristic.readValue();

    log('> Battery Level is ' + value.getUint8(0) + '%');
  } catch(error) {
    log('Argh! ' + error);
  }
}