bluetooth

Get Started with Bluetooth on the Web

Remarks#

Sources:

Read Battery Level from a nearby Bluetooth device (readValue)

function onButtonClick() {

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

Reset energy expended from a nearby Bluetooth Device (writeValue)

function onButtonClick() {
    
  navigator.bluetooth.requestDevice({filters: [{services: ['heart_rate']}]})
  .then(device => {
    // Connecting to GATT Server...
    return device.gatt.connect();
  })
  .then(server => {
    // Getting Heart Rate Service...
    return server.getPrimaryService('heart_rate');
  })
  .then(service => {
    // Getting Heart Rate Control Point Characteristic...
    return service.getCharacteristic('heart_rate_control_point');
  })
  .then(characteristic => {    
    // Writing 1 is the signal to reset energy expended.
    let resetEnergyExpended = new Uint8Array([1]);
    return characteristic.writeValue(resetEnergyExpended);
  })
  .then(_ => {
    console.log('> Energy expended has been reset.');
  })
  .catch(error => {
    console.log('Argh! ' + error);
  });
}

This modified text is an extract of the original Stack Overflow Documentation created by the contributors and released under CC BY-SA 3.0 This website is not affiliated with Stack Overflow