-
Notifications
You must be signed in to change notification settings - Fork 0
/
bluetooth.html
87 lines (78 loc) · 2.22 KB
/
bluetooth.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Web Bluetooth demo</title>
</head>
<body>
<button id="go">Go Bluetooth</button>
<button >Go Bluetooth2</button>
<script>
class GenericDevice {
constructor() {
this.device = null;
this.onDisconnected = this.onDisconnected.bind(this);
}
request() {
let options = {
"filters": [{
"name": "foo"
}],
"optionalServices": ["device_information"]
};
return navigator.bluetooth.requestDevice(options)
.then(device => {
this.device = device;
this.device.addEventListener('gattserverdisconnected', this.onDisconnected);
});
}
connect() {
if (!this.device) {
return Promise.reject('Device is not connected.');
}
return this.device.gatt.connect();
}
readManufacturername() {
return this.device.gatt.getPrimaryService("device_information")
.then(service => service.getCharacteristic("manufacturer_name_string"))
.then(characteristic => characteristic.readValue());
}
disconnect() {
if (!this.device) {
return Promise.reject('Device is not connected.');
}
return this.device.gatt.disconnect();
}
onDisconnected() {
console.log('Device is disconnected.');
}
}
var genericDevice = new GenericDevice();
document.querySelector('button').addEventListener('click', event => {
genericDevice.request()
.then(_ => genericDevice.connect())
.then(_ => { /* Do something with genericDevice... */})
.catch(error => { console.log(error) });
});
document.querySelector('#go').onclick = (e) => {
e.preventDefault();
let options = {
acceptAllDevices: true
}
// Use the same service UUID as in mbed here!
navigator.bluetooth.requestDevice(options)
.then(device => {
console.log('Found device ' + device.name);
alert('Connected over GATT!' + device.name );
return device.connectGATT();
})
//.then( =>
// alert('Connected over GATT!');
//);
.catch(err => {
alert('ixi' + err + ' ' + JSON.stringify(err));
});
};
</script>
</body>
</html>