-
Notifications
You must be signed in to change notification settings - Fork 3
/
heartRate.js
55 lines (47 loc) · 1.71 KB
/
heartRate.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
var heartRate_Characteristic = null;
function heartRate_connect() {
let serviceUuid = "heart_rate";
let characteristicUuid = "heart_rate_measurement"
navigator.bluetooth.requestDevice
({
filters: [{ services: [serviceUuid] }]
//, optionalServices: [serviceUuid]
})
.then(device => { return device.gatt.connect(); })
.then(server => { return server.getPrimaryService(serviceUuid); })
.then(service => { return service.getCharacteristic(characteristicUuid); })
.then(characteristic => { // Save characteristic
heartRate_Characteristic = characteristic;
return characteristic;
})
.then(characteristic => { // Start notification
return heartRate_Characteristic.startNotifications()
.then(_ => {
heartRate_Characteristic.addEventListener(
'characteristicvaluechanged',
heartRate_read);
});
})
.catch(error => { // Handle Errors
log('Error! ' + error);
});
}
function heartRate_read(event) {
let value = event.target.value;
var bpm = value.getUint8(1);
setHeartRateValue(bpm);
log(bpm.toString().padStart(3) + '|' + '-'.repeat(bpm-40) + '>');
}
function heartRate_disconnect() {
if (heartRate_Characteristic) {
heartRate_Characteristic.stopNotifications()
.then(_ => {
heartRate_Characteristic.removeEventListener(
'characteristicvaluechanged',
heartRate_read);
})
.catch(error => {
log('Error! ' + error);
});
}
}