-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
624 lines (514 loc) · 22.8 KB
/
index.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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="import" href="import.html">
</head>
<body>
<script>
var DEBUG = false; // enable this will just display random data
var COL_NUM = 2; // config cols
var chartLoaded = false;
var data_array = [];
var chart_map = {};
var calibrate_low_buffer = []; // buffer for textarea in low standard
var calibrate_high_buffer = []; // buffer for textarea in high standard
var calibrating_sensor_id = ''; // storate which sensor is calibrating
var calibrate_buffer = {};
var CalibrateStateEnum = {
None: 1,
Low: 2,
High: 3,
};
var socket;
var calibrate_state = CalibrateStateEnum.None; // init calibrate state
Chart.defaults.global.legend.display = false; // disable the title
// dynamicly compose the grid / cell / chart unit
function composeGrid(num) {
var cols = COL_NUM;
var total_width = 12;
var width = total_width / cols;
// document.write("<div class='container'>");
var container_div = document.createElement("div");
container_div.setAttribute("class", "container");
for (var i = 0; i < Math.ceil(num / cols); i++) {
// document.write("<div class='row'>");
var row_div = document.createElement("div");
row_div.setAttribute("class", "row");
var jn;
if (i != Math.ceil(num / cols) - 1) {
jn = cols;
} else {
jn = num % cols == 0 ? cols : num % cols;
}
for (var j = 0; j < jn; j++) {
var index = i * cols + j;
var cell = composeCell(index);
// document.write("<div class='col-sm-" + width + "'>" + cell + "</div>");
var col_div = document.createElement("div");
col_div.setAttribute("class", "col-sm-" + width);
// var canvas_div = document.createElement("canvas");
// canvas_div.setAttribute("id", data_array[index]["sensor_id"]);
var canvas_div = composeCell(index);
col_div.appendChild(canvas_div);
var buttons_div = composeButtons(index);
// col_div.appendChild(buttons_div);
var calibrate_btn_div = composeCalibrateButton(index);
col_div.appendChild(calibrate_btn_div);
row_div.appendChild(col_div);
}
// document.write("</div>");
container_div.appendChild(row_div);
}
// document.write("</div>");
var body_DOM = document.getElementsByTagName("BODY")[0];
body_DOM.appendChild(container_div);
}
// create the DOM unit for canvas
function composeCell(index) {
var canvas_div = document.createElement("canvas");
var sensor_id = data_array[index]["sensor_id"];
canvas_div.setAttribute("id", sensor_id);
return canvas_div;
}
// create the DOM unit for button
function composeButtons(index) {
var button_group = document.createElement("div");
button_group.setAttribute("class", "btn-group");
button_group.setAttribute("role", "group");
var btn1 = document.createElement("button");
btn1.setAttribute("type", "button");
btn1.setAttribute("class", "btn btn-default");
btn1.innerText = "12 Hours";
var btn2 = document.createElement("button");
btn2.setAttribute("type", "button");
btn2.setAttribute("class", "btn btn-default");
btn2.innerText = "30 Minutes";
var btn3 = document.createElement("button");
btn3.setAttribute("type", "button");
btn3.setAttribute("class", "btn btn-default");
btn3.innerText = "20 Seconds";
button_group.appendChild(btn1);
button_group.appendChild(btn2);
button_group.appendChild(btn3);
return button_group;
}
// create the DOM unti for calibrate button
function composeCalibrateButton(index) {
var sensor_id = data_array[index]["sensor_id"];
var btn = document.createElement("button");
btn.setAttribute("type", "button");
btn.setAttribute("class", "btn btn-success pull-right");
btn.setAttribute("data-toggle", "modal");
btn.setAttribute("data-target", "#calibrate_modal");
btn.innerText = "Calibrate";
btn.setAttribute("sensor_id", sensor_id);
// btn.addEventListener("click", function(e) {
// var sensor_id = data_array[index]["sensor_id"];
// // console.log("calibrate " + sensor_id);
// calibrating_sensor_id = sensor_id;
//
// $("#calibrate_modal").modal("show");
// });
return btn;
}
function presentCalibrateModelView() {
}
// start to init the socket connection when the whole window has loaded
window.onload = initSocketConnect;
// document.ready = initSocketConnect;
// init the socket connection
function initSocketConnect() {
socket = io.connect(domain);
// receive the Event "update_frontend" fron the back-end server
socket.on("update_frontend", function(data_map) {
data_array.length = 0;
// put all the sensor data to a array
for (var sensor_id in data_map) {
data_array.push(data_map[sensor_id]);
}
// the order may different at every time the front-end receive the data
// in order to make the front-end sensor chart looks the same
// we always sort the array by the sensor id
data_array.sort(function(data1, data2) {
return data1.sensor_id.localeCompare(data2.sensor_id);
});
if (!chartLoaded) {
var sensor_num = data_array.length;
composeGrid(sensor_num);
initChart(data_array);
chartLoaded = true;
}
updateChart();
// console.log(data_array);
updateCalibrateView();
});
}
// init the chart for diaplay data
function initChart(data_array) {
var chart_num = data_array.length;
// var chart_num = 8;
for (var i = 0; i < chart_num; i++) {
var data_map = data_array[i];
var sensor_id = data_map["sensor_id"];
// we have a pre-defined color pool
var color = getColor(i);
// var chartdata = [{ x: 1, y: 0 }, { x: 2, y: 0 }, { x: 3, y: 0 }, { x: 4, y: 0 }];
var chartdata = [];
// this is the chart data format
var data = {
datasets: [{
label: sensor_id,
data: chartdata,
backgroundColor: [
// 'rgb(27, 201, 142)',
color,
],
borderColor: [
// 'rgb(27, 201, 142)',
color,
],
fill: false,
steppedLine : false,
}]
};
// this is the chart configuration format
var chart_option =
{
scales : {
xAxes : [{
display : true,
// type : 'linear',
type : 'time',
distribution: 'linear',//series
time : {
displayFormats: {
second: 'h:mm:ss'
},
unit: 'second',
}}]
},
title : {
display : true,
text : 'Title',
fontColor : color,
fontSize : 20,
},
// elements: {
// line: {
// tension: 0, // disables bezier curves
// }
// },
};
// get the contex
var ctx = document.getElementById(sensor_id).getContext('2d');
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: chart_option,
});
chart_map[sensor_id] = chart;
}
};
// update the chart when the front-end receive new sensor data from back-end
function updateChart() {
data_array.forEach(function(data_map, index) {
var sensor_id = data_map["sensor_id"];
if (chart_map.hasOwnProperty(sensor_id))
{
var chart = chart_map[sensor_id];
var data = data_map["sensor_data"];
// if DEBUG is enable, will generate some random data
if (DEBUG)
{
data = getRandomInt(50, 100); // DEBUG
}
var unit = data_map["unit"];
var date = data_map["received_date"];
var label = sensor_id + " : " + data + " " + unit;
var chartdata = chart.data.datasets[0].data;
// we need to shift the data in the chart to make it not too squeezed
if (chartdata.length >= 20) {
chartdata.shift();
}
//var last_coordinate = chartdata[chartdata.length - 1];
//var last_x = last_coordinate["x"];
//var x = last_x + 1;
// chartdata = [{ x: 1, y: 0 }, { x: 2, y: 0 }, { x: 3, y: 0 }, { x: 4, y: 0 }];
// add the new data to the array
chartdata.push({
"x": date,
"y": data
});
// chart.data.datasets[0].data = chartdata;
chart.data.datasets[0].label = label;
chart.options.title.text = label;
// update the data
chart.update();
console.log(data_map);
}
});
}
// display the new data into the textarea when calibrating
function updateCalibrateView()
{
if (calibrate_state == CalibrateStateEnum.None) return;
data_array.forEach(function(data_map, index) {
var sensor_id = data_map["sensor_id"];
if (sensor_id == calibrating_sensor_id)
{
if (sensor_id == calibrating_sensor_id)
var data = data_map["sensor_data"];
var unit = data_map["unit"];
var date = data_map["received_date"];
var voltage = data_map["sensor_voltage"];
var label = voltage + ' mV';
var textarea;
if (calibrate_state == CalibrateStateEnum.Low)
{
textarea = document.getElementById('calibrate_low_textarea');
calibrate_low_buffer.push(voltage);
textarea.value = textarea.value == '' ? label : textarea.value + '\n' + label;
$('#calibrate_low_textarea').animate({scrollTop: $('#calibrate_low_textarea').prop("scrollHeight")}, 500);
}
else if (calibrate_state == CalibrateStateEnum.High)
{
textarea = document.getElementById('calibrate_high_textarea');
calibrate_high_buffer.push(voltage);
textarea.value = textarea.value == '' ? label : textarea.value + '\n' + label;
$('#calibrate_high_textarea').animate({scrollTop: $('#calibrate_high_textarea').prop("scrollHeight")}, 500);
}
// textarea.scrollTop = textarea.scrollHeight;
// $('calibrate_low_textarea').val(label);
// textarea.append(label).animate({scrollTop: textarea.prop("scrollHeight")}, 500);
console.log(data_map);
}
});
}
// get the color from the pre-defined color pool
function getColor(index)
{
var colorPool = ['rgb(27, 201, 142)', 'rgb(230, 71, 89)', 'rgb(159, 134, 255)', 'rgb(228, 216, 54)'];
return colorPool[index % colorPool.length];
}
// I have tried, the random color is ugly
function getRandomColor()
{
return "rgb(" + getRandomInt(0, 255) + "," + getRandomInt(0, 255) + "," + getRandomInt(0, 255) + ")";
}
function getRandomInt(min, max)
{
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
// callback when the calibrate model window start to show
$(document).on('show.bs.modal','#calibrate_modal', function (e) {
var button = e.relatedTarget;
var sensor_id = button.getAttribute("sensor_id");
calibrating_sensor_id = sensor_id;
var title = sensor_id + ' Calibration';
$('#calibrate_modal_label').text(title);
calibrateViewWillShow();
});
// callback when the calibrate model window finish to hide
$(document).on('hide.bs.modal','#calibrate_modal', function (e) {
calibrating_sensor_id = '';
calibrateViewDidHide()
refresh_config();
});
function refresh_config()
{
}
// clean up the calibrate window before it show up
function calibrateViewWillShow()
{
$('#calibrate_low_textarea').val('');
$('#calibrate_high_textarea').val('');
$('#calibrate_low_concentration').val('');
$('#calibrate_high_concentration').val('');
$('#calibrate_step3_label').text('');
$('#calibrate_step1_mark').hide();
$('#calibrate_step2_mark').hide();
$('#calibrate_step3_mark').hide();
}
// clean up the calibrate window after it hide
function calibrateViewDidHide()
{
calibrate_low_buffer.length = 0;
calibrate_low_buffer.length = 0;
}
// callback after the calibrate_low_start_button is clicked
$(document).on('click', '#calibrate_low_start_button', function (e) {
console.log('calibrate_low_start_button');
calibrate_state = CalibrateStateEnum.Low;
})
// callback after the calibrate_low_stop_button is clicked
$(document).on('click', '#calibrate_low_stop_button', function (e) {
console.log('calibrate_low_stop_button');
calibrate_state = CalibrateStateEnum.None;
$('#calibrate_step1_mark').show();
})
// callback after the calibrate_high_start_button is clicked
$(document).on('click', '#calibrate_high_start_button', function (e) {
console.log('calibrate_high_start_button');
calibrate_state = CalibrateStateEnum.High;
})
// callback after the calibrate_high_stop_button is clicked
$(document).on('click', '#calibrate_high_stop_button', function (e) {
console.log('calibrate_low_stop_button');
calibrate_state = CalibrateStateEnum.None;
$('#calibrate_step2_mark').show();
})
// callback after the calculate_parameters_button is clicked
$(document).on('click', '#calculate_parameters_button', function (e) {
console.log('calculate_parameters_button');
console.log(calibrate_low_buffer);
console.log(calibrate_high_buffer);
var input_text1 = $('#calibrate_low_concentration');
var input_text2 = $('#calibrate_high_concentration');
var low_concentration = parseFloat($('#calibrate_low_concentration').val());
var high_concentration = parseFloat($('#calibrate_high_concentration').val());
var x1 = Math.log(low_concentration);
var x2 = Math.log(high_concentration);
// get the average of received data to reduce the mistakes
var y1 = getMean(calibrate_low_buffer);
var y2 = getMean(calibrate_high_buffer)
var p1 = [x1, y1];
var p2 = [x2, y2];
console.log(p1);
console.log(p2);
// find the linear releation of the two points
var equation = linearFit(x1, y1, x2, y2);
var k = equation[0].toFixed(2);
var b = equation[1].toFixed(2);
console.log(k);
console.log(b);
// var label = 'Slope : ' + k + ' Intercept : ' + b;
var label = 'E = ' + b + ' + ' + k + '(lnC)';
if (b != 'NaN' && k != 'NaN')
{
$('#calibrate_step3_mark').show();
$('#calibrate_step3_label').text(label);
calibrate_buffer = {
'sensor_id' : calibrating_sensor_id,
'm' : k,
'Eo' : b,
};
}
})
// find the linear releation of the two points
function linearFit(x1, y1, x2, y2)
{
var k, b;
if (x1 == x2)
{
k = Infinity;
}
else
{
k = (y1 - y2) / (x1 - x2);
}
b = y1 - k * x1;
return [k, b];
}
// callback after the calibrate_cancel_button is clicked
$(document).on('click', '#calibrate_cancel_button', function (e) {
console.log('calibrate_cancel_button');
clearMap(calibrate_buffer);
})
// callback after the calibrate_done_button is clicked
$(document).on('click', '#calibrate_done_button', function (e) {
console.log('calibrate_done_button');
if (validateData(calibrate_buffer))
{
socket.emit('calibrate', calibrate_buffer);
}
clearMap(calibrate_buffer);
})
// alway remember to validate the data
function validateData(arr)
{
if (!arr.hasOwnProperty('sensor_id') || !arr.hasOwnProperty('Eo') || !arr.hasOwnProperty('m'))
{
return false;
}
else if (arr['Eo'] == NaN || arr['m'] == NaN)
{
return false;
}
return true;
}
function clearMap(map)
{
for (var key in map)
{
delete map[key];
}
}
function getMean(arr)
{
if (arr.length == 0) return 0;
var sum = 0;
for (var i = 0, len = arr.length; i < len; i++) {
sum += parseFloat(arr[i]);
}
return sum / arr.length;
}
</script>
<!-- Calibrate Modal Window -->
<div class="modal fade" id="calibrate_modal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title" id="calibrate_modal_label" align="center">Calibration</h3>
</div>
<div class="modal-body">
<div class='calibrate_row'>
<H4>Step 1 : Low Standard Calibration Point</H4>
<img id='calibrate_step1_mark' class='calibrate_mark' src='images/green_mark.jpg'>
</div>
<div class='calibrate_row'>
<input id='calibrate_low_concentration' type="text" class="form-control" style="width:40%; display:inline;">
<H4>mg / L</H4>
<button id='calibrate_low_start_button' type="button" class="btn btn-info">Start Sampling</button>
<button id='calibrate_low_stop_button' type="button" class="btn btn-danger">Stop Sampling</button>
</div>
<div>
<textarea id='calibrate_low_textarea' rows="3" cols="70" style="width:100%; margin-top:5px;"></textarea>
</div>
<div class='calibrate_row'>
<H4>Step 2 : High Standard Calibration Point</H4>
<img id='calibrate_step2_mark' class='calibrate_mark' src='images/green_mark.jpg'>
</div>
<div class='calibrate_row'>
<input id='calibrate_high_concentration' type="text" class="form-control" style="width:40%; display:inline;">
<H4>mg / L</H4>
<button id='calibrate_high_start_button' type="button" class="btn btn-info">Start Sampling</button>
<button id='calibrate_high_stop_button' type="button" class="btn btn-danger">Stop Sampling</button>
</div>
<div>
<textarea id='calibrate_high_textarea' rows="3" cols="70" style="width:100%; margin-top:5px;"></textarea>
</div>
<div class='calibrate_row'>
<H4>Step 3 : Calculate Parameters</H4>
<img id='calibrate_step3_mark' class='calibrate_mark' src='images/green_mark.jpg'>
</div>
<div class='calibrate_row'>
<H4 id='calibrate_step3_label'></H4>
<button id='calculate_parameters_button' type="button" class="btn btn-info">Auto Calculate Parameters</button>
</div>
</div>
<div class="modal-footer">
<button id='calibrate_cancel_button' type="button" class="btn btn-warning" data-dismiss="modal">Cancel</button>
<button id='calibrate_done_button' type="button" class="btn btn-success" data-dismiss="modal">Save</button>
</div>
</div>
</div>
</div>
<!-- Calibrate Modal Window -->
<div id='alert_calibrate_success' class="alert alert-success hide">
<a href="#" class="close" data-dismiss="alert" aria-label="close">X</a>
<strong>Success!</strong> This alert box could indicate a successful or positive action.
</div>
</body>
</html>