-
Notifications
You must be signed in to change notification settings - Fork 0
/
ble.js
63 lines (58 loc) · 1.62 KB
/
ble.js
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
/*
A minimal Web Bluetooth connection example
created 6 Aug 2018
by Tom Igoe
*/
var myDevice;
var myService = 0xffb0; // fill in a service you're looking for here
var myCharacteristic = 0xffb2; // fill in a characteristic from the service here
function connect(){
navigator.bluetooth.requestDevice({
// filters: [myFilters] // you can't use filters and acceptAllDevices together
optionalServices: [myService],
acceptAllDevices: true
})
.then(function(device) {
// save the device returned so you can disconnect later:
myDevice = device;
console.log(device);
// connect to the device once you find it:
return device.gatt.connect();
})
.then(function(server) {
// get the primary service:
return server.getPrimaryService(myService);
})
.then(function(service) {
// get the characteristic:
return service.getCharacteristics();
})
.then(function(characteristics) {
// subscribe to the characteristic:
for (c in characteristics) {
characteristics[c].startNotifications()
.then(subscribeToChanges);
}
})
.catch(function(error) {
// catch any errors:
console.error('Connection failed!', error);
});
}
// subscribe to changes from the meter:
function subscribeToChanges(characteristic) {
characteristic.oncharacteristicvaluechanged = handleData;
}
// handle incoming data:
function handleData(event) {
// get the data buffer from the meter:
var buf = new Uint8Array(event.target.value);
console.log(buf);
}
// disconnect function:
function disconnect() {
if (myDevice) {
// disconnect:
myDevice.gatt.disconnect();
}
}