Web Bluetooth / Battery Level Sample

Available in Chrome 45+ | View Source | View on GitHub | Browse Samples

The Web Bluetooth API discovers and communicates with devices over the Bluetooth 4 wireless standard using the Generic Attribute Profile (GATT). It is currently only partially implemented in Chrome OS and Android M behind the experimental flag chrome://flags/#enable-web-bluetooth. Check out all Web Bluetooth Samples.

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.

Live Output


JavaScript Snippet

function onButtonClick() {
  'use strict';

  log('Requesting Bluetooth Device...');
  navigator.bluetooth.requestDevice(
    {filters: [{services: ['battery_service']}]})
  .then(device => {
    log('> Found ' + device.name);
    log('Connecting to GATT Server...');
    return device.connectGATT();
  })
  .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(buffer => {
    let data = new DataView(buffer);
    let batteryLevel = data.getUint8(0);
    log('> Battery Level is ' + batteryLevel + '%');
  })
  .catch(error => {
    log('Argh! ' + error);
  });
}