-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
1502 lines (1434 loc) · 64.4 KB
/
index.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
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
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
module.exports = function (app) {
/**/
var plugin = {};
var versionTXT = '';
plugin.id = 'e-inkDashboard';
plugin.name = 'e-inkDashboard';
plugin.description = 'e-ink screens - optimized dashboard with some Signal K instruments';
plugin.schema = {
'title': plugin.name,
'type': 'object',
'required': [],
'properties': {
'speedProp':{
'title': '',
'type': 'object',
'properties': {
'feature':{
'type': 'string',
'title': 'Will be displayed as Speed:',
'enum': [
'Speed ower ground (SOG)',
'Speed through water (STW)',
],
'default': 'Speed ower ground (SOG)'
},
},
},
'depthProp':{
'title': '',
'type': 'object',
'properties': {
'feature':{
'type': 'string',
'title': 'Will be displayed as Depth:',
'enum': [
'Depth below surface (DBS)',
'Depth below keel (DBK)',
'Depth below transducer (DBT)',
],
'default': 'Depth below transducer (DBT)'
},
},
},
'dashboardPort': {
'type': 'string',
'title': 'port of dashboard',
'description': `Open this port in the firewall. If this port is busy on your system, change it to other
`,
'default': '3531'
},
'refreshInterval': {
'type': 'number',
'title': 'Dashboard refresh interval, sec',
'description': `Set this as quickly as your e-ink device may.
`,
'default': 2
},
'checkDataFreshness':{
'type': 'boolean',
'title': 'Checking the freshness of data',
'description': `Does not display out-of-date data. If all devices on your network have the same time
(with differents less than 1 sec.) -- check this and you can be sure that you see actual data.
`,
'default': true
},
'updNotifications':{
'type': 'boolean',
'title': 'Update SignalK notifications',
'description': `Updating the SignalK notification system value zones and raising alarms. Note that
each instance of the dashboard has its own alarms, but SignalK alert is one for all.
`,
'default': true
},
}
};
var unsubscribes = []; // массив функций с традиционным именем, в котором функции, которые надо выполнить при остановке плагина
plugin.start = function (options, restartPlugin) {
//
//app.debug('Plugin started');
const http = require('http');
const url = require('url');
const path = require("path");
const fs = require("fs");
const exec = require('child_process');
//const dashboardHost = exec.execSync('hostname --all-ip-addresses').toString().trim().split(' ')[0]; // иначе, как вызовом системной команды адрес не узнать. Это ли не жопа?
let dashboardHost = exec.execSync('ip -o -4 addr show scope global').toString(); // но, однако, нормальный вариант команды есть не во всех системах
const addrStart = dashboardHost.indexOf('inet')+4;
const addrEnd = dashboardHost.indexOf('/');
dashboardHost = dashboardHost.slice(addrStart,addrEnd).trim();
if(!dashboardHost) dashboardHost = 'localhost';
//app.debug(dashboardHost);
const dashboardPort = options.dashboardPort;
if(options.speedProp.feature.includes('SOG')) options.speedProp.feature = 'navigation.speedOverGround';
else if(options.speedProp.feature.includes('STW')) options.speedProp.feature = 'navigation.speedThroughWater';
if(options.depthProp.feature.includes('DBS')) options.depthProp.feature = 'environment.depth.belowSurface';
else if(options.depthProp.feature.includes('DBK')) options.depthProp.feature = 'environment.depth.belowKeel';
else if(options.depthProp.feature.includes('DBT')) options.depthProp.feature = 'environment.depth.belowTransducer';
//app.debug('options:',options);
// Если версия старая, будем сами выставлять notification, а если новая -
// пусть это делает SignalK.
// Определим версию SignalK
let signalKold = app.config.version; // это не версия плагина, как можно было бы подумать, а версия сервера.
if(signalKold[0]>2 || (signalKold[0]==2 && signalKold[2]>8) || (signalKold[0]==2 && signalKold[2]==8 && signalKold[4]>1)){
signalKold = false;
}
else signalKold = true;
//signalKold = true; // Оно всё равно с ошибкой, отключаем
//app.debug('signalKold=',signalKold);
const indexhtml = `<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<meta http-equiv='refresh' content='1;url=http://${dashboardHost}:${dashboardPort}/'>
</head>
<body style="text-align: center;">
<span style="font-size: 600%;"><br><br>Dashboard not run</span>
</body>
</html>
`;
const indexDir = __dirname+'/public';
if (!fs.existsSync(indexDir)) fs.mkdirSync(indexDir);
fs.writeFileSync(indexDir+'/index.html',indexhtml);
var tpv = {};
var modes = {}; // состояние каждого клиента
// функция, реализующая функциональность сервера. Поскольку в node.js всё через жопу -- нельзя заставить уже имеющийся сервер выполнять дополнительные функции, надо организовать свой. Ага, на своём порту, б... Правда, вроде, есть Express, но оно тооооормоооозззззз.
function dashboardServer(request, response) {
//app.debug('request:',request);
//app.debug('request:',request.headers['accept-language']);
//app.debug('request:',request.headers.cookie);
// чёта cookie-parser нету. ну сделаем свой, чё.
var cookies = request.headers.cookie;
if(cookies){
cookies.split(';');
//app.debug('cookies:',typeof cookies,cookies);
// Какая-то фигня. В доке https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
// ясно сказано: "If separator does not occur in str, the returned array contains one element consisting of the entire string."
// однако мы наблюдаем, что возвращается строка...
if(typeof cookies == 'string') cookies = [cookies];
cookies.forEach((str,i) => {
str = str.split('=');
str[0] = '"'+str[0].trim()+'" : ';
if(str[1][0]!='{') str[1] = '"'+str[1].trim()+'"';
str = str.join('');
cookies[i] = str;
//app.debug(str);
});
cookies = JSON.parse('{'+cookies.join(',')+'}');
}
else cookies = {};
//app.debug('cookies:',cookies);
// Serve static files
let uri = url.parse(request.url).pathname;
//app.debug('uri',uri);
if(uri.startsWith('/static')) { // только если спросили файл из специального каталога
//app.debug('path.dirname(__filename):',path.dirname(__filename));
//app.debug('process.cwd()',process.cwd(),'filename',filename);
const filename = path.join(__dirname, uri); // каталог запущенного файла (ибо рабочий каталог указывает в ~, и почему это так -- неясно), и каталог в запросе
//app.debug('uri',uri,'filename',filename);
// синхронно проверяем наличие файла
if(fs.existsSync(filename)) { // файл или каталог есть
if(fs.statSync(filename).isDirectory()) { // если спросили каталог
response.statusCode = 403;
response.setHeader('Content-Type', 'text/html; charset=utf-8');
response.write("403 Forbidden\n");
response.end();
return;
}
//app.debug('filename',filename);
let file;
try {
file = fs.readFileSync(filename); // синхронно читаем файл. Если асинхронно, то в кривом Node.js будет непонятно, на чём сработает response.write(file), и будет ошибка ERR_STREAM_WRITE_AFTER_END, или response.setHeader, и будет ошибка, что заголовки уже посланы
}
catch (err) {
app.debug(err);
response.statusCode = 500;
response.setHeader('Content-Type', 'text/html; charset=utf-8');
response.write(err + "\n");
response.end();
return;
}
//app.debug('filename',filename,'\n',file);
// header и длину ответа устанавливать не будем, потому что всё это надо делать руками. Пусть будет криво -- нефиг пользоваться Node.js
response.statusCode = 200;
response.write(file); // file -- это buffer.
response.end();
return;
}
else { // файла или каталога нет
response.statusCode = 404;
response.setHeader('Content-Type', 'text/html; charset=utf-8');
response.write("404 Not Found\n");
response.end();
return;
}
}
// Serve index.
/* Идея гонять сессию через запрос единственно верная для принятого способа
обновления страницы. Но тогда клиент не идентифицуем, и, скажем, по перезагрузке клиентского
устройства клиент будет новым, и не восстановятся оповещения. Кроме того, если делать
установку "зон" в SignalK, то надо делать и удаление - не всех имеющихся зон, а именно выставленных,
и даже - выставленных этим клиентом. Т.е., клиента надо идентифицировать.
Идентифицировать через куку, ибо фингерпринт - это извращение и всё равно для абсолютно тупого клиента
ненадёжно.
Однако, в куку кладётся только идентификатор, а не вся сессия. Так сохраняется
работоспособность совсем тупых клиентов, которые не умеют ни javascript, ни даже куки.
*/
let mode = {}; // все данные конкретного клиента. Гоняются к клиенту и обратно в переменной session
//app.debug('request.url',request.url);
//app.debug("modes:",modes);
const inData = url.parse(request.url,true).query;
//app.debug('inData:',inData);
if(cookies['e-inkDashboardInstance']){
//app.debug('Установим идентификатор клиента в',cookies['e-inkDashboardInstance']);
mode.instance = cookies['e-inkDashboardInstance'];
}
else mode.instance = generateUUID();
if(modes[mode.instance]) mode = modes[mode.instance];
else if(inData.session) {
mode = JSON.parse(inData.session);
};
//app.debug('mode:',mode);
//app.debug('mode.instance:',mode.instance);
// Интернационализация
var dashboardCourseTXT = 'Course';
var dashboardHeadingTXT = 'Heading';
var dashboardMagCourseTXT = 'Magnetic course';
var dashboardMagHeadingTXT = 'Magnetic heading';
var dashboardMagVarTXT = 'Magnetic variation';
var dashboardSpeedTXT = 'Velocity';
var dashboardMinSpeedAlarmTXT = 'Speed too high';
var dashboardMaxSpeedAlarmTXT = 'Speed too low';
var dashboardSpeedMesTXT = 'km/h';
var dashboardDepthTXT = 'Depth';
var dashboardDepthAlarmTXT = 'Too shallow';
var dashboardDepthMesTXT = 'm';
var dashboardGNSSoldTXT = 'Instrument data old';
var dashboardDepthMenuTXT = 'Shallow';
var dashboardMinSpeedMenuTXT = 'Min speed';
var dashboardMaxSpeedMenuTXT = 'Max speed';
var dashboardToCourseAlarmTXT = 'The course is bad';
var dashboardToHeadingAlarmTXT = 'The heading is bad';
var dashboardKeysMenuTXT = 'Use keys to switch the screen mode';
var dashboardKeySetupTXT = 'Select purpose and press key for:';
var dashboardKeyNextTXT = 'Next mode';
var dashboardKeyPrevTXT = 'Previous mode';
var dashboardKeyMenuTXT = 'Alarm menu';
var dashboardKeyMagneticTXT = 'Magnetic course';
var dashboardMOBTXT = 'A man overboard!';
//app.debug("request.headers['accept-language']:",request.headers['accept-language']);
let i18nFileName = request.headers['accept-language'].split(',',1)[0].split(';',1)[0].split('-',1)[0].toLowerCase()+'.json'; // хотя она и так должна быть LowerCase, но то должна.
//console.log('i18nFileName=',i18nFileName);
//i18nFileName = 'en.json'
let i18n;
try {
i18n = JSON.parse(fs.readFileSync(path.join(__dirname,'internationalisation/'+i18nFileName))); // синхронно читаем файл. Если асинхронно, то в кривом Node.js будет непонятно, на чём сработает response.write(file), и будет ошибка ERR_STREAM_WRITE_AFTER_END, или response.setHeader, и будет ошибка, что заголовки уже посланы
({ dashboardCourseTXT,
dashboardHeadingTXT,
dashboardMagCourseTXT,
dashboardMagHeadingTXT,
dashboardMagVarTXT,
dashboardSpeedTXT,
dashboardMinSpeedAlarmTXT,
dashboardMaxSpeedAlarmTXT,
dashboardSpeedMesTXT,
dashboardDepthTXT,
dashboardDepthAlarmTXT,
dashboardDepthMesTXT,
dashboardGNSSoldTXT,
dashboardDepthMenuTXT,
dashboardMinSpeedMenuTXT,
dashboardMaxSpeedMenuTXT,
dashboardToCourseAlarmTXT,
dashboardToHeadingAlarmTXT,
dashboardKeysMenuTXT,
dashboardKeySetupTXT,
dashboardKeyNextTXT,
dashboardKeyPrevTXT,
dashboardKeyMenuTXT,
dashboardKeyMagneticTXT,
dashboardMOBTXT
} = i18n); // () тут обязательно, потому что не var {} = obj, и кривой JavaScript воспринимает {} как блок кода;
}
catch (err) {
//app.debug(err.message);
app.setPluginError(`Internationalisation file:`+err.message);
};
if(inData.mode) mode.mode = inData.mode;
if(typeof inData.magnetic !== 'undefined') mode.magnetic = parseInt(inData.magnetic,10);
let magneticTurn;
if(mode.magnetic) magneticTurn = 0;
else magneticTurn = 1;
let menu = inData['menu'];
if(!mode.toHeadingPrecision) mode.toHeadingPrecision = 10;
//app.debug('meta:',app.getSelfPath(options.speedProp.feature+'.meta'));
if(inData['submit']) {
//app.debug('inData',inData);
//app.debug('mode',mode);
const previous_depthAlarm = mode.depthAlarm;
mode.depthAlarm = inData['depthAlarm'];
mode.minDepthValue = parseFloat(inData['minDepthValue']);
if(!mode.minDepthValue) mode.depthAlarm = false;
const previous_minSpeedAlarm = mode.minSpeedAlarm;
mode.minSpeedAlarm = inData['minSpeedAlarm'];
mode.minSpeedValue = parseFloat(inData['minSpeedValue']);
if(!mode.minSpeedValue) mode.minSpeedAlarm = false;
const previous_maxSpeedAlarm = mode.maxSpeedAlarm;
mode.maxSpeedAlarm = inData['maxSpeedAlarm'];
mode.maxSpeedValue = parseFloat(inData['maxSpeedValue']);
if(!mode.maxSpeedValue) mode.maxSpeedAlarm = false;
// запишем в mode.toHeadingAlarm что у нас, собственно, значит toHeading
const previous_toHeadingAlarm = mode.toHeadingAlarm;
switch(mode.mode){ // хотя здесь ещё может не быть mode.mode
case 'track':
if(mode.magnetic) mode.toHeadingAlarm = 'navigation.courseOverGroundMagnetic';
else mode.toHeadingAlarm = 'navigation.courseOverGroundTrue';
case 'heading':
if(mode.magnetic) mode.toHeadingAlarm = 'navigation.headingMagnetic';
else mode.toHeadingAlarm = 'navigation.headingTrue';
default:
mode.toHeadingAlarm = 'navigation.courseOverGroundTrue';
}
let toRemovePath;
if(!inData['toHeadingAlarmCheck']){
toRemovePath = mode.toHeadingAlarm;
mode.toHeadingAlarm = false;
}
//app.debug("inData['toHeadingAlarmCheck']:",inData['toHeadingAlarmCheck'],'mode.toHeadingAlarm:',mode.toHeadingAlarm);
mode.toHeadingValue = parseFloat(inData['toHeadingValue']);
mode.toHeadingPrecision = parseFloat(inData['toHeadingPrecision']);
mode.toHeadingMagnetic = mode.magnetic;
if(!mode.toHeadingValue) mode.toHeadingAlarm = false;
// Теперь в этом уродском SignalK попытаемся выставить границы параметров
// Считаем, что кроме нас границы никто не ставит, потому что если ставит, то как в них разобраться, чтобы изменить нужное? Агащазкакже, не ставит...
// Кароче, облом. Изменить meta не удаётся. Кароче, оказалось, что для meta есть специальный синтаксис. Б...
// Скорость
//app.debug('mode',mode);
if(options.updNotifications){
// Скорость
if(mode.minSpeedAlarm || mode.maxSpeedAlarm){
let zones=[],minVal=0,maxVal=102.2;
if(mode.minSpeedAlarm) {
minVal = mode.minSpeedValue*1000/(60*60);
zones.push({lower: 0, upper: minVal, state: "alarm", message: mode.instance});
}
if(mode.maxSpeedAlarm) {
maxVal = mode.maxSpeedValue*1000/(60*60);
zones.push({lower: maxVal, upper: 102.2, state: "alarm", message: mode.instance});
}
zones.push({lower: minVal, upper: maxVal, state: "normal", message: mode.instance});
setSKzones(options.speedProp.feature,zones,mode.instance); // установим границы значений
}
else {
if(previous_minSpeedAlarm || previous_maxSpeedAlarm){ // будем дёргать сервер только если действительно произошли изменения
setSKzones(options.speedProp.feature,null,mode.instance,null); // уберём границы значений
if(signalKold) setSKnotification(options.speedProp.feature,null) // уберём оповещение
};
};
// Глубина
if(mode.depthAlarm) {
let zones=[],minVal=0,maxVal=11000;
minVal = mode.minDepthValue;
zones.push({lower: 0, upper: minVal, state: "alarm", message: mode.instance});
zones.push({lower: minVal, upper: maxVal, state: "normal", message: mode.instance});
//app.debug("inData['submit'] zones:",zones);
setSKzones(options.depthProp.feature,zones,mode.instance); // установим границы значений
}
else {
if(previous_depthAlarm){ // будем дёргать сервер только если действительно произошли изменения
setSKzones(options.depthProp.feature,null,mode.instance,null); // уберём границы значений
if(signalKold) setSKnotification(options.depthProp.feature,null) // уберём оповещение
};
};
// Направление
if(mode.toHeadingAlarm) {
let zones=[],minVal,maxVal;
minVal = mode.toHeadingValue-mode.toHeadingPrecision;
if(minVal<0) minVal = minVal+360;
minVal = minVal * Math.PI / 180;
maxVal = mode.toHeadingValue+mode.toHeadingPrecision;
if(maxVal>=360) maxVal = maxVal-360;
maxVal = maxVal * Math.PI / 180;
zones.push({lower: 0, upper: minVal, state: "alarm", message: mode.instance});
zones.push({lower: maxVal, upper: 2*Math.PI, state: "alarm", message: mode.instance});
zones.push({lower: minVal, upper: maxVal, state: "normal", message: mode.instance});
//app.debug('zones:',zones);
setSKzones(mode.toHeadingAlarm,zones,mode.instance); // установим границы значений
}
else {
if(previous_toHeadingAlarm){ // будем дёргать сервер только если действительно произошли изменения
setSKzones(toRemovePath,null,mode.instance,null); // уберём границы значений
if(signalKold) setSKnotification(toRemovePath,null) // уберём оповещение
};
};
};
};
// Получение приборов
//var tpv = {};
if(app.getSelfPath(options.speedProp.feature)){
if(!tpv.speed) tpv.speed = {};
tpv.speed.value = app.getSelfPath(options.speedProp.feature).value;
tpv.speed.timestamp = Date.parse(app.getSelfPath(options.speedProp.feature).timestamp);
}
if(app.getSelfPath(options.depthProp.feature)){
if(!tpv.depth) tpv.depth = {};
tpv.depth.value = app.getSelfPath(options.depthProp.feature).value;
tpv.depth.timestamp = Date.parse(app.getSelfPath(options.depthProp.feature).timestamp);
}
if(app.getSelfPath('navigation.courseOverGroundTrue')){
if(!tpv.track) tpv.track = {};
tpv.track.value = app.getSelfPath('navigation.courseOverGroundTrue').value *180/Math.PI;
tpv.track.timestamp = Date.parse(app.getSelfPath('navigation.courseOverGroundTrue').timestamp);
}
if(app.getSelfPath('navigation.headingTrue')){
if(!tpv.heading) tpv.heading = {};
tpv.heading.value = app.getSelfPath('navigation.headingTrue').value *180/Math.PI;
tpv.heading.timestamp = Date.parse(app.getSelfPath('navigation.headingTrue').timestamp);
}
if(app.getSelfPath('navigation.courseOverGroundMagnetic')){
if(!tpv.magtrack) tpv.magtrack = {};
tpv.magtrack.value = app.getSelfPath('navigation.courseOverGroundMagnetic').value *180/Math.PI;
tpv.magtrack.timestamp = Date.parse(app.getSelfPath('navigation.courseOverGroundMagnetic').timestamp);
}
if(app.getSelfPath('navigation.headingMagnetic')){
if(!tpv.mheading) tpv.mheading = {};
tpv.mheading.value = app.getSelfPath('navigation.headingMagnetic').value *180/Math.PI;
tpv.mheading.timestamp = Date.parse(app.getSelfPath('navigation.headingMagnetic').timestamp);
if(!tpv.mheading.value) {
if(app.getSelfPath('navigation.headingCompass')){
tpv.mheading.value = app.getSelfPath('navigation.headingCompass').value *180/Math.PI;
tpv.mheading.timestamp = Date.parse(app.getSelfPath('navigation.headingCompass').timestamp);
if(tpv.mheading.value && tpv.magdev !== undefined) tpv.mheading.value += tpv.magdev.value;
if(mode.toHeadingAlarm) mode.toHeadingAlarm = 'navigation.headingCompass';
}
}
}
if(app.getSelfPath('navigation.magneticVariation')){
if(!tpv.magvar) tpv.magvar = {};
tpv.magvar.value = app.getSelfPath('navigation.magneticVariation').value *180/Math.PI;
tpv.magvar.timestamp = Date.parse(app.getSelfPath('navigation.magneticVariation').timestamp);
}
if(app.getSelfPath('navigation.magneticDeviation')){
if(!tpv.magdev) tpv.magdev = {};
tpv.magdev.value = app.getSelfPath('navigation.magneticDeviation').value *180/Math.PI;
tpv.magdev.timestamp = Date.parse(app.getSelfPath('navigation.magneticDeviation').timestamp);
}
//app.debug('tpv:',tpv);
// Получение MOB
let mobPosition = null;
// Похоже, что автор Freeboard-SK индус. В любом случае - он дебил, и
// разницы между выключением режима и сменой режима не видит.
// Поэтому он выключает режим MOB установкой value.state = "normal"
// вместо value = null, как это указано в документации.
if(app.getSelfPath('notifications.mob.value')){
let value = app.getSelfPath('notifications.mob.value');
if(value && (value.state != "normal")){
mode.mob = true;
let from=[],to=[],selfLonLat;
if(selfLonLat=app.getSelfPath('navigation.position.value')){
from.push(selfLonLat.longitude,selfLonLat.latitude);
}
if(value.data && value.data.position){ // это MOB от Freeboard-SK
to.push(value.data.position.longitude,value.data.position.latitude);
}
else if(value.position && value.position.features){ // Это GeoJSON
// поищем точку, указанную как текущая
for(let point of value.position.features){ // там не только точки, но и LineString
if((point.geometry.type == "Point") && point.properties.current){
to = point.geometry.coordinates;
break;
};
};
}
else {
if(value.position){
const s = JSON.stringify(value.position);
if(s.includes('longitude') && s.includes('latitude')){
to.push(value.position.longitude,value.position.latitude);
}
else if(s.includes('lng') && s.includes('lat')){
to.push(value.position.lng,value.position.lat);
}
else if(s.includes('lon') && s.includes('lat')){
to.push(value.position.lon,value.position.lat);
}
else if(Array.isArray(value.position)){
to=value.position;
};
}
else{
const s = JSON.stringify(value);
if(s.includes('longitude') && s.includes('latitude')){
to.push(value.longitude,value.latitude);
}
else if(s.includes('lng') && s.includes('lat')){
to.push(value.lng,value.lat);
}
else if(s.includes('lon') && s.includes('lat')){
to.push(value.lon,value.lat);
}
else if(Array.isArray(value)){
to=value.position;
};
};
};
if(to.length){
to.forEach((coord)=>parseFloat(coord));
if(isNaN(to[0]) || isNaN(to[1])) to=[];
}
mobPosition = [from,to];
//app.debug('mob data from server',mobPosition);
}
else {
mode.mob = false;
};
}
else {
mode.mob = false;
};
//app.debug('mode.mob =',mode.mob);
// перепишем теневое значение mode актуальным, раз такова воля юзера
// здесь фиксируется то состояние mode, которое "нормальное"
// дальше mode меняется в зависимости от ситуации, но это как бы временное:
// оно отражается в интерфейсе, но не является текущим состоянием
inData.session = JSON.stringify(mode);
modes[mode.instance] = mode;
// Поехали
// типы данных, которые, собственно, будем показывать
const displayData = { //
'track' : {'variants' : [['track',dashboardCourseTXT],['magtrack',dashboardMagCourseTXT]], // путь, магнитный путь
'precision' : 0, // точность показываемой цифры, символов после запятой
'multiplicator' : 1, // на что нужно умножить значение для показа
'fresh': (5+options.refreshInterval) * 1000 // время свежести, миллисек.
},
'heading' : {'variants' : [['heading',dashboardHeadingTXT],['mheading',dashboardMagHeadingTXT]], // курс или магнитный курс
'precision' : 0,
'multiplicator' : 1,
'fresh': (5+options.refreshInterval) * 1000 // время свежести, миллисек.
},
'speed' : {'variants' : [['speed',dashboardSpeedTXT+', '+dashboardSpeedMesTXT]], // скорость
'precision' : 1,
'multiplicator' : 60*60/1000,
'fresh': (3+options.refreshInterval) * 1000
},
'depth' : {'variants' : [['depth',dashboardDepthTXT+', '+dashboardDepthMesTXT]], // глубина
'precision' : 1,
'multiplicator' : 1,
'fresh': (2+options.refreshInterval) * 1000
}
};
// Очищаем данные от устаревших
if(options.checkDataFreshness){
for(let props in displayData){
for(let variant of displayData[props].variants){
if(variant[0] in tpv){
//console.log('Очищаем данные от устаревших',variant[0],tpv[variant[0]],Date.now()-tpv[variant[0]].timestamp,displayData[props].fresh);
if(tpv[variant[0]] && ((Date.now()-tpv[variant[0]].timestamp)>displayData[props].fresh)){
app.debug('Property',variant[0],'expired on',(Date.now()-tpv[variant[0]].timestamp)/1000,'sec.');
delete tpv[variant[0]]; //
}
}
}
}
}
//app.debug('tpv:',tpv);
let alarm = false, prevMode = null, nextMode = null, currDirectMark='', currTrackMark='';
let enough = false, type, parm, variant, variantType, symbol='', nextsymbol='', header = '';
// Оповещения в порядке возрастания опасности, реально сработает последнее
// Похоже, сам SignalK оповещения не выставляет, или я опять чего-то не понял. Teppo традиционно молчит, доку можно понять, что должен. И по идее -- должен, иначе какой смысл назначать zones. Но -- нет.
let alarmJS;
if(mode.minSpeedAlarm && tpv['speed'] && (tpv['speed'].value != (null || undefined))) {
if(tpv['speed'].value*60*60/1000 <= mode.minSpeedValue) {
mode.mode = 'speed';
header = dashboardMinSpeedAlarmTXT;
alarmJS = 'minSpeedAlarmSound();';
alarm = true;
if(options.updNotifications && signalKold) setSKnotification(options.speedProp.feature,{method: ["sound", "visual"],state: "alarm",message: mode.instance}); // Установим оповещение
}
else{
if(options.updNotifications && signalKold) setSKnotification(options.speedProp.feature,null); // Уберём оповещение
}
}
if(mode.maxSpeedAlarm && tpv['speed'] && (tpv['speed'].value != (null || undefined))) {
if(tpv['speed'].value*60*60/1000 >= mode.maxSpeedValue) {
mode.mode = 'speed';
header = dashboardMaxSpeedAlarmTXT;
alarmJS = 'maxSpeedAlarmSound();';
alarm = true;
if(options.updNotifications && signalKold) setSKnotification(options.speedProp.feature,{method: ["sound", "visual"],state: "alarm",message: mode.instance}); // Установим оповещение
}
else{
if(options.updNotifications && signalKold) setSKnotification(options.speedProp.feature,null); // Уберём оповещение
}
}
let theHeading=null, toHeadingAlarm=false;
if(mode.toHeadingAlarm && !mode.mob) {
toHeadingAlarm=true;
let theHeading=null; // это будет другой theHeading, используемый только для вычисления тревоги
if(mode.toHeadingMagnetic && tpv.magtrack) theHeading = tpv.magtrack.value;
else if(tpv.track) theHeading = tpv.track.value; // тревога прозвучит, даже если был указан магнитный курс, но его нет
if(theHeading){
let minHeading = mode.toHeadingValue - mode.toHeadingPrecision;
if(minHeading<0) minHeading = minHeading+360;
let maxHeading = mode.toHeadingValue + mode.toHeadingPrecision;
if(maxHeading>=360) maxHeading = maxHeading-360;
if((theHeading < minHeading) || (theHeading > maxHeading)) {
switch(mode.mode){
case 'heading':
header = dashboardToHeadingAlarmTXT;
if(options.updNotifications && signalKold) setSKnotification(mode.toHeadingAlarm,{method: ["sound", "visual"],state: "alarm",message: mode.instance}); // Установим оповещение
break;
case 'track':
default:
mode.mode = 'track';
header = dashboardToCourseAlarmTXT;
if(options.updNotifications && signalKold) setSKnotification(mode.toHeadingAlarm,{method: ["sound", "visual"],state: "alarm",message: mode.instance}); // Установим оповещение
}
alarmJS = 'toHeadingAlarmSound();';
alarm = true;
}
else{
if(options.updNotifications && signalKold) setSKnotification(mode.toHeadingAlarm,null); // Уберём оповещение
};
}
else {
if(options.updNotifications && signalKold) setSKnotification(mode.toHeadingAlarm,null); // Уберём оповещение
};
};
if(mode.depthAlarm && tpv['depth'] && (tpv['depth'].value != (null || undefined))) {
if(tpv['depth'].value <= mode.minDepthValue) {
mode.mode = 'depth';
header = dashboardDepthAlarmTXT;
alarmJS = 'depthAlarmSound();';
alarm = true;
if(options.updNotifications && signalKold) setSKnotification(options.depthProp.feature,{method: ["sound", "visual"],state: "alarm",message: mode.instance}); // Установим оповещение
}
else {
if(options.updNotifications && signalKold) setSKnotification(options.depthProp.feature,null); // Уберём оповещение
}
}
//app.debug('alarm=',alarm,'mode.mode=',mode.mode,'mode.mob=',mode.mob);
// Что будем рисовать
const parms = Object.keys(displayData);
const cnt = parms.length;
let cycle = null;
for(let i=0;i<cnt;i++){ //
type = parms[i];
parm = displayData[type];
//app.debug('type=',type,"parm=",parm,'mode=',mode);
if(!mode.mode) mode.mode = type; // что-то не так с типом, сделаем текущий тип указанным
if(enough) {
variant = 0;
if(type == 'track' && mode.magnetic) variant = 1;
variantType = parm['variants'][variant][0];
//app.debug('Next variantType =',variantType);
if(tpv[variantType] == undefined) { // но такого типа значения нет в полученных данных.
if(i == cnt-1) i = -1; // цикл по кругу
continue;
}
if(cycle == variantType){ // прокрутили до ранее выбранного типа, но нечего показывать
nextsymbol = '';
break;
}
nextsymbol = parm['variants'][variant][1]+": "+Math.round(tpv[variantType].value*parm['multiplicator']*(10**parm['precision']))/(10**parm['precision']);
nextMode = type;
//app.debug('symbol =',symbol,'nextsymbol=',nextsymbol,'nextMode=',nextMode,'parm=',parm);
break;
}
if(type != mode.mode) { // это не указанный тип
prevMode = type;
continue;
}
variant = 0;
if(type == 'track' && mode.magnetic) variant = 1;
variantType = parm['variants'][variant][0];
//app.debug('Main variantType =',variantType,tpv);
if(tpv[variantType] == undefined) { // но такого типа значения нет в полученных данных.
mode.mode = null; // обозначим, что следующий тип должен стать указанным
if(cycle == variantType){ // прокрутили все типы, но нечего показывать
symbol = 'No data';
break;
}
if(!cycle) cycle = variantType; // запомним этот тип того, что нужно показывать для проверки зацикливания, если ничего не осталось показывать
if(i == cnt-1) i = -1; // цикл по кругу
//app.debug('Cycle2 type=',type,"mode.mode=",mode.mode,'i=',i);
continue;
}
if(!header) header = parm['variants'][variant][1];
symbol = Math.round(tpv[variantType].value*parm['multiplicator']*(10**parm['precision']))/(10**parm['precision']);
enough = true;
cycle = variantType; // сдедующий тип будем искать по кругу до выбранного
if(i == cnt-1) i = -1; // цикл по кругу
//app.debug('Cycle type=',type,'prevMode=',prevMode,"mode.mode=",mode.mode,'nextMode=',nextMode,'i=',i,'cnt=',cnt);
}
if(!prevMode){
prevMode = parms[cnt-1];
}
//app.debug('Exit cycle type=',type,'prevMode=',prevMode,"mode.mode=",mode.mode,'nextMode=',nextMode);
if(mode.toHeadingMagnetic && tpv['magtrack']) theHeading = tpv['magtrack'].value;
else if(tpv['track']) theHeading = tpv['track'].value; //
else theHeading = null;
const rumbNames = [' N ','NNE',' NE ','ENE',' E ','ESE',' SE ','SSE',' S ','SSW',' SW ','WSW',' W ','WNW',' NW ','NNW'];
let rumbNum;
if(theHeading !== null){
rumbNum = theHeading;
rumbNum = Math.round(rumbNum/22.5);
if(rumbNum==16) rumbNum = 0;
}
else rumbNum = null;
let currRumb = [' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '];
currRumb[rumbNum] = rumbNames[rumbNum];
let MOBtxt = '';
if(mode.mob) {
MOBtxt = `<div style="position:absolute;left:1%;right:auto;top:20%;opacity: 0.3;" class="big_mid_symbol wb"><span style="">${dashboardMOBTXT}</span></div>`;
if(mobPosition){
toHeadingAlarm = true;
mode.toHeadingValue = Math.round(bearing(mobPosition[0],mobPosition[1]));
//app.debug('mode.toHeadingValue=',mode.toHeadingValue,mobPosition[0],mobPosition[1]);
}
}
let percent=null;
if(toHeadingAlarm) {
//mode.toHeadingValue =30;
// Метка указанного направления
if((mode.toHeadingValue>315)&&(mode.toHeadingValue<360)){
percent = 100 - (mode.toHeadingValue - 313)*100/90;
currDirectMark = `<img src='static/img/markNNW.png' style='display:block;position:fixed;top:0;right:${percent}%;' class='markVert'>`;
}
else if(mode.toHeadingValue == 0){
currDirectMark = `<img src='static/img/markN.png' style='display:block;position:fixed;top:0;left:49.5%;' class='markVert'>`;
}
else if((mode.toHeadingValue>0)&&(mode.toHeadingValue<45)){
percent = (mode.toHeadingValue+43)*100/90;
currDirectMark = `<img src='static/img/markNNE.png' style='display: block;position: fixed;top:0;left:${percent}%;' class='markVert'>`;
}
else if(mode.toHeadingValue == 45){
currDirectMark = `<img src='static/img/markNE.png' style='display: block;position: fixed;top:0;right:0;' class='markVert'>`;
}
else if((mode.toHeadingValue > 45) && (mode.toHeadingValue < 90)){
percent = 100 - (mode.toHeadingValue-43)*100/90;
currDirectMark = `<img src='static/img/markENE.png' style='display: block;position: fixed;right:0;bottom:${percent}%;' class='markHor'>`;
}
else if(mode.toHeadingValue == 90){
currDirectMark = `<img src='static/img/markE.png' style='display: block;position: fixed;right:0;top:49%;' class='markHor'>`;
}
else if((mode.toHeadingValue > 90) && (mode.toHeadingValue < 135)){
percent = (mode.toHeadingValue-47)*100/90;
currDirectMark = `<img src='static/img/markESE.png' style='display: block;position: fixed;right:0;top:${percent}%;' class='markHor'>`;
}
else if(mode.toHeadingValue == 135){
currDirectMark = `<img src='static/img/markSE.png' style='display: block;position: fixed;bottom:0;right:0;' class='markHor'>`;
}
else if((mode.toHeadingValue>135)&&(mode.toHeadingValue<180)){
percent = 100 - (mode.toHeadingValue-133)*100/90;
currDirectMark = `<img src='static/img/markSSE.png' style='display: block;position: fixed;bottom:0;left:${percent}%;' class='markVert'>`;
}
else if(mode.toHeadingValue == 180){
currDirectMark = `<img src='static/img/markS.png' style='display: block;position: fixed;bottom:0;left:49.5%;' class='markVert'>`;
}
else if((mode.toHeadingValue>180)&&(mode.toHeadingValue<225)){
percent = (mode.toHeadingValue-137)*100/90;
currDirectMark = `<img src='static/img/markSSW.png' style='display: block;position: fixed;bottom:0;right:${percent}%;' class='markVert'>`;
}
else if(mode.toHeadingValue==225){
currDirectMark = `<img src='static/img/markSW.png' style='display: block;position: fixed;bottom:0;left:0;' class='markHor'>`;
}
else if((mode.toHeadingValue>225)&&(mode.toHeadingValue<270)){
percent = 100 - (mode.toHeadingValue-223)*100/90;
currDirectMark = `<img src='static/img/markWSW.png' style='display:block;position:fixed;left:0;top:${percent}%;' class='markHor'>`;
}
else if(mode.toHeadingValue == 270){
currDirectMark = `<img src='static/img/markW.png' style='display: block;position: fixed;left:0;top:49%;' class='markHor'>`;
}
else if((mode.toHeadingValue>270)&&(mode.toHeadingValue<315)){
percent = (mode.toHeadingValue-227)*100/90;
currDirectMark = `<img src='static/img/markWNW.png' style='display:block;position:fixed;left:0;bottom:${percent}%;' class='markHor'>`;
}
else if(mode.toHeadingValue==315){
currDirectMark = `<img src='static/img/markNW.png' style='display: block;position: absolute;top:0;left:0;' class='markHor'>`;
}
// Метка текущего направления theHeading уже есть
if(theHeading !== null){
if((theHeading>315)&&(theHeading<=360)){
percent = 100 - (theHeading - 315)*100/90;
currTrackMark = `<img src='static/img/markCurrN.png' style='display:block;position:fixed;top:0;right:${percent}%;' class='vert'>`;
}
else if((theHeading>=0)&&(theHeading<45)){
percent = (theHeading+45)*100/90;
currTrackMark = `<img src='static/img/markCurrN.png' style='display: block;position: fixed;top:0;left:${percent}%;' class='vert'>`;
}
else if(theHeading == 45){
currTrackMark = `<img src='static/img/markCurrSE.png' style='display: block;position: fixed;top:0;right:0;' class='vert'>`;
}
else if((theHeading > 45) && (theHeading < 135)){
percent = 100 - (theHeading-45)*100/90;
currTrackMark = `<img src='static/img/markCurrE.png' style='display: block;position: fixed;right:0;bottom:${percent}%;' class='hor'>`;
}
else if(theHeading == 135){
currTrackMark = `<img src='static/img/markCurrNE.png' style='display: block;position: fixed;bottom:0;right:0;' class='vert'>`;
}
else if((theHeading>135)&&(theHeading<225)){
percent = 100 - (theHeading-135)*100/90;
currTrackMark = `<img src='static/img/markCurrN.png' style='display: block;position: fixed;bottom:0;left:${percent}%;' class='vert'>`;
}
else if(theHeading==225){
currTrackMark = `<img src='static/img/markCurrNE.png' style='display: block;position: fixed;bottom:0;left:0;' class='vert'>`;
}
else if((theHeading>225)&&(theHeading<315)){
percent = 100 - (theHeading-225)*100/90;
currTrackMark = `<img src='static/img/markCurrE.png' style='display:block;position:fixed;left:0;top:${percent}%;' class='hor'>`;
}
else if(theHeading==315){
currTrackMark = `<img src='static/img/markCurrNE.png' style='display: block;position: absolute;top:0;left:0;' class='vert'>`;
};
};
};
// DISPLAY:
let fontZ = Math.floor(symbol.length/3); // считая, что штатный размер шрифта позволяет разместить 4 символа на экране
if(fontZ>1) {
fontZ = Math.round((1/fontZ)*100);
symbol = "<span style='font-size:"+fontZ+"%;'>"+symbol+"</span>";
}
// Вся переменная mode является "сессией" и всегда сохраняется целиком
uri = encodeURI(`http://${dashboardHost}:${dashboardPort}/?session=${inData.session}`);
//app.debug("menu=",menu);
let responseBody = `<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<meta http-equiv="Content-Script-Type" content="text/javascript">
`;
if(!menu) responseBody += `<meta http-equiv='refresh' content="${options.refreshInterval}; url=${uri}" />`;
responseBody += `
<script src="static/dashboard.js"> </script>
`;
if(alarm) responseBody += "<script>"+alarmJS+"</script>";
responseBody += `
<link rel="stylesheet" href="static/dashboard.css" type="text/css">
<title>e-inkDashboard ${versionTXT}</title>
</head>
<body style="margin:0; padding:0;">
${currTrackMark} ${currDirectMark}
<!--Refresh interval: ${options.refreshInterval};-->
<script>
var controlKeys = getCookie('e-inkDashboardControlKeys');
if(controlKeys) {
controlKeys = JSON.parse(controlKeys);
}
else {
controlKeys = {
'upKey': ['ArrowUp',38],
'downKey': ['ArrowDown',40],
'menuKey': ['AltRight',18,2],
'magneticKey': ['KeyM',77]
}
}
//console.log('controlKeys before',controlKeys);
window.addEventListener("keydown", keySu, true);
function keySu(event) {
if (event.defaultPrevented) {
return; // Should do nothing if the default action has been cancelled
}
var handled = false;
if (event.code !== undefined) {
if(controlKeys.upKey.indexOf(event.code) != -1) handled = 'up';
else if(controlKeys.downKey.indexOf(event.code) != -1) handled = 'down';
else if(controlKeys.menuKey.indexOf(event.code) != -1) handled = 'menu';
else if(controlKeys.magneticKey.indexOf(event.code) != -1) handled = 'magnetic';
}
else if (event.keyCode !== undefined) { // Handle the event with KeyboardEvent.keyCode and set handled true.
if(controlKeys.upKey.indexOf(event.keyCode) != -1) handled = 'up';
else if(controlKeys.downKey.indexOf(event.keyCode) != -1) handled = 'down';
else if(controlKeys.menuKey.indexOf(event.keyCode) != -1) handled = 'menu';
else if(controlKeys.magneticKey.indexOf(event.keyCode) != -1) handled = 'magnetic';
}
else if (event.location != 0) { //
if(controlKeys.upKey.indexOf(event.location) != -1) handled = 'up';
else if(controlKeys.downKey.indexOf(event.location) != -1) handled = 'down';
else if(controlKeys.menuKey.indexOf(event.location) != -1) handled = 'menu';
else if(controlKeys.magneticKey.indexOf(event.location) != -1) handled = 'magnetic';
}
if (handled) {
event.preventDefault(); // Suppress "double action" if event handled
switch(handled){
case 'down':
//alert(handled);
window.location.href = '${uri}&mode=${nextMode}';
break;
case 'up':
//alert(handled);
window.location.href = '${uri}&mode=${prevMode}';
break;
case 'menu':
//alert(handled);
window.location.href = '${uri}&menu=${menu?'':'1'}';
break;
case 'magnetic':
//alert(handled);
window.location.href = '${uri}&magnetic=${magneticTurn}';
break;
}
}
} // end function keySu
let sendedInstance = "${mode.instance}";
let instance = getCookie('e-inkDashboardInstance');
if(!instance){
instance = sendedInstance;
let date = new Date(new Date().getTime()+1000*60*60*24*365).toGMTString();
document.cookie = 'e-inkDashboardInstance='+instance+'; expires='+date+';';
};
function getCookie(name) {
// возвращает cookie с именем name, если есть, если нет, то undefined
name=name.trim();
var matches = document.cookie.match(new RegExp(
"(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
)
);
//console.log('matches',matches);
return matches ? decodeURIComponent(matches[1]) : undefined;
};// end function getCookie
</script>
`;
if(menu) {
responseBody += `
<form action='${uri}' method='get' style = '
position:fixed;
right: 5%;
top: 5%;
width:75%;
background-color:lightgrey;
padding: 1rem;
font-size: xx-large;
z-index: 10;
'>
<input type='hidden' name='session' value=${JSON.stringify(mode)}>
<table>
<tr style='height:2rem;'>
<td><input type='checkbox' name='depthAlarm' value='1'
`;
if(mode.depthAlarm) responseBody += 'checked';
responseBody += ` style='height:3em;width:3rem;'
></td><td>${dashboardDepthMenuTXT}, ${dashboardDepthMesTXT}</td><td style='width:10%;'><input type='text' name=minDepthValue value='${mode.minDepthValue?mode.minDepthValue:''}' style='width:95%;font-size:inherit;'></td>
</tr><tr style='height:2rem;'>
<td><input type='checkbox' name='minSpeedAlarm' value='1'
`;
if(mode.minSpeedAlarm) responseBody += 'checked';
responseBody += ` style='height:3em;width:3rem;'
></td><td>${dashboardMinSpeedMenuTXT}, ${dashboardSpeedMesTXT}</td><td style='width:10%;'><input type='text' name=minSpeedValue value='${mode.minSpeedValue?mode.minSpeedValue:''}' style='width:95%;font-size:inherit;'></td>
</tr><tr style='height:2rem;'>
<td><input type='checkbox' name='maxSpeedAlarm' value='1'`;
if(mode.maxSpeedAlarm) responseBody += 'checked';
responseBody += ` style='height:3em;width:3rem;'