Bluetooth
The Web Bluetooth API is a low-level API allowing Web applications to pair with the nearby Bluetooth Low Energy-enabled peripheral devices and access their services exposed.
API glimpse
navigator.bluetooth.requestDevice(serviceFilters)
- Scans for the device in range supporting the requested services. Returns a
Promise
. device.gatt.connect()
- Returns a
Promise
resolved with the server object providing access to the services available on the device. server.getPrimaryService(name)
- Returns a
Promise
resolved with the particular Bluetooth service on the device. service.getCharacteristic(name)
- Returns a
Promise
resolved with the GATT characteristic object. characteristic.readValue()
- Returns a
Promise
resolved with a raw value from the GATT characteristic. characteristic.writeValue(value)
- Writes a new value for the GATT characteristic.
Live Demo
Based on code snippets from Google Developers.
-
function readBatteryLevel() { var $target = document.getElementById('target'); if (!('bluetooth' in navigator)) { $target.innerText = 'Bluetooth API not supported.'; return; } navigator.bluetooth.requestDevice({ filters: [{ services: ['battery_service'] }] }) .then(function (device) { return device.gatt.connect(); }) .then(function (server) { return server.getPrimaryService('battery_service'); }) .then(function (service) { return service.getCharacteristic('battery_level'); }) .then(function (characteristic) { return characteristic.readValue(); }) .then(function (value) { $target.innerHTML = 'Battery percentage is <b>' + value.getUint8(0) + '</b>.'; }) .catch(function (error) { $target.innerText = error; }); }
-
<p> <button onclick="readBatteryLevel()">Read Bluetooth device's<br>battery level</button> </p> <p id="target"></p> <p><small>Based on code snippets from <a href="https://developers.google.com/web/updates/2015/07/interact-with-ble-devices-on-the-web" target="_blank" rel="noopener">Google Developers</a>.</small></p>