Web Bluetooth / Battery Level Sample

Available in Chrome 45+ | 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, Linux, and Mac.

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 (Async Await) sample.

Live Output


JavaScript Snippet

function onButtonClick() {
  log('Requesting Bluetooth Device...');
  navigator.bluetooth.requestDevice(
    {filters: [{services: ['battery_service']}]})
  .then(device => {
    log('Connecting to GATT Server...');
    return device.gatt.connect();
  })
  .then(server => {
    log('Getting Battery Service...');
    return server.getPrimaryService('battery_service');
  })
  .then(service => {
    log('Getting Battery Level Characteristic...');
    return service.getCharacteristic('battery_level');
  })
  .then(characteristic => {
    log('Reading Battery Level...');
    return characteristic.readValue();
  })
  .then(value => {
    let batteryLevel = value.getUint8(0);
    log('> Battery Level is ' + batteryLevel + '%');
  })
  .catch(error => {
    log('Argh! ' + error);
  });
}