forked from gfwilliams/HeartRate
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index2.html
266 lines (232 loc) · 8.26 KB
/
index2.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
<html>
<head>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-LCRH415DPW"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-LCRH415DPW');
</script>
<!---G tracking-->
<!-- 2016 Gordon Williams, [email protected]
Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/
-->
<meta charset="utf-8">
<meta name="viewport" content="width=320, initial-scale=1">
<title>Vedic Heart</title>
</head>
<body>
<p>Allow, this website to use your webcam, then place your finger lightly over the camera and wait for the trace to stabilise.</p>
<p>Put the tip of a finger carefully on the camera lens.Ensure that the camera image turns <b style="color:red;">red</b> </p>
<p>You will have most success when there is light behind your finger. Hence we will attempt to turn on flashlight on your device . It can get hot please <b>do not burn</b> yourself!! This website works best on Chrome </p>
<video id="v" width="100" height="100" muted></video> <!--style="display:none" for hiding video -->
<canvas id="c" width="100" height="100" style="display:none"></canvas><!--for drawing video on canvas-->
<canvas id="g" width="320" height="30"></canvas><br/>
<div id="bpm">--</div>
<div id="time_left"></div>
<div id="avg_bright"></div>
<form id="mainform" action="https://vedicheart.pythonanywhere.com/ml/" method="post">
<input type="text" id="hdata" name="hdata" value="None" hidden ><br><br>
<input type="button" id="start_btn" value="Start" onclick="startReading()">
<br>Set Measurement timer for <br>
<!-- 1 <input type="radio" checked onclick="set_maxtimer(1);" name="timer" value="1">-->
2 <input type="radio" onclick="set_maxtimer(2);" name="timer" checked value="2">
<!-- 5 <input type="radio" onclick="set_maxtimer(5);" name="timer" value="5"> -->
</form>
<p> Please maintain a calm posture and <b>do not move</b></p>
<!--input type="button" value="flip camera" id="flip-button"/-->
<script>
var start_timer=null;
var maxtimer=2*60000
var video, width,stopped, height, context, graphCanvas, graphContext, bpm,track,torchMaxRetry;
var torchMaxRetry=5;
var hist = [];// older way of storing data [{bright:64,time:200},{bright:68,time:202},...]
var stopped=false;
var heartData={bright:[],time:[]};// new way of storing data {bright:[64,68,..],time:[200,202,..]}
navigator.getUserMedia = ( navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
////https://stackoverflow.com/a/28991938
var constraints = { audio:false, video: { facingMode:"environment"} };
function set_maxtimer(x){
maxtimer=x*60000// in milliseconds
}
function startReading(){
// Get the webcam's stream.// request user permission
navigator.getUserMedia(constraints, startStream, function () {alert("camera permission is required for detecting heart rate "); });
return false;
}
function reset(){
hist = [];
heartData={bright:[],time:[]};
timer_start();
}
function timer_start()
{
start_timer=Date.now();
}
function submitData()
{
stop_reading();
document.getElementById("hdata").value=JSON.stringify(heartData);
document.getElementById("mainform").submit();
}
function stop_reading()
{
stopped=true;
video.pause();
bpm.innerHTML="Sending reading ... please stay on the page ";
}
function initialize() {
navigator.mediaDevices.enumerateDevices().then(function(devices) {
devices.forEach(function(device) {
console.log(device.kind + ": " + device.label +
" id = " + device.deviceId/*, JSON.stringify(device,null,2)*/);
if (device.kind=="videoinput" /*&& constraints.video===true*/)
constraints.video = { optional: [{sourceId: device.deviceId}, { fillLightMode: "on" }] };
});
initialize2();
}).catch(function(err) {
console.log(err.name + ": " + err.message);
});
}
function initialize2() {
// The source video.
video = document.getElementById("v");
width = video.width;
height = video.height;
// The target canvas.
var canvas = document.getElementById("c");
context = canvas.getContext("2d");
// The canvas for the graph
graphCanvas = document.getElementById("g");
graphContext = graphCanvas.getContext("2d");
// The bpm meter
bpm = document.getElementById("bpm");
}
function startStream(stream) {
document.getElementById("start_btn").style.visibility = 'hidden';
video.srcObject = stream;
track = stream.getVideoTracks()[0];
video.play();
setTimeout(function(){
track.applyConstraints({advanced: [{torch: true}]})
//alert('Turning on flashlight , if present ');
}, 800);
timer_start();
// Ready! Let's start drawing.
requestAnimationFrame(draw);
}
function draw() {
var frame = readFrame();
if (frame) {
store_and_draw(frame.data);
}
// Wait for the next frame.
requestAnimationFrame(draw);
}
function readFrame() {
try {
context.drawImage(video, 0, 0, width, height);
} catch (e) {
// The video may not be ready, yet.
return null;
}
if(torchMaxRetry!=0){
track.applyConstraints({advanced: [{torch: true}]});
torchMaxRetry=torchMaxRetry-1;
}
return context.getImageData(0, 0, width, height);
}
function store_and_draw(data) {
var len = data.length;
var sum = 0;
if(stopped)//if stoppped then do not compute
return
for (var i = 0, j = 0; j < len; i++, j += 4) {
sum += data[j] + data[j+1] + data[j+2]; // rgba
}
document.getElementById("avg_bright").innerHTML="AVG BRIGHTNESS IS "+(sum/len).toFixed(2);
//store brightness and time
hist.push({ bright : sum/len, time : Date.now() });
heartData['bright'].push(sum/len);
heartData['time'].push(Date.now());
if(Date.now()-start_timer>maxtimer)
{
// if timeout then submit data
submitData();
return
}
// else display time left
document.getElementById("time_left").innerHTML="Time left "+((maxtimer-(Date.now()-start_timer))/60000).toFixed(2)+' Minutes'
//detect impulse
try{
if( (Math.max(...heartData['bright'].slice(-300))-Math.min(...heartData['bright'].slice(-300)))>20)
{
// if in last 300 values => max-min>20 then impulse present
reset();
console.log("reset");
return ;
}
}
catch (e){}
/////////// below code to display graph
while (hist.length>graphCanvas.width) hist.shift();
// max and min
var max = hist[0].bright;
var min = hist[0].bright;
hist.forEach(function(v) {
if (v.bright>max) max=v.bright;
if (v.bright<min) min=v.bright;
});
// thresholds for bpm
var lo = min*0.6 + max*0.4;
var hi = min*0.4 + max*0.6;
var pulseAvr = 0, pulseCnt = 0;
// draw
var ctx = graphContext;
ctx.clearRect(0, 0, graphCanvas.width, graphCanvas.height);
ctx.beginPath();
ctx.moveTo(0,0);
hist.forEach(function(v,x) {
var y = graphCanvas.height*(v.bright-min)/(max-min);
ctx.lineTo(x,y);
});
ctx.stroke();
// work out bpm
var isHi = undefined;
var lastHi = undefined;
var lastLo = undefined;
ctx.fillStyle = "red";
hist.forEach(function(v, x) {
if (isHi!=true && v.bright>hi) {
isHi = true;
lastLo = x;
}
if (isHi!=false && v.bright<lo) {
if (lastHi !== undefined && lastLo !== undefined) {
pulseAvr += hist[x].time-hist[lastHi].time;
pulseCnt++;
ctx.fillRect(lastLo,graphCanvas.height-4,lastHi-lastLo,4);
}
isHi = false;
lastHi = x;
}
});
// write bpm
if (pulseCnt) {
var pulseRate = 60000 / (pulseAvr / pulseCnt);
bpm.innerHTML = pulseRate.toFixed(0)+" BPM ("+pulseCnt+" pulses)";
} else {
bpm.innerHTML = "-- BPM";
}
}
addEventListener("DOMContentLoaded", initialize);
</script>
<h3>Disclaimer</h3>
This is an app which tries to determine your heart rate as best as it can, but it's not medical equipment.<br> Do not base any medical decisions solely on the results of this app.<br>Please contact a doctor when you are in need of medical advice or in an emergency .<br>
</body>
</html>