-
Notifications
You must be signed in to change notification settings - Fork 7
/
ITpings_dashboard.js
1993 lines (1722 loc) · 97.2 KB
/
ITpings_dashboard.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
/**
* @license MIT (C) ITpings.nl - Danny Engelman
*
* */
//todo: Do not not a graph line between two time points if there where no measurements for an N timeperiod
//todo: debug double gateways - activated event trace
//todo: plot coordinates
//todo: fixed alt in PingedGateways
//todo: link Gateway to TTNmapper: https://ttnmapper.org/colour-radar/?gateway=ttn_365csi_nl&type=radar
//todo: monitor when last ping was received (dashboard reports TTN server offline status)
//todo: preload other graph intervals (download largest then proces in WebWorker)
//todo: add Kalman filter : https://www.wouterbulten.nl/blog/tech/lightweight-javascript-library-for-noise-filtering/
//todo audio sounds for (new) events
//todo: (low) remove cached data when deleted from DB
//todo: (low) detect foreign traffic (wait for TTN V3)
//unoffical TTN endpoints
//https://www.thethingsnetwork.org/gateway-data/location?latitude=52.316&longitude=4.66040850&distance=2000
//http://noc.thethingsnetwork.org:8085/api/v2/gateways/ttn_365csi_nl
/**
* Functions and Variables starting with $_ are globals (replacing the need for jQuery, Lodash or Underscode)
*
* Use a decent IDE, like JetBrains, Atom or VSCode
* Learn to collapse regions/code-blocks with Alt-7 (code structure view) Ctrl-Plus and Ctrl-Minus
* press Ctrl-Shift-Minus now to collapse all code
* press Ctrl-Shift-Plus TWICE to uncollapse all code
* Use Ctrl-B to browse code by reference
*
* This Dashboard uses hardcoded Databases references
* If you make changes in the Database Schema, be sure to check those new names in this Dashboard source code
*
* **/
//region ========================================================== F12 Console traces with lots of colors
(console.log(function () {
window.$l = function () {// development code
console.log(...arguments);
};
return 'Initialized ITpings debugging functions';
}()));
/**
* See F12 console when running ITpings Dashboard
*
* eg: $_log( "mySection.red", data )
* **/
$_log = function () { // NO arrow function, then this scope will be the window, and there are no arguments in arrow function
let params = Array.from(arguments); // get all parameters and proces first parameter as label/CSS
let label = String(params.shift()).split('.'); // cast first parameter to String, then split on period
// define optional second backgroundcolor after dot (.)
// first %c gets second param CSS, next %c gets third param CSS, etc
let firstCSS = "background:lightgreen;";
let labelCSS_background = "background:" + (label[1] || "green");
let labelCSS_color = ";color:" + (label[2] || "white");
let labelCSS_fontweight = (label[2] === 'black' || label[3] === 'bold') ? ";font-weight:bold" : "";
let secondCSS = labelCSS_background + labelCSS_color + labelCSS_fontweight;
params = ["%c ITpings %c " + label[0] + " ", firstCSS, secondCSS, ...params];
console.log(...params);
};
$_logerror = function (err) {
// remove empty function: https://github.com/mishoo/UglifyJS2/issues/506
console.log("%c Error : %c " + (((new Error().stack).split("at ")[2]).split('(https')[0])
, "background:red;color:yellow;font-weight:bold", "background:teal;color:white;"
, function () {
return err;
}());
};
$_log.rows = function (rows, idfield = $_DEF.ID) {
// remove empty function: https://github.com/mishoo/UglifyJS2/issues/506
console.log("%c ITpings Rows : %c " + (((new Error().stack).split("at ")[2]).split('(https')[0])
, "background:gold;font-weight:bold", "background:teal;color:white;"
, function () {
let firstrow = rows[0];
let lastrow = rows[rows.length - 1];
return rows.length + " rows , ids: " + firstrow[idfield] + " - " + lastrow[idfield];
}());
};
//endregion ======================================================= F12 Console traces with lots of colors
//region ========================================================== learning to code without jQuery, Underscore or Lodash
$_emptyString = '';
// Tiny, recursive autocurry
const $_curry = (f, arr = []) => (...args) => (a => a.length === f.length ? f(...a) : $_curry(f, a))([...arr, ...args]);
// noinspection JSUnusedGlobalSymbols
const $_compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x);
// noinspection JSUnusedGlobalSymbols
const $_pipe = (...fns) => x => fns.reduce((y, f) => f(y), x);
let $_isDefined = x => typeof x !== "undefined";
// noinspection JSUnusedGlobalSymbols
/** String **/
let $_StrPad = (str, len, char) => (char.repeat(len) + str).slice(-1 * len);
// noinspection JSUnusedGlobalSymbols
let $_StrReverse = x => [...x].reverse().join``;
let $_isString = x => typeof x === "string";
/** Number **/
let $_isNumber = x => typeof x === "number";
let $_absolute = x => (x ^ (x >> 31)) - (x >> 31); // faster than Math.abs or unary expresssion
// noinspection JSUnusedGlobalSymbols
/** Array **/
let $_ArrayFrom = x => Array.from(x);
let $_isArray = x => Array.isArray(x);
let $_last = array => (array && array.slice(-1)[0]);
let $_lastNelements = (arr, n) => arr.slice(-1 * n);
let $_length = x => $_isArray(x) ? x.length : false;
let $_isEmptyArray = x => $_length(x) === 0;
let $_isNotEmptyArray = x => $_length(x) > 0;
let $_hasValue = (x, y) => x.indexOf(y) > -1;
// noinspection JSUnusedGlobalSymbols
let $_ArrayPushEnd = (arr, val) => arr.push(val);
// noinspection JSUnusedGlobalSymbols
let $_ArrayPushStart = (arr, val) => {
arr.unshift(val);
return arr;
}
/** CSV **/
let $_CSV2Array = x => x.split`,`;
/**
* Convert a CSV string -> array OR Array -> CSV string
* @return {Array || string}
*/
$_CSV_convert = function (csv, newline = '\n', keys = false, comma = ',') {
let Objkeys = x => Object.keys(x);
//let commaLine = x => x.join(comma);
if (Array.isArray(csv)) {
/** return String with {} Objects as Lines **/
csv = [
Objkeys(csv[0]).join(comma) // first array element = Object keys
, ...csv.map(row => Objkeys(row).map(key => row[key]).join(comma)) // spread all lines
].join(newline);
} else {
/** return Array with {} Objects **/
if (typeof csv === 'string' && csv.includes(newline)) // do not process single line Strings
csv = csv.split(newline).reduce((csv_arr, line, linenr) => {
line = line.split(comma);
if (linenr < 1 && !keys) keys = line; // first line are the header keys, or use keys parameter
else csv_arr.push(line.reduce( // convert Array to Object
(obj, val, idx) => {
let key = keys[idx];
//obj[key] = val; // CSV val is a string!
if (key === '1created' || key === '1time') obj[key] = new Date(val);
else obj[key] = isNaN(val) ? val : Number(val); // save Numbers as Numbers!
return obj;
}
, {})); // start with empty {} Object
return csv_arr;
}, []);
}
return csv;
};
/** Object **/
let $_hasOwnProperty = (obj, key) => obj && obj.hasOwnProperty(key);
/** Map **/
let $_newMap = x => new Map(x);
/** Set **/
let $_newSet = x => new Set(x);
let $_JSONstringify = x => JSON.stringify(x);
/** window methods **/
let $_setTimeout = (func, delay) => window.setTimeout(func(), delay);
/** DOM methods **/
let $_forceDOMupdate = () => window.setTimeout(void(false), 1);
let $_getElementById = element_id => document.getElementById(element_id);
let $_querySelectorAll = (selector, parent = document) => [...parent.querySelectorAll(selector)];
/** Attributes **/
let $_getAttribute = (element, property) => element.getAttribute(property);
let $_setAttribute = (element, property, value) => element.setAttribute(property, value);
// noinspection JSUnusedGlobalSymbols
let $_removeAttribute = (element, attr) => element.removeAttribute(attr);
// noinspection JSUnusedGlobalSymbols
let $_setAttributes = (element, arr) => $_Object_keys(arr).map((property) => element.setAttribute(property, arr[property]));
// noinspection JSUnusedGlobalSymbols
/** create DOM elements **/
let $_createDocumentFragment = () => document.createDocumentFragment();
let $_createElement = element_type => document.createElement(element_type);
// noinspection CommaExpressionJS
let $_createDIV = (html, element = $_createElement("DIV")) => (html && (element.innerHTML = html), element);
// noinspection CommaExpressionJS
let $_createDIV_withClass = (html, className, element = $_createDIV(html)) => (element.classList.add(className), element);
// noinspection CommaExpressionJS
let $_createDIV_with_id = (html, id, DIV = $_createDIV(html)) => ($_setAttribute(DIV, "id", id), DIV);
// noinspection CommaExpressionJS
let $_innerHTML = (element, html = $_emptyString) => element && (element.innerHTML = html, element); // return element
let $_innerHTMLById = (element_id, html) => {
let element = $_getElementById(element_id);
$_innerHTML(element, html);
return element; // return element
};
// noinspection JSUnusedGlobalSymbols
let $_replaceInnerHTML = (oldDiv, html) => {
let newDiv = oldDiv.cloneNode(false);
newDiv.innerHTML = html;
oldDiv.parentNode.replaceChild(newDiv, oldDiv);
};
// noinspection JSUnusedGlobalSymbols
let $_childElementCount = element => element && element.childElementCount;
let $_appendChild = (parent, child) => parent.appendChild(child);
// noinspection JSUnusedGlobalSymbols
let $_insertBefore = (parent, child, referenceNode) => parent.insertBefore(child, referenceNode);
// noinspection JSUnusedGlobalSymbols
let $_removeLastChild = parent => parent.removeChild(parent.lastElementChild);
let $_importNode = (nodeId) => document.importNode($_getElementById(nodeId).content, true);
let $_hideElement = element => element.style.display = 'none';
let $_showElement = (element, displaysetting = 'block') => element.style.display = displaysetting;
let $_classList = element => element.classList;
// noinspection JSUnusedGlobalSymbols
let $_classList_add = (element, classStr) => $_classList(element).add(classStr);
// toggle a className for N elements (selected/unselected)
let $_toggleClass = (element, className) => $_classList(element).toggle(className);
let $_toggleClasses = (elements, selectedElement, className) => elements.map(x => x.classList[x === selectedElement ? "add" : "remove"](className));
let $_setCSSproperty = (property, value, el = document.body) => el.style.setProperty(property, value);
//Chrome CSS Type Object model
// noinspection JSUnusedGlobalSymbols
let $_setattributeStyleMap = (property, value, el = document.body) => el.attributeStyleMap.set(property, value);
let $_setBackgroundColor = (el, color) => el.style.backgroundColor = color;
let $_Object_keys = x => Object.keys(x);
let $_style_display = (el, value = 'none') => el.style.display = value;
let $_addEventListener = (event, func) => window.addEventListener(event, func);
let $_localstorage_Get = (key, defaultvalue = false, stored = localStorage.getItem(key)) => stored ? stored : defaultvalue;
let $_localstorage_Set = (key, value) => localStorage.setItem(key, $_isString(value) ? value : $_JSONstringify(value));
// let $_colors: {
// "blue" : "#0000ff,#3232ff,#6666ff,#9999ff,#ccccff".split()
// };
//localstorage
class LocalStorageManager {
// noinspection JSUnusedGlobalSymbols
/**
*
* **/
static _log() {
$_log && $_log("LocalStorageManager.orangered", ...arguments);
}
static item(value) { // Map entry storage object
return {value, timestamp: new Date()}
}
static JSONconvert(value) {/** .parse or .stringify **/
return JSON[typeof value === 'string' ? 'parse' : 'stringify'](value);
}
constructor() {
this.memory_storage = new Map();
$_Object_keys(localStorage).forEach(key => this.set_memory_storage(key));
let size = 0;
$_Object_keys(localStorage).forEach(key => size += localStorage.getItem(key).length);
LocalStorageManager._log('total localStorage size:', size, 'bytes')
}
has(key) {
return this.memory_storage.has(key); // Map.get
}
set_memory_storage(key, value) {
return this.memory_storage.set(key, value ? LocalStorageManager.item(value) : localStorage.getItem(key));
}
delete(key) {
localStorage.removeItem(key);
return this.memory_storage.delete(key);
}
set(key, value, datatype = false, isString = typeof value === 'string') {
try {
let temp__savedPercentage = false;
let temp__rowcount = false;
if (!datatype && !isString) datatype = 'JSN';
switch (datatype) {
case 'JSN':
value = datatype + ":" + LocalStorageManager.JSONconvert(value);
break;
case 'CSV':
let csv = $_CSV_convert(value);
let JSONlength = LocalStorageManager.JSONconvert(value).length;
temp__savedPercentage = ~~((csv.length / JSONlength) * 100);
temp__rowcount = ~~value.length;
value = datatype + ":" + csv;
break;
default:
value = isString ? value : LocalStorageManager.JSONconvert(value);
break;
}
localStorage.setItem(key, value);
this.set_memory_storage(key, value);
LocalStorageManager._log("set:", key, temp__rowcount ? temp__rowcount + " rows," : "", value.length, "Bytes ", temp__savedPercentage ? `CSV = ${temp__savedPercentage}% reduction` : "");
} catch (e) {
console.error("set", key, value.length, '\n', e); // todo: catch QuotaExceeded Error
}
}
get(key, defaultvalue = false) { // localStorage.getItem
let stored = this.memory_storage.get(key) && this.memory_storage.get(key).value;
let value = localStorage.getItem(key);
if (value) {
switch (value.slice(0, 3)) {
case 'JSN':
value = JSON.parse(value.slice(4));
return value;
break;
case 'CSV':
value = $_CSV_convert(value.slice(4));
return value;
break;
default:
LocalStorageManager._log(key, stored, value);
}
return value;
}
//if (localstored) return localstored;
if (stored) return stored;
return defaultvalue;
}
getJSON(key) {
return LocalStorageManager.JSONconvert(this.get(key));
}
setJSON(key, value) {
thi.set(key, LocalStorageManager.JSONconvert(value));
}
}
$_LSM = new LocalStorageManager();
// var managed = $_LSM.storage.get(key);
// var get = $_LSM.get(key);
let $_localPath = (x, basePath = 'ITpings_connector.php?query=') => {
let uri = location.href.split('#')[0]; // discard routes
uri = uri.split`/`; // get endpoint from current uri location
uri.pop(); // discard filename
uri.push(basePath + x); // stick on basePath
uri = uri.join`/`;
return uri;
};
//region ========================================================== Application Constants / definitions
let $_app_custom_element_Namespace = "itpings-"; // W3C standard Custom Elements need their own Namespace
let $_app__QueryManager; // manage all (async) queries from/for multiple tables/charts (if A has just called for data X, then B can use it as well)
let $_app__Router; // Simple SPA router
let $_app_ITpings_data_tables = ['Temperature', 'Luminosity', 'Battery'];
let $_DEF = { // Single global, so properties can be mangled by Uglify
// matching definitions in PHP/MySQL
ID: "_pingid",
dev_id: "dev_id",
created: "created",
modulation: "modulation",
data_rate: "data_rate",
coding_rate: "coding_rate",
ITpings_devid: "_devid",
ITpings_result: "result",
ITpings_cached: "cached",
ITpings_time: "time",
sensor: "sensor",
LastSeen: "LastSeen",
MINUTE: "MINUTE",
HOUR: "HOUR",
DAY: "DAY",
WEEK: "WEEK",
MONTH: "MONTH",
YEAR: "YEAR",
THEAD: "THEAD",
TABLE: "TABLE",
TBODY: "TBODY"
};
/**
* Endpoints query=[endpoint]
* See F12 console 'Fetch API' references for clickable URIs
* **/
let $_app_single_PingID_endpoint = "PingID"; // Smallest payload 256 Bytes, but only gets max(_pingid)
let $_app_DB_IDs_endpoint = "IDs"; // All (new) IDs (only called when there is a new _pingid)
let ITpings_last_pingid = false; // last received _pingid
/**
* sensor names that can query data from PingedDevices
* **/
let ITPings_graphable_PingedDevices_Values = "frequency,snr,rssi,channel".split`,`;
/**
* With multiple tables displayed, auto scroll all tables to the same _pingid
* **/
let __synchronized_pingID_table_scrolling = false;
let __TEXT_QUERYMANAGER_CANT_REGISTER = " QueryManager can't register";
let __TEXT_CUSTOM_ELEMENT_CONSTRUCTOR = "CustomElement constructor";
let __TEXT_CUSTOM_ELEMENT_ATTRIBUTECHANGED = "CustomElement attributeChanged:";
let __TEXT_CUSTOM_ELEMENT_CONNECTED = "CustomeElement connectedCallback";
//endregion ======================================================= Application Constants / definitions
//region ========================================================== Application Functions
let $_hasResultArray = json => json && json.hasOwnProperty($_DEF.ITpings_result);
let $_isCachedJSON = json => json && json.hasOwnProperty($_DEF.ITpings_cached);
let $_getResultArray = json => json && json[$_DEF.ITpings_result];
let $_HTML_clickable_pingid = pingid => `<A target=_blank HREF=ITpings_connector.php?query=ping&_pingid=${pingid}>${pingid}</A><A target=_blank HREF=ITpings_connector.php?query=DeletePingID&_pingid=${pingid}> X </A>`;
let $_HTML_LoadingTitle = (x, y = "Loading: ", z = $_emptyString) => `<DIV class="loading">${y} ${x} ${z}</DIV>`;
//endregion ======================================================= Application Functions
(function (funcName = "$_ready", baseObj = window) {
// The public function name defaults to window.docReady
// but you can modify the last line of this function to pass in a different object or method name
// if you want to put them in a different namespace and those will be used instead of
// window.docReady(...)
let readyList = [];
let readyFired = false;
let readyEventHandlersInstalled = false;
// call this when the document is ready
// this function protects itself against being called more than once
function ready() {
if (!readyFired) {
// this must be set to true before we start calling callbacks
readyFired = true;
for (let i = 0; i < readyList.length; i++) {
// if a callback here happens to add new ready handlers,
// the docReady() function will see that it already fired
// and will schedule the callback to run right after
// this event loop finishes so all handlers will still execute
// in order and no new ones will be added to the readyList
// while we are processing the list
readyList[i].fn.call(window, readyList[i].ctx);
}
// allow any closures held by these functions to free
readyList = [];
}
}
function readyStateChange() {
if (document.readyState === "complete") ready();
}
// This is the one public interface: docReady(fn, context);
// the context argument is optional - if present, it will be passed as an argument to the callback
baseObj[funcName] = function (callback, context) {
if (typeof callback !== "function") throw new TypeError("callback for docReady(fn) must be a function");
// if ready has already fired, then just schedule the callback to fire asynchronously, but right away
if (readyFired) {
setTimeout(function () {
callback(context);
}, 1);
return;
} else {
// add the function and context to the list
readyList.push({fn: callback, ctx: context});
}
// if document already ready to go, schedule the ready function to run
// IE only safe when readyState is "complete", others safe when readyState is "interactive"
if (document.readyState === "complete" || (!document.attachEvent && document.readyState === "interactive")) {
window.setTimeout(ready, 1);
} else if (!readyEventHandlersInstalled) {
// otherwise if we don't have event handlers installed, install them
if (document.addEventListener) {
// first choice is DOMContentLoaded event
document.addEventListener("DOMContentLoaded", ready, false);
// backup is window load event
window.addEventListener("load", ready, false);
} else {
// must be IE
document.attachEvent("onreadystatechange", readyStateChange);
window.attachEvent("onload", ready);
}
readyEventHandlersInstalled = true;
}
}
}
)(); // modify this line to pass in your own method name and object for the method to be attached to
/**
* Fetch API wrapper, can handle cached (localstorage) data
* will fetch data if no cached data is available
*
* uri - full uri, see F12 console for clickable links
* cacheKey - string localstorage Key
* **/
let $_fetch = (uri, cacheKey = false) => { // Async/Await?
function _log() { // ES6 arrow functions can not do ...arguments!
$_log("Fetch API.firebrick", ...arguments);
}
let shortURI = uri.replace($_localPath($_emptyString), $_emptyString); // truncate local path
let isSinglePingID = uri.includes('query=' + $_app_single_PingID_endpoint);
let encodedURI = uri.replace(/ /g, '%20'); // can't use encodeURI(), it will encode existing %
if (!isSinglePingID) _log("Fetching from ", cacheKey ? "Cache:" + cacheKey : "Server", cacheKey ? "" : "\n" + encodedURI);
return new Promise((resolve, reject) => { // return Promise to calling function
if (cacheKey) { // localstorage string key
let json = $_LSM.get(cacheKey, {}); // get cached data from localstorage
// CSV from localStorage does not have result structure yet. todo: move this into localeStorageManager
let has_pingid = $_hasOwnProperty(json[0], $_DEF.ID);
if (!$_hasResultArray(json) && json.length > 0 && json[0] && has_pingid) { // first row has a _pingid key
_log('converting to ITpings json with result array');
json = {
result: json
}
}
if ($_hasResultArray(json)) { // if it has a "result" key
_log('Using ', $_length(json.result), ' results cached data for:', cacheKey); // it is cached data
//_log('first cached row:', json.result[0]);
resolve(json);
} else {
//todo get data from static CSV file
_log('No cache data for:', cacheKey); // no data
cacheKey = false; // continue with fetch in next if block
}
}
if (!cacheKey) {
fetch(uri) // async fetch
.then(response => {
if (response.ok) {
//todo check if data is CSV encoded data
return response.json();
} else {
$_log('$_fetch error ' + response.status + ' ' + response.statusText + ".red.white", uri, response);
return response;
}
})
.then(json => {
if ($_hasResultArray(json)) { // "result" key in json?
if (json.result) {
let JSONsize = $_JSONstringify(json).length;
$_log("Fetched (" + shortURI + ").firebrick", $_length(json.result), "rows , ", JSONsize, 'bytes', "\n", encodedURI);
} else {
$_log("Fetch Error.red", json.sql);
console.error(json.errors[0]);
console.error(json.errors);
}
} else {
// update UI for single ping value
if ($_isNumber(json)) {
ITpings_last_pingid = json;
$_getElementById('heartbeat_ping').innerHTML = $_HTML_clickable_pingid(json);
}
}
resolve(json)
})
.catch(error => {
reject($_log(error + '.red.yellow', shortURI));
console.error(error);
});
}
})
};
//endregion ======================================================= learning to code without jQuery, Underscore or Lodash
//region ========================================================== $_datetime functions, no need for Moment or Date-Fns
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
// noinspection JSCheckFunctionSignatures
let $_Date = (x = false) => x ? new Date(x) : new Date();
let $_Date_getTime = (x) => $_Date(x).getTime();
// noinspection JSUnusedGlobalSymbols
let $_isDate = x => Object.prototype.toString.call(x) === '[object Date]';
let $_dateLocale = navigator.language; // get browser(system) language
let $_dateFormat_Hmm = "H:mm";
let $_dateFormat_DMMM = "D MMM";
let $_dateFormat_DMMMHmm = "D MMM H:mm";
let $_date_Default_ShortDate = {month: 'short', day: 'numeric'}; // native JS .toLocaleDateString options
let $_date_Default_LongDate = {month: 'long', day: 'numeric', year: 'numeric'}; // according to locale: DD MMMM YYYY or MMMM DD YYYY
let $_dateTimeDefault = {hour: '2-digit', minute: '2-digit', hour12: false}; // 23:21
let $_dateEnsureDate = (date = $_emptyString) => $_isString(date) ? $_Date(date) : date;
let $_dateTimeStr = (date, options = $_dateTimeDefault, locale = $_dateLocale) => $_dateEnsureDate(date).toLocaleTimeString(locale, options);
/**
* date - date string or Date object
* format - (optional) format
* locale - (optional) language locale
* returns formatted string
* **/
function $_dateStr(date, format = $_dateFormat_DMMMHmm, locale = $_dateLocale) {
date = $_dateEnsureDate(date);
let localeDate = options => date.toLocaleDateString(locale, options); // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
let padded = date => ("0" + date).slice(-2); // pad 9 minutes to 09 minutes
if (format === $_dateFormat_DMMM) {
return localeDate($_date_Default_ShortDate);
} else if (format === $_dateFormat_Hmm) {
return padded(date.getHours()) + ":" + padded(date.getMinutes());
} else if (format === $_dateFormat_DMMMHmm) {
return $_dateStr(date, $_dateFormat_DMMM) + " " + $_dateTimeStr(date);
} else {
return localeDate(format) + " " + $_dateTimeStr(date);
}
}
/**
* date - date string or Date Object
* interval - (optional) interval in minutes (default) (day = * 1000 = 864e5)
* returns offset/interval
* **/
let $_dateSince_Interval = (toDate, fromDate = $_Date_getTime(), interval = 864e2) => Math.floor(($_Date_getTime(toDate) - fromDate) / interval); // 0=today , negative for past days, positive for future days
let $_dateMinutesSince = date => $_dateSince_Interval(date);
// noinspection JSUnusedGlobalSymbols
let $_dateDayssSince = (fromDate, toDate = null) => $_dateSince_Interval(fromDate, null, 864e5);
//endregion ======================================================= $_datetime functions, no need for Moment or Date-Fns
!(function (window, document, localStorage) { // minify globals inside IIFE
if (!window.customElements) { // detect Browser that do not support
window.setTimeout(function () {
document.body.innerHTML = "<h1>This Browser does not support <a href=https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements>W3C customElements</a> yet<br>Use Chrome, or FireFox (may 2018)</h1>";
}, 1000);
return;
}
// create extra Event listeners for debugging purposes
//https://developer.mozilla.org/en-US/docs/Web/Events
['DOMContentLoaded', 'hashchange', 'load', 'click', 'focus', 'blur'].map(evt => window.addEventListener(evt, () => $_log('Event: ' + evt, event ? event.target : $_emptyString)));
//region ========================================================== GEO functions
// nearbyGateways(52.4, 4.87); // latitude, longitude
function nearbyGateways(lat, lon, meters = 15000) {
fetch(`https://www.thethingsnetwork.org/gateway-data/location?latitude=${lat}&longitude=${lon}&distance=${meters}`)
.then(response => response.json())
.then(json => {
let $_Distance = (lat1, lon1, lat2, lon2, accuracy = 1e3) => { // Haversine distance
let M = Math, C = M.cos, P = M.PI / 180,
a = 0.5 - C((lat2 - lat1) * P) / 2 + C(lat1 * P) * C(lat2 * P) * (1 - C((lon2 - lon1) * P)) / 2;
return M.round(M.asin(M.sqrt(a)) * 12742 * accuracy) / accuracy;// 12742 = Earth radius KMs * 2
};
console.table(Object.keys(json).map(id => {
let gtw = json[id];
gtw.distance = $_Distance(lat, lon, gtw.lat = gtw.location.latitude, gtw.lon = gtw.location.longitude);
return gtw;
}), ["id", "owner", "description", "last_seen", "lat", "lon", "distance"]);
});
}
//endregion ======================================================= GEO functions
//region ========================================================== StyleManager : manage <STYLE> definitions in DOM
// TTN Node names get a distinct color in Tables and Graphs
class StyleManager {
// noinspection JSUnusedGlobalSymbols
static _log() {
$_log("Router.seagreen", ...arguments);
}
constructor(id) { //cheeky way of omitting let declaration, saving 4 bytes in Uglify
//let _StyleManager = this;
// Get a single (existing!!) STYLE definition from DOM (dynamically added STYLE tags are not available in the .styleSheets Object!)
// CSSStyleSheet does not have an id
this.STYLE = [...document.styleSheets].find(sheet => sheet.ownerNode["id"] === id);
this.devicesMap = $_newMap(); // _devid -> dev_id
this.deviceColor = $_newMap();
// 20 Distinct colors: https://sashat.me/2017/01/11/list-of-20-simple-distinct-colors/
this.colors = $_CSV2Array("#e6194b,#0082c8,#f58231,#911eb4,#46f0f0,#f032e6,#d2f53c,#fabebe,#008080,#e6beff,#aa6e28,#fffac8,#800000,#aaffc3,#808000,#ffd8b1,#000080,#808080,#ffe119");
}
addDevice(device) {
let _devid = device[$_DEF.ITpings_devid];
let dev_id = device[$_DEF.dev_id];
this.devicesMap.set(_devid, dev_id);
let color = this.getColor(dev_id);
$_log('DeviceColor: ' + _devid + " = " + dev_id + '.' + color);
}
getColor(dev_id) { // store distinct color PER device
let _StyleManager = this;
let color;
let deviceColor = _StyleManager.deviceColor;
if (parseInt(dev_id)) dev_id = _StyleManager.devicesMap.get(String(dev_id)); // Map key is a string, not a number
if (deviceColor.has(dev_id)) {
color = deviceColor.get(dev_id);
} else {
color = _StyleManager.colors.shift();
deviceColor.set(dev_id, color);
_StyleManager.STYLE.insertRule(`span[data-${$_DEF.dev_id}='${dev_id}']::before{background:${color}}`, 0);
}
return color;
}
}
//endregion ======================================================= StyleManager
//region ========================================================== QueryManager for all itpings-table & itpings-chart Custom Elements
/** display date/time **/
window.setInterval(() => {
$_innerHTMLById('heartbeat_time', $_dateStr($_Date(), $_date_Default_LongDate));
}, 5000); // half a minute update
/**
* Heartbeat - Polling Server for new data,
* first a single pingid, then each table/chart polls the server for new data (if required!)
*
* lower setting doesn't speed up because the single new pingid triggers a second (slower) request (eg. PingedDevices WHERE pingid > currentid )
* could be enhanced if the endpoint returns the whole _pingid record, but that requires refactoring of tables/chart
* **/
let __heartbeat_default = 500; // 0.5 second
let __heartbeat_blurred = 1000 * 60 * 5; // 5 minutes
let __heartbeat_msecs; // current heartbeat, polling the back-end for new data
let __heartbeat_windowInterval = 0;
let __setHeartbeat = new_heartbeat_msecs => {
__heartbeat_msecs = new_heartbeat_msecs; // global
let heartbeat_display = __heartbeat_msecs / 1000 + "s"; // display time in seconds or minutes
if (__heartbeat_msecs > 6000) heartbeat_display = __heartbeat_msecs / 60000 + "m";
$_log("Change Heartbeat:.orange.black", heartbeat_display);
$_innerHTMLById('heartbeat', heartbeat_display);
window.clearInterval(__heartbeat_windowInterval);
__heartbeat_windowInterval = window.setInterval(() => {
$_toggleClass($_getElementById('heartbeat_heart'), 'heartbeating');
$_app__QueryManager.pollServer($_app_single_PingID_endpoint); // Query Manager notifies all tables/charts
}, __heartbeat_msecs);
};
/**
* It would be loads of XHR request when every Table and Chart polled the backend for new data (most of the time for no new data)
* So, on display, Tables and Charts register themselves with the QueryManager (IQM) (by Query and PrimaryKey they use)
* The IQM polls the Server MySQL backend for new (Primary) Key values
* If there are new values the IQM tells the Component (Tables and Charts) to .pollServer and (they) retrieve the new Rows from the database themselves
* This XHR short-polling method works fine for your single client Dashboard, every poll is only 256 Bytes (per second)
* In a modern web-world this can be done with (more complex) WebSockets
* **/
class ITpings_Query_Manager {
static _log() {
$_log("QueryManager.purple", ...arguments);
}
constructor(_QM = this) {
_QM.maxid = 0; // record MAX(_pingid), higher value will cause all registered tables/graphs to update
_QM["pulse"] = $_newMap(); // store all tables/graphs query endpoints AND PrimaryKey fields here
}
register_for_pollServer(WC) {// register a new query
/**
* For each WebComponent, register which endpoint and db fieldname to poll
* see ?query=IDs endpoint
* **/
// let example_refresh: {
// "applications": {
// "_appid": "1"
// },
// "devices": {
// "_devid": "2"
// },
// "events": {
// "_pingid": "5417"
// },
// "gateways": {
// "_gtwid": "2"
// },
// "locations": {
// "_locid": "3"
// },
// "pings": {
// "_pingid": "5529"
// },
// "sensors": {
// "_sensorid": "14"
// }
// };
//get 'pulse' dataattribute, record tablename and idfield / value, reference DOM element
let _QM = this, datasrc, idfield, setting, _IQMap, datasrcMap;
setting = $_getAttribute(WC, "pulse"); // eg: pulse="SensorValues:_pingid"
if (setting) {
/**
* These CAN be configured as data arribute on the itpings-table tag
* <itpings-table query="PingedDevices" pulse="PingedDevices:_pingid">
* **/
[datasrc, idfield] = setting.split`:`; // ES6 Destructuring
} else { // determine from query="..."
/**
* Easier to (auto configure) query="xxx" name and the FIRST column name in the retrieved table
* <itpings-table query="PingedDevices">
* **/
datasrc = WC.query || $_getAttribute(WC, "query");
idfield = $_DEF.ID; // FIRST column in itpings-table
}
if (!datasrc) console.error(__TEXT_QUERYMANAGER_CANT_REGISTER, WC);
_IQMap = _QM["pulse"];
if (!_IQMap.has(datasrc)) _IQMap.set(datasrc, $_newMap()); // every datasrc gets its own Map (so 'can' store muliple PrimaryKeys
datasrcMap = _IQMap.get(datasrc); // Sorry... looking back I should have simplified this
if (!datasrcMap.has(idfield)) datasrcMap.set(idfield, $_newSet()); // I thought, too soon, about multiple dashboards and hundreds of devices
datasrcMap.get(idfield).add(WC);
ITpings_Query_Manager._log("register WC for pollServer event", "datasrc:" + datasrc, "idfield:" + idfield, _IQMap.get(datasrc));
return true;
}
/**
* Get maximum ID values from Database and notify/pulse the (registered) Custom Elements in the page
*/
pollServer(endpoint) {
let _QM = this;
$_fetch($_localPath(endpoint)) // QueryManager Poll an endpoint
.then(json => {
if (endpoint === $_app_single_PingID_endpoint) { // single value max(_pingid)
if (json > _QM.maxid) {
_QM.maxid = json; // if it is higher
_QM.pollServer($_app_DB_IDs_endpoint); //
} else {
//
}
} else {
ITpings_Query_Manager._log("heartbeat:" + __heartbeat_msecs, "Got highest _pingid values from Database: ►►►", json.maxids.pings._pingid, json);
_QM["pulse"].forEach((datasrcMap, datasrc) => {
datasrcMap.forEach(fieldSet => {
fieldSet.forEach(ITpings_element => {
let idvalue = json["maxids"]["pings"]["_pingid"]; //todo remove hardcoded _pingid
ITpings_Query_Manager._log(datasrc + ".pollServer(" + idvalue + ")");
ITpings_element.pollServer(idvalue);// method defined on CustomElement !!!
});
})
})
}
}).catch(e => console.error("pollServer", e));
}
}//class ITpings_Query_Manager
//endregion ======================================================= QueryManager for all itpings-table & itpings-chart Custom Elements
class TableRow {
constructor(row, columns = Object.keys(row), isTHEAD = false) {
this.data = row;
this.columns = columns;
this.element = this.DOMelement(row, isTHEAD);
this.requiredColumns = $_newSet();
}
DOMelement(row, isTHEAD = false) {
let TR = document.createElement('TR');
this.columns.forEach(name => {
try {
let TD = TR.insertCell();
let data_name = "data-" + name;
let value = row[name];
TR.setAttribute(data_name, value); // stick all values on the TR too
TD.setAttribute("data-column", name);
TD.setAttribute(data_name, value);
// only display a column if there are non-standard values
if (name === $_DEF.modulation && value !== "LORA") this.requiredColumns.add($_DEF.modulation);
if (name === $_DEF.coding_rate && value !== "4/5") this.requiredColumns.add($_DEF.coding_rate);
if (name === $_DEF.data_rate && value !== "SF7BW125") this.requiredColumns.add($_DEF.data_rate);
if (name === $_DEF.LastSeen) value = $_dateMinutesSince(value);
if (name === $_DEF.dev_id) value = `<SPAN data-column="${name}" data-${name}="${value}">${value}</SPAN>`;
if (name === $_DEF.ID) {
value = $_HTML_clickable_pingid(value);
// ** Only execute once PER Row/Table
// ** mouseover a pingid and all other tables scroll to the same pingid
if (__synchronized_pingID_table_scrolling) {
TR.addEventListener("mouseenter", function () {
let dataname = "data-" + $_DEF.ID; // _pingid
let _pingid = $_getAttribute(TR, dataname);
let saved_backgroundColor = TR.style.backgroundColor;
let selector = "itpings-table .data-table TR[" + dataname + "='" + _pingid + "']";
let TRs = $_querySelectorAll(selector); // get all TRs with the same _pingid defined
let hasMatchingTRs = $_length(TRs) > 1;
let TRcolor = hasMatchingTRs ? "chartreuse" : "lightcoral";
if (TRs) TRs.map(otherTR => { // scroll all Other TRs in Tables to the same _pingid
if (otherTR !== TR) { // for all other TRs: scroll TR into view
otherTR.savedScrollTop = otherTR.parentNode.parentNode.parentNode.scrollTop;
otherTR.scrollIntoView({"block": "center", "inline": "nearest"});
}
$_setBackgroundColor(otherTR, TRcolor); // highlight all matching _pingids
});
if (!TR.hasMouseLeaveListener) { // no eventlistner defined yet
TR.addEventListener("mouseleave", () =>
TRs.map(otherTR => {
$_setBackgroundColor(otherTR, saved_backgroundColor);
// window.setTimeout(() => {
// let parentDIV = otherTR.parentNode.parentNode.parentNode;
// let savedScrollTop = hasMatchingTRs ? otherTR.savedScrollTop : 0;
// parentDIV.scrollTop = savedScrollTop;
// }, 200)
}));
TR.hasMouseLeaveListener = true;
}
});
}
}
TD.innerHTML = isTHEAD ? name : value;
} catch (e) {
$_logerror(e);
}
});
return TR;
}
ageColor() {
try {
let colors = $_CSV2Array("#00FF00,#33FF66,#66FF99,#99FFCC,#CCFFFF,#FFFFFF");
let color_count = colors.length;
let idx = 0;
let row = this.rows[idx];
let property = x => $_hasOwnProperty(row, x) ? x : false;
/**
* time is the TTN Gateway UTC time, created is the MySQL server time. todo: calculate correct ping time
* for now we return the timestamp the DOM element was created
* **/
let timestamp = property('created') || property('time');
let minutes_since;
if (timestamp) {
do {
let row = this.rows[idx++];
if (row.TR) {
minutes_since = $_absolute($_dateMinutesSince(row[timestamp]));
row.TR.style.backgroundColor = colors[minutes_since];
}
} while (row.TR && minutes_since <= color_count);
}
} catch (e) {
$_logerror(e);
}
}
}
class TableManager {
// or pay 800$ for https://www.ag-grid.com/ag-grid-8-performance-hacks-for-javascript/
static _log() {
$_log("TableManager.gold.black", ...arguments);
}
constructor(customelement, rows) {
window.tm = this; // debugging
/** init columns to be displayed in TR row **/
let rowKeys = $_Object_keys(rows[0]); // keys from first object (row)
this.columns = [...rowKeys]; // add extra columns here