Skip to content

Commit

Permalink
Add boilerplate code for u2f
Browse files Browse the repository at this point in the history
  • Loading branch information
beaufortfrancois committed May 26, 2016
1 parent 4462ee6 commit 0f73ae8
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 0 deletions.
27 changes: 27 additions & 0 deletions web-bluetooth/u2f/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fido</title>
<link rel="icon" sizes="192x192" href="../favicon.png">
</head>
<body>
<button>Click</button>
<pre></pre>
<script src="u2f.js"></script>
<script>

document.querySelector('button').addEventListener('click', function() {
fido.request()
.then(_ => fido.connect())
.then(_ => fido.readBatteryLevel())
.then(value => {
document.querySelector('pre').textContent = 'Battery Level is ' + value.getUint8(0) + '%';
})
.catch(error => { console.log(error) });
});

</script>
</body>
</html>
50 changes: 50 additions & 0 deletions web-bluetooth/u2f/u2f.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
class Fido {

constructor() {
this.device = null;
this.onDisconnected = this.onDisconnected.bind(this);
}

request() {
let options = {
"filters": [{
"name": "U2F FT"
}],
"optionalServices": ["battery_service"]
};
return navigator.bluetooth.requestDevice(options)
.then(device => {
this.device = device;
this.device.addEventListener('gattserverdisconnected', this.onDisconnected);
return device;
});
}

connect() {
if (!this.device) {
return Promise.reject('Device is not connected.');
} else {
return this.device.gatt.connect();
}
}

readBatteryLevel() {
return this.device.gatt.getPrimaryService("battery_service")
.then(service => service.getCharacteristic("battery_level"))
.then(characteristic => characteristic.readValue());
}

disconnect() {
if (!this.device) {
return Promise.reject('Device is not connected.');
} else {
return this.device.gatt.disconnect();
}
}

onDisconnected() {
console.log('Device is disconnected.');
}
}

var fido = new Fido();

0 comments on commit 0f73ae8

Please sign in to comment.