-
Notifications
You must be signed in to change notification settings - Fork 364
/
app.js
2977 lines (2746 loc) · 83.7 KB
/
app.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
/********************************************************************************
* Copyright (c) 2024 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* https://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v1.0 which is available at
* https://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
********************************************************************************/
'use strict';
const version = "Version 0.17.0, 15. May 2024";
let timeShift = 0;
function strip(value, head) {
if (value && value.startsWith(head)) {
return value.slice(head.length);
}
return null;
}
function conv(value, hexLen) {
if (value && value.match(/^[0-9a-fA-F]+$/)) {
let base = 0;
if (value.match(/^[1-9]\d*$/)) {
base = 10
} else if ((hexLen && value.length == hexLen) ||
(!hexLen && (value.length & 1) == 0)) {
base = 16;
}
if (base > 0) {
return Number.parseInt(value, base);
}
}
return value;
}
function getElement(page) {
if (!(page instanceof Element)) {
const dom = new DOMParser().parseFromString(page, 'text/html')
return dom.activeElement.firstChild;
} else {
return page;
}
}
function minOr(m, value) {
if (value == undefined || value == null) {
return m;
}
if (m == undefined || m == null) {
return value;
}
if (m < value) {
return m;
} else {
return value;
}
}
function maxOr(m, value) {
if (value == undefined || value == null) {
return m;
}
if (m == undefined || m == null) {
return value;
}
if (m > value) {
return m;
} else {
return value;
}
}
function compareItem(item1, item2) {
return (item1 < item2) ? -1 : (item1 > item2) ? 1 : 0;
}
function indexItem(sortedArray, item, fn = compareItem) {
let upper = sortedArray.length - 1;
if (upper < 0 || fn(sortedArray[upper], item) < 0) {
return ~(upper + 1);
}
let lower = 0;
while (lower <= upper) {
const index = (upper + lower) >> 1;
const cmp = fn(sortedArray[index], item);
if (cmp < 0) {
lower = index + 1;
} else if (cmp > 0) {
upper = index - 1;
} else {
return index;
}
}
return ~lower;
}
/* fn must return the distance! */
function indexNearestItem(sortedArray, item, fn) {
let pos = indexItem(sortedArray, item, fn);
if (pos < 0) {
const end = sortedArray.length - 1;
pos = ~pos;
if (pos >= end) {
pos = end;
} else if (pos > 0) {
const d1 = -fn(sortedArray[pos - 1], item);
const d2 = fn(sortedArray[pos], item);
if (d1 < d2) {
--pos;
}
}
}
return pos;
}
function insertItem(sortedArray, item, fn) {
const pos = indexItem(sortedArray, item, fn);
if (pos < 0) {
sortedArray.splice(~pos, 0, item);
}
return pos;
}
class S3Request {
constructor(id, key, region, endpoint, login, stateHandler) {
this.id = id.replace(/[/<>\n]/g, '');
this.key = key;
this.region = region ?? "us-east-1";
this.endpoint = endpoint ?? "";
this.login = login;
this.stateHandler = stateHandler;
this.startGroups = 0;
}
static hexDigit(c) {
if ('0'.charCodeAt(0) <= c && c <= '9'.charCodeAt(0)) {
return c - '0'.charCodeAt(0);
}
if ('a'.charCodeAt(0) <= c && c <= 'f'.charCodeAt(0)) {
return c - 'a'.charCodeAt(0) + 10;
}
if ('A'.charCodeAt(0) <= c && c <= 'F'.charCodeAt(0)) {
return c - 'A'.charCodeAt(0) + 10;
}
throw new Error(c + " is no hex-digit.")
}
static hexToBuffer(hex) {
if (hex.length & 1) {
throw new Error(hex.length + " is odd, must be even for hex.")
}
const result = new Uint8Array(hex.length / 2);
for (let i = 0; i < hex.length; i += 2) {
let b = (S3Request.hexDigit(hex.charCodeAt(i)) & 0xf) << 4;
b += (S3Request.hexDigit(hex.charCodeAt(i + 1)) & 0xf);
result[i / 2] = b;
}
return result;
}
static bufferToHex(buffer, hexChars = '0123456789ABCDEF', head) {
let result = '';
if (head) {
(new Uint8Array(buffer)).forEach((v) => { result += head; result += hexChars[v >> 4] + hexChars[v & 15]; });
} else {
(new Uint8Array(buffer)).forEach((v) => { result += hexChars[v >> 4] + hexChars[v & 15]; });
}
return result;
}
static bufferToHexLower(buffer) {
return S3Request.bufferToHex(buffer, '0123456789abcdef');
}
static async h256(data = new ArrayBuffer(0)) {
return window.crypto.subtle.digest("SHA-256", data);
}
static async h256Text(data) {
return S3Request.h256(new TextEncoder().encode(data));
}
static async hmac256(key, data) {
const hmackey = await window.crypto.subtle.importKey("raw", key, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
return window.crypto.subtle.sign("HMAC", hmackey, new TextEncoder().encode(data));
}
static isSignableHeader(key) {
const unsignableHeaders = [
'authorization',
'content-type',
'content-length',
'user-agent',
'presigned-expires',
'expect',
'x-amzn-trace-id'
];
if (key.indexOf('x-amz-') === 0) return true;
return unsignableHeaders.indexOf(key) < 0;
}
static uriEncode(value, keepSlash) {
const h = '0123456789ABCDEF';
let encoder;
let result = "";
for (let i = 0; i < value.length; i++) {
const c = value.charCodeAt(i);
const s = value.charAt(i);
if (c < 128) {
if ('%' == s) {
const hex = value.slice(i + 1, i + 3);
if (keepSlash && (hex == "2F" || hex == "2f")) {
result += "/";
} else {
result += s + hex;
}
i += 2;
} else if ('a' <= s && s <= 'z') {
result += s;
} else if ('A' <= s && s <= 'Z') {
result += s;
} else if ('0' <= s && s <= '9') {
result += s;
} else if ('-._~'.indexOf(s) >= 0) {
result += s;
} else if (keepSlash && '/' == s) {
result += s;
} else {
result += "%" + h[c >> 4] + h[c & 15];
}
} else {
encoder ??= new TextEncoder();
const bytes = encoder.encode(s);
result += S3Request.bufferToHex(bytes, h, "%");
}
}
return result;
}
static uriEncodeQueryParameter(parameter) {
let result = "";
if (parameter instanceof URLSearchParams) {
parameter.sort();
parameter.forEach((value, key) => {
result += S3Request.uriEncode(key) + "=" + S3Request.uriEncode(value) + "&";
});
result = result.slice(0, -1);
}
return result;
}
static uriEncodeHeader(host, headers) {
let keys = "";
let pairs = "";
let canoncialHeaders = [["host", host]];
for (const [key, value] of headers.entries()) {
const lkey = key.toLowerCase();
if (S3Request.isSignableHeader(lkey)) {
let v;
if (value instanceof Array) {
value.map((v) => v.trim());
v = value;
} else {
v = value.trim();
}
canoncialHeaders.push([lkey, v]);
}
}
canoncialHeaders.sort((a, b) => { return a[0] < b[0] ? -1 : 1; });
canoncialHeaders.forEach((h) => {
pairs += h[0] + ":";
let value = h[1];
if (value instanceof Array) {
for (let val of value) {
pairs += val + ",";
}
pairs = pairs.slice(0, -1);
} else {
pairs += value;
}
pairs += "\n";
keys += h[0] + ";";
});
keys = keys.slice(0, -1);
return [pairs, keys];
}
async getSigningKey(date) {
if (this.login) {
const key = this.login[date];
if (key) {
return key;
}
}
if (!this.key) {
let error = null;
if (this.login) {
error = new Error("Session expired! Login again.");
} else {
error = new Error("Missing credentials!");
}
error.login = 0;
throw error;
}
const key = new TextEncoder().encode("AWS4" + this.key);
const keyDate = await S3Request.hmac256(key, date);
const keyRegion = await S3Request.hmac256(keyDate, this.region);
const keyService = await S3Request.hmac256(keyRegion, "s3");
this.login = new Object();
this.login[date] = await S3Request.hmac256(keyService, "aws4_request")
return this.login[date];
}
async signedRequest(request, body) {
const uri = new URL(request.url);
const datetime = request.headers.get('x-amz-date');
const date = datetime.slice(0, 8);
const scope = date + "/" + this.region + "/s3/aws4_request";
const payloadHash = await S3Request.h256(body);
request.headers.set('x-amz-content-sha256', S3Request.bufferToHexLower(payloadHash));
const canonicalHeaders = S3Request.uriEncodeHeader(uri.host, request.headers);
let value = request.method + "\n";
value += S3Request.uriEncode(uri.pathname, true) + "\n";
value += S3Request.uriEncodeQueryParameter(uri.searchParams) + "\n";
value += canonicalHeaders[0] + "\n";
value += canonicalHeaders[1] + "\n";
value += request.headers.get('x-amz-content-sha256');
const hash = await S3Request.h256Text(value);
const stringToSign = 'AWS4-HMAC-SHA256\n' + datetime + "\n" + scope + "\n" + S3Request.bufferToHexLower(hash);
const key = await this.getSigningKey(date);
const sign = await S3Request.hmac256(key, stringToSign);
const cred = this.id + '/' + scope + ",SignedHeaders=" + canonicalHeaders[1] + ",Signature=" + S3Request.bufferToHexLower(sign)
request.headers.set('Authorization', 'AWS4-HMAC-SHA256 Credential=' + cred);
return request;
}
async getContent(response, url, optional) {
const stateHandler = this.stateHandler;
// console.log("Status: " + response.status);
if (response.status == 200) {
const text = await response.text();
if (url) {
console.log(url + ": " + text.length);
}
if (stateHandler) {
stateHandler(false, 0, 1, text.length);
}
return text ?? "";
} else if (response.status == 304) {
if (stateHandler) {
stateHandler(false, 0, 1, 0);
}
return "";
} else if (optional && response.status == 404) {
if (stateHandler) {
stateHandler(false, 0, 1, 0);
}
return null;
} else {
if (stateHandler) {
let errorText = await response.text();
const ct = response.headers.get("content-type");
if (errorText.length > 0 && ct) {
if (ct.startsWith("text/html")) {
const xml = new DOMParser().parseFromString(errorText, 'text/xml');
errorText = xml.firstChild.innerHTML;
} else if (ct.startsWith("application/xml")) {
const xml = new DOMParser().parseFromString(errorText, 'text/xml');
const message = xml.querySelector("Message");
if (message) {
errorText = message.textContent;
}
}
}
if (errorText) {
stateHandler(false, 0, 1, 0, errorText);
} else {
stateHandler(false, 0, 1, 0, response.statusText);
}
}
return null;
}
}
async getText(response, url, optional) {
const text = await this.getContent(response, url, optional);
if (text != null) {
return { headers: response.headers, text: text };
} else {
return null;
}
}
async getJson(response, url, optional) {
const text = await this.getContent(response, url, optional);
if (text) {
const json = JSON.parse(text);
return { headers: response.headers, json: json };
} else {
return null;
}
}
async getXml(response, url, optional) {
const text = await this.getContent(response, url, optional);
if (text) {
const dom = new DOMParser().parseFromString(text, 'text/xml');
return { headers: response.headers, xml: dom };
} else {
return null;
}
}
async fetch(url, now, etag) {
const stateHandler = this.stateHandler;
if (stateHandler) stateHandler(false, 1, 0, 0);
try {
if (!(now)) {
now = new Date(Date.now() - timeShift).toISOString().replace(/[-:]/g, '').replace(/\.\d+/, '');
}
const request = new Request(url, {
method: 'GET',
headers: {
"x-amz-date": now,
},
mode: 'cors',
cache: 'no-cache',
});
if (etag) {
request.headers.set("If-None-Match", etag);
}
const s3Request = await this.signedRequest(request);
return await fetch(s3Request);
} catch (error) {
if (error.message == "NetworkError when attempting to fetch resource." && this.id) {
error = new TypeError(`NetworkError when attempting to fetch resource with ${this.id.slice(0, 6)}...`);
}
console.error(error);
if (stateHandler) {
stateHandler(false, 0, 1, 0, error, error.login);
}
throw error;
}
}
async fetchText(url, etag, optional) {
const response = await this.fetch(url, null, etag);
return this.getText(response, url, optional);
}
async fetchJson(url, etag, optional) {
const response = await this.fetch(url, null, etag);
return this.getJson(response, url, optional);
}
async fetchXml(url, etag, optional) {
const response = await this.fetch(url, null, etag);
return this.getXml(response, url, optional);
}
static xmlList(xmlList, exp) {
let list = Array();
if (xmlList) {
xmlList.querySelectorAll(exp).forEach((e) => list.push(e.textContent));
}
return list;
}
static xmlLast(xmlList, exp) {
let last = null;
if (xmlList) {
xmlList.querySelectorAll(exp).forEach((e) => last = maxOr(last, e.textContent));
}
return last;
}
async fetchXmlList(key, startAfterKey, maxKeys) {
if (key) {
let uri = this.endpoint + "?list-type=2&prefix=" + key + "&delimiter=%2F";
if (startAfterKey) {
uri += "&start-after=" + startAfterKey;
}
if (maxKeys) {
uri += "&max-keys=" + maxKeys;
}
return this.fetchXml(uri);
}
return null;
}
async fetchXmlListNoDelimiter(key, startAfterKey, maxKeys) {
if (key) {
let uri = this.endpoint + "?list-type=2&prefix=" + key;
if (startAfterKey) {
uri += "&start-after=" + startAfterKey;
}
if (maxKeys) {
uri += "&max-keys=" + maxKeys;
}
return this.fetchXml(uri);
}
return null;
}
async fetchXmlListLast(key, exp) {
const xmlList = await this.fetchXmlList(key);
return S3Request.xmlLast(xmlList.xml, exp);
}
async fetchContent(key, etag, optional) {
if (key) {
return this.fetchText(this.endpoint + key, etag, optional);
} else {
return null;
}
}
async put(url, body, now) {
const stateHandler = this.stateHandler;
if (stateHandler) stateHandler(false, 1, 0, 0);
try {
if (!(now)) {
now = new Date(Date.now() - timeShift).toISOString().replace(/[-:]/g, '').replace(/\.\d+/, '');
}
const request = new Request(url, {
method: 'PUT',
headers: {
"x-amz-date": now,
"content-type": "text/plain; charset=UTF-8",
},
mode: 'cors',
cache: 'no-cache',
body: body,
});
const s3Request = await this.signedRequest(request, body);
return fetch(s3Request);
} catch (error) {
console.error(error);
if (stateHandler) {
stateHandler(false, 0, 1, 0, error, error.login);
}
throw error;
}
}
async putContent(key, content, now) {
const url = this.endpoint + key;
const response = await this.put(url, content, now);
this.stateHandler(false, 0, 0, content.length);
const text = await this.getContent(response, url);
if (text != null) {
return { headers: response.headers, text: text };
} else {
return null;
}
}
allStarted() {
const stateHandler = this.stateHandler;
if (stateHandler) {
if (this.startGroups > 0) {
this.startGroups--;
} else {
stateHandler(true, 0, 0, 0);
}
}
}
ignoreResponse() {
const stateHandler = this.stateHandler;
if (stateHandler) stateHandler(false, 0, 1, 0);
}
}
class ChartConfig {
constructor(regex, units, color, min, max, scale = 1) {
this.regex = regex;
this.units = units;
this.color = color;
this.min = min;
this.max = max;
this.scale = scale;
}
}
const dayInMillis = 24 * 60 * 60 * 1000;
// yyyy-mm-ddThh:mm:ss.SSSZ
const regexTimeEnding = /(\d{2,4}-\d{1,2}-\d{1,2}T\d{1,2}:\d{1,2}:\d{1,2})(\.\d{3})?Z$/;
const regexTimeHeader = /^(\d{2,4}-\d{1,2}-\d{1,2}T\d{1,2}:\d{1,2}:\d{1,2})(\.\d{3})?Z/;
const chartConfig = [
new ChartConfig(/\s([+-]?\d+)\smV/, "mV", "blue", 3400, 4300, 1000),
new ChartConfig(/mV\s+([+-]?\d+(\.\d+)?)\%/, "%", "navy", 20, 100),
new ChartConfig(/,\s*([+-]?\d+(\.\d+)?)(,([+-]?\d+(\.\d+)?))*\sC/, "°C", "red", 10, 40),
new ChartConfig(/,\s*([+-]?\d+(\.\d+)?)(,([+-]?\d+(\.\d+)?))*\s%H/, "%H", "green", 10, 80),
new ChartConfig(/,\s*([+-]?\d+(\.\d+)?)(,([+-]?\d+(\.\d+)?))*\shPa/, "hPa", "SkyBlue", 900, 1100),
new ChartConfig(/,\s*([+-]?\d+(\.\d+)?)(,([+-]?\d+(\.\d+)?))*\sQ/, "IAQ", "lightblue", 0, 500),
new ChartConfig(/,\s*RSRP:\s*([+-]?\d+(\.\d+)?)\sdBm/, "dBm", "orange", -125, -75),
new ChartConfig(/,\s*SNR:\s*([+-]?\d+(\.\d+)?)\sdB/, "dB", "gold", -15, 15),
new ChartConfig(/,\s*ENY:\s*([+-]?\d+(\.\d+)?)(\/([+-]?\d+(\.\d+)?))?\sm(As|C)/, "mAs", "DarkGoldenrod", 50, 400),
new ChartConfig(/,\s*ENY0:\s*([+-]?\d+(\.\d+)?)\smAs/, "mAs0", "tomato", 50, 400),
new ChartConfig(/,\s*CHA\s*([+-]?\d+(\.\d+)?)\skg/, "kg A", "olive", 0, 50),
new ChartConfig(/,\s*CHB\s*([+-]?\d+(\.\d+)?)\skg/, "kg B", "teal", 0, 50),
new ChartConfig(/,\s*Ext\.Bat\.:\s*([+-]?\d+(\.\d+)?)\smV/, "mV Ext.", "lime", 8000, 16000, 1000),
new ChartConfig(/,\s*RETRANS:\s*(\d+)/, "Retr.", "red", 0, 3, 0),
new ChartConfig(/,\s*RTT:\s*([+-]?\d+)\sms/, "ms", "salmon", 0, 60000, 1000),
];
function getChartConfigIndex(units) {
return chartConfig.findIndex((cfg) => cfg.units == units);
}
function addChartConfigValue(result, values, units) {
const i = getChartConfigIndex(units);
if (i >= 0 && i + 1 < values.length) {
const value = values[i + 1];
if (value != null) {
result.push(value + " " + chartConfig[i].units);
}
}
}
const defaultProviderMap = new Map();
defaultProviderMap.set("em", "EMnify");
defaultProviderMap.set("flolive.net", "Flo.Live");
defaultProviderMap.set("gigsky-02", "Flo*Live");
defaultProviderMap.set("globaldata.iot", "iBASIS");
defaultProviderMap.set("ibasis.iot", "iBASIS");
defaultProviderMap.set("internet.m2mportal.de", "DTAG");
defaultProviderMap.set("iot.1nce.net", "1nce");
defaultProviderMap.set("iot.melita.io", "Melita");
defaultProviderMap.set("iot.truphone.com", "TruPhone");
defaultProviderMap.set("onomondo", "Ono");
defaultProviderMap.set("public4.m2minternet.com", "Spider");
const providerMap = new Map();
function providerMapInit(newProviderMap) {
providerMap.clear();
newProviderMap.forEach((v, k) => {
providerMap.set(k, v);
if (k.length > 15) {
providerMap.set(k.slice(0, 15), v);
}
});
providerMap.forEach((v, k) => {
console.log(`'${k}' => '${v}'`);
});
}
providerMapInit(defaultProviderMap);
const radioTypeMap = new Map();
radioTypeMap.set("CAT-M1", "M1");
radioTypeMap.set("NB-IoT", "NB");
radioTypeMap.set("NTN", "NT");
radioTypeMap.set("none", "");
class DeviceData {
lastInterval = null;
lastModified = null;
updated = false;
status = null;
statusTime = null;
statusKey = null;
network = null;
pdn = null;
batteryLevel = null;
uptime = null;
startKey = null;
allKeys = Array();
loaded = new Map();
allTimes = Array();
allValues = Array();
rangeValues = Array();
constructor(key) {
this.key = key;
this.label = DeviceData.label(key);
}
toString() {
return this.label;
}
getDetails() {
let details = {};
details.uptime = this.uptime ? this.uptime.toString() : "";
details.pdn = this.pdn ?? "";
details.batteryLevel = this.batteryLevel;
details.plmn = "";
details.type = "";
details.net = "";
if (this.network) {
details.plmn = this.network.plmn;
details.type = radioTypeMap.get(this.network.type) ?? this.network.type;
if (details.plmn || details.type) {
details.net = details.plmn + "/" + details.type;
}
}
return details;
}
static label(key) {
const found = key.match(/([^\/]+)\/?$/);
if (found && found.length > 1) {
return found[1];
} else {
return key;
}
}
static getISODateFromKey(key, millis) {
const m = key.match(regexTimeEnding);
if (m) {
let date = m[1];
if (millis) {
if (m[2] && m[2].length > 0) {
date += m[2];
} else {
date += ".000";
}
}
return date + "Z";
} else {
const path = key.split('/');
if (path.length > 2) {
let time = path.at(-1);
if ((time.length <= 8) && millis) {
time += ".000";
} else if ((time.length > 8) && !millis) {
time = time.slice(0, 8);
}
return path.at(-2) + "T" + time + "Z";
} else {
return key;
}
}
}
static getTimeFromKey(key) {
const date = DeviceData.getISODateFromKey(key, true);
if (date != key) {
return new Date(date).getTime();
} else {
return null;
}
}
static getDev(list, key, fn) {
let dev = null;
const pos = indexItem(list, key, fn);
if (pos < 0) {
dev = new DeviceData(key);
list.splice(~pos, 0, dev);
} else {
dev = list[pos];
}
return dev;
}
static async loadDeviceList(list, groups, details) {
const xmlList = await s3.fetchXmlList("devices/");
if (xmlList) {
function addDevCmp(x, y) {
return (x.key < y) ? -1 : (x.key > y) ? 1 : 0;
}
const allJobs = Array();
const keys = Array();
const newList = Array();
xmlList.xml.querySelectorAll("CommonPrefixes>Prefix").forEach((e) => insertItem(keys, e.textContent));
xmlList.xml.querySelectorAll("Contents>Key").forEach((e) => insertItem(keys, e.textContent + "/"));
keys.forEach((e) => {
if (groups.length == 0 || groups.includes(DeviceData.label(e))) {
const dev = DeviceData.getDev(list, e, addDevCmp);
newList.push(dev);
allJobs.push(dev.readOverview(details));
}
});
s3.allStarted();
const results = await Promise.allSettled(allJobs);
let error = results.find((result) => result.reason);
return { deviceList: newList, error: error ? error.reason : null };
} else {
return { error: "No devices found!" };
}
}
findNearestValues(time) {
const range = this.rangeValues;
let pos = indexNearestItem(range, time, (x, y) => x[0] - y);
return range[pos];
}
findNearestTime(time, delta, index) {
const range = this.allTimes;
if (range && range.length > 0) {
let pos = 0;
if (time) {
pos = indexNearestItem(range, time, (x, y) => x[0] - y);
} else {
pos = indexItem(range, Date.now(), (x, y) => x[0] - y);
if (pos < 0) {
pos = ~pos;
if (delta < 0 && pos == range.length) {
--pos;
}
}
}
if (delta) {
pos += delta;
}
pos = Math.max(pos, 0);
pos = Math.min(pos, range.length - 1);
if (index) {
return pos;
} else {
return range[pos][0];
}
} else {
return -1;
}
}
async readOverview(details) {
const last = this.lastModified;
// limit to year 20xx, exclude "series"
const lastMessageKey = await this.fetchLastMessageKey();
if (lastMessageKey) {
this.lastModified = DeviceData.getISODateFromKey(lastMessageKey, false)
if (details) {
this.updated = last != this.lastModified;
return this.readStatus(lastMessageKey);
}
} else {
// fallback S3 "last modified"
const lastModified = await s3.fetchXmlListLast(this.key.slice(0, -1), "Contents>LastModified");
if (lastModified) {
this.lastModified = DeviceData.getISODateFromKey(lastModified, false)
}
}
if (!this.lastModified) {
// fallback to series
const lastKey = await s3.fetchXmlListLast(this.key + "series", "Contents>Key");
if (lastKey) {
this.lastModified = DeviceData.getISODateFromKey(lastKey, false);
}
}
this.updated = last && this.lastModified && last != this.lastModified;
}
async readStatus(key) {
this.status = null;
this.statusKey = null;
this.statusTime = null;
this.network = null;
this.pdn = null;
this.uptime = null;
this.batteryLevel = null;
const status = await s3.fetchContent(key, null, true);
if (status) {
this.statusTime = DeviceData.getTimeFromKey(key);
this.statusKey = key;
this.status = status.text;
if (this.statusTime == null) {
const last = status.headers.get("last-modified");
if (last) {
this.statusTime = new Date(last).getTime();
}
}
const regexBatteryLevel = /mV\s+(\d+(\.\d+)?)%/;
const lines = status.text.split(/\r?\n/);
const m = lines[0].match(/^\d+-/);
if (m) {
this.uptime = Number(m[0].slice(0, -1));
lines.shift();
}
lines.forEach((l) => {
const l2 = strip(l, "!") ?? l;
const net = strip(l2, "Network: ");
if (net) {
const nets = net.split(/,/);
this.network = {
type: nets.shift(),
mode: nets.shift(),
band: "",
plmn: "",
tac: "",
cell: ""
}
nets.forEach((f) => {
let value = strip(f, "Band ");
if (value) {
this.network.band = value;
return;
}
value = strip(f, "PLMN ");
if (value) {
this.network.plmn = value;
return;
}
value = strip(f, "#PLMN ");
if (value) {
this.network.plmn = value;
return;
}
value = strip(f, "TAC ");
if (value) {
this.network.tac = conv(value, 4);
return;
}
value = strip(f, "Cell ");
if (value) {
this.network.cell = conv(value, 8);
return;
}
});
}
const pdn = strip(l2, "PDN: ");
if (pdn) {
const parts = pdn.split(/,/);
if (parts.length > 1) {
this.pdn = providerMap.get(parts[0]) ?? parts[0];
}
}
const bat = l2.match(regexBatteryLevel);
if (bat && bat.length > 1) {
const n = Number(bat[1]);
if (n !== Number(n)) {
} else {
this.batteryLevel = n;
}
}
});
}
}
async fetchLastMessageKey() {
// limit to year 20xx, exclude "series"
const lastDayKey = await s3.fetchXmlListLast(this.key + "20", "CommonPrefixes>Prefix");
if (lastDayKey) {
return s3.fetchXmlListLast(lastDayKey, "Contents>Key");
} else {
return null;
}
}
async readStatusFrom(center) {
let statusKey = null;
if (this.allTimes.length > 0) {
const nearestTime = this.findNearestTime(center);
const dateTime = new Date(nearestTime).toISOString();
const date = dateTime.slice(0, 10);
const time = dateTime.slice(11, -1);
statusKey = this.key + date + "/" + time;
} else {
statusKey = await this.fetchLastMessageKey();
if (!statusKey) {
statusKey = this.key;
if (statusKey.endsWith("/")) {
statusKey = statusKey.slice(0, -1);
}
}
}
return this.readStatus(statusKey);
}
async readConfig() {
let changed = false;
const fetch = s3.fetchContent(this.key + "config", null, true);
s3.allStarted();
const config = await fetch;
if (config) {
changed = this.config != config.text;
this.config = config.text;
this.configTimestamp = config.headers.get("last-modified");
} else {
changed = this.config != null;