This repository has been archived by the owner on Apr 11, 2021. It is now read-only.
/
heart-rates.stream.js
82 lines (72 loc) · 2.08 KB
/
heart-rates.stream.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
$(function() {
const totalPoints = 120;
const updateInterval = 1000;
const buildEventUrl = (userId) => '/users/' + userId + '/heart-rates/stream';
// GLOBAL VARIABLES :scream: --------------------------------------------------------------------
let data = [];
let heartRate = null;
// PLOT -----------------------------------------------------------------------------------------
const buildData = () => {
if (data.length > 0) {
data = data.slice(1);
}
if (heartRate && !isNaN(heartRate.value)) {
data.push(heartRate.value);
}
while (data.length < totalPoints) {
data.push(0);
}
let res = [];
for (let i = 0; i < data.length; ++i) {
res.push([i, data[i]])
}
return res;
}
let plot = $.plot('.heart-rate-placeholder', [ buildData() ], {
series: {
shadowSize: 0 // Drawing is faster without shadows
},
yaxis: {
min: 0,
max: 250
},
xaxis: {
show: false
}
});
// EVENT SOURCE ---------------------------------------------------------------------------------
const getUserId = () => {
let urlParams = new URLSearchParams(window.location.search);
let userId = urlParams.get('userId');
if (!userId) {
userId = 1;
}
return userId;
};
const userId = getUserId();
$('.title').text(`Heart rates for user ${userId}`);
let source = new EventSource(buildEventUrl(userId));
source.addEventListener('message', (event) => {
heartRate = JSON.parse(event.data);
console.info('read heart rate', heartRate);
});
source.onerror = () => {
source.close();
};
// INIT -----------------------------------------------------------------------------------------
const update = () => {
plot.setData([buildData()]);
plot.draw();
setTimeout(update, updateInterval);
};
const stop = () => {
console.info('Stopping event...');
source.close();
};
// START ----------------------------------------------------------------------------------------
plot.setupGrid();
update();
window.onbeforeunload = () => {
stop();
};
});