-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.js
executable file
·2149 lines (1845 loc) · 74.1 KB
/
main.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
/**
*
* ioBroker Meteoalarm Adapter
*
* (c) 2019 Alexander K <[email protected]>
*
* MIT License
*
*/
'use strict';
const utils = require('@iobroker/adapter-core');
//const request = require('request');
const moment = require('moment');
const util = require('util')
const turf = require('@turf/turf')
var parseString = require('xml2js').parseString;
var parseStringPromise = require('xml2js').parseStringPromise;
const stateAttr = require('./lib/stateAttr.js'); // State attribute definitions
const i18nHelper = require(`${__dirname}/lib/i18nHelper`);
const bent = require("bent");
const parseCSV = require('csv-parse');
const geoCodeJSON = require('./admin/geocodes.json')
const fs = require("fs");
const path = require('path');
const { hasUncaughtExceptionCaptureCallback, features } = require('process');
const { count } = require('console');
const { level } = require('./lib/stateAttr.js');
const { addAbortSignal } = require('stream');
var DescFilter1 = '';
var DescFilter2 = '';
var country = '';
//var countryConfig = '';
var geocodeLocationConfig = []
var geocodeCountry = ""
//var regionConfig = '';
var latConfig = '';
var longConfig = '';
var countEntries = 0;
var typeArray = [];
var urlArray = [];
var regionCSV = ""
//var regionName = ""
var xmlLanguage = ""
const warnMessages = {};
var tempFirst = true
var channelNames = []
var csvContent = [];
var alarmAll = []
var alarmOldIdentifier = []
var alarmOldArray = []
var urlAtom = ""
var locationArray = new Array()
let adapter;
let lang;
var noOfAlarmsAtEnd= 0
var noOfAlarmsAtStart = 0
var htmlCode = ""
var today = new Date();
var maxAlarmLevel = 1
var notificationAlarmArray = []
var imageSizeSetup = 0
var updateError = false
var initialDataLoaded = false
//var geoCodeLoaded = false
let Sentry;
let SentryIntegrations;
function initSentry(callback) {
if (!adapter.ioPack.common || !adapter.ioPack.common.plugins || !adapter.ioPack.common.plugins.sentry) {
return callback && callback();
}
const sentryConfig = adapter.ioPack.common.plugins.sentry;
if (!sentryConfig.dsn) {
adapter.log.warn('Invalid Sentry definition, no dsn provided. Disable error reporting');
return callback && callback();
}
// Require needed tooling
Sentry = require('@sentry/node');
SentryIntegrations = require('@sentry/integrations');
// By installing source map support, we get the original source
// locations in error messages
require('source-map-support').install();
let sentryPathWhitelist = [];
if (sentryConfig.pathWhitelist && Array.isArray(sentryConfig.pathWhitelist)) {
sentryPathWhitelist = sentryConfig.pathWhitelist;
}
if (adapter.pack.name && !sentryPathWhitelist.includes(adapter.pack.name)) {
sentryPathWhitelist.push(adapter.pack.name);
}
let sentryErrorBlacklist = [];
if (sentryConfig.errorBlacklist && Array.isArray(sentryConfig.errorBlacklist)) {
sentryErrorBlacklist = sentryConfig.errorBlacklist;
}
if (!sentryErrorBlacklist.includes('SyntaxError')) {
sentryErrorBlacklist.push('SyntaxError');
}
Sentry.init({
release: adapter.pack.name + '@' + adapter.pack.version,
dsn: sentryConfig.dsn,
integrations: [
new SentryIntegrations.Dedupe()
]
});
Sentry.configureScope(scope => {
scope.setTag('version', adapter.common.installedVersion || adapter.common.version);
if (adapter.common.installedFrom) {
scope.setTag('installedFrom', adapter.common.installedFrom);
}
else {
scope.setTag('installedFrom', adapter.common.installedVersion || adapter.common.version);
}
scope.addEventProcessor(function(event, hint) {
// Try to filter out some events
if (event.exception && event.exception.values && event.exception.values[0]) {
const eventData = event.exception.values[0];
// if error type is one from blacklist we ignore this error
if (eventData.type && sentryErrorBlacklist.includes(eventData.type)) {
return null;
}
if (eventData.stacktrace && eventData.stacktrace.frames && Array.isArray(eventData.stacktrace.frames) && eventData.stacktrace.frames.length) {
// if last exception frame is from an nodejs internal method we ignore this error
if (eventData.stacktrace.frames[eventData.stacktrace.frames.length - 1].filename && (eventData.stacktrace.frames[eventData.stacktrace.frames.length - 1].filename.startsWith('internal/') || eventData.stacktrace.frames[eventData.stacktrace.frames.length - 1].filename.startsWith('Module.'))) {
return null;
}
// Check if any entry is whitelisted from pathWhitelist
const whitelisted = eventData.stacktrace.frames.find(frame => {
if (frame.function && frame.function.startsWith('Module.')) {
return false;
}
if (frame.filename && frame.filename.startsWith('internal/')) {
return false;
}
if (frame.filename && !sentryPathWhitelist.find(path => path && path.length && frame.filename.includes(path))) {
return false;
}
return true;
});
if (!whitelisted) {
return null;
}
}
}
return event;
});
adapter.getForeignObject('system.config', (err, obj) => {
if (obj && obj.common && obj.common.diag !== 'none') {
adapter.getForeignObject('system.meta.uuid', (err, obj) => {
// create uuid
if (!err && obj) {
Sentry.configureScope(scope => {
scope.setUser({
id: obj.native.uuid
});
});
}
callback && callback();
});
}
else {
callback && callback();
}
});
});
}
//var Interval
function startAdapter(options) {
options = options || {};
Object.assign(options, {
name: 'meteoalarm',
useFormatDate: true,
ready: function() {
//main()
}
});
adapter = new utils.Adapter(options);
adapter.on(`unload`, callback => {
//clearInterval(Interval);
callback && callback();
});
adapter.on('ready', function() {
if (adapter.supportsFeature && adapter.supportsFeature('PLUGINS')) {
const sentryInstance = adapter.getPluginInstance('sentry');
if (sentryInstance) {
Sentry = sentryInstance.getSentryObject();
}
main();
}
else {
initSentry(main);
}
});
return adapter;
}
function main() {
getData()
}
function initialSetup(){
// run once when adapter starts
adapter.getForeignObject('system.config', (err, systemConfig) => {
if (!systemConfig.common.language){
lang = 'en'
}
else{
lang = systemConfig.common.language
}
})
latConfig = adapter.config.lat
longConfig = adapter.config.long
locationArray = adapter.config.geocode
geocodeLocationConfig = adapter.config.geocodeLocation
geocodeCountry = adapter.config.geocodeCountry
if (geocodeCountry == ''){
// could be the case for the people who tested version 3.0.0
geocodeCountry = locationArray[0]+locationArray[1]
}
// check if there is a space after the comma, and if not, add it
/*
if (geocodeLocationConfig.indexOf(',') > -1)
{
let indexFind = geocodeLocationConfig.indexOf(',')
if (geocodeLocationConfig.substring(indexFind+1, indexFind+2) != ' '){
geocodeLocationConfig = geocodeLocationConfig.substring(0,indexFind) + ', ' +
}
adapter.log.debug('TTT: ' + geocodeLocationConfig.substring(indexFind+1, indexFind+2))
//if ()
}
*/
imageSizeSetup = Number(adapter.config.imageSize)
adapter.log.debug('0.0 Initial setup loaded')
}
async function getData(){
alarmAll = []
if (!initialDataLoaded){
initialSetup()
initialDataLoaded = true
}
if (geocodeCountry == ""|| !geocodeCountry || latConfig == "" || !latConfig ||longConfig == ""|| !longConfig || !locationArray){
adapter.log.error('0.1 Please maintain country, geocode and location in setup!')
let htmlCode = '<table style="border-collapse: collapse; width: 100%;" border="1"><tbody><tr>'
htmlCode += '<td style="width: 100%; background-color: #fc3d03;">Please maintain country and location in setup!</td></tr></tbody></table>'
await Promise.all([
adapter.setStateAsync({device: '' , channel: '',state: 'level'}, {val: 0, ack: true}),
adapter.setStateAsync({device: '' , channel: '',state: 'htmlToday'}, {val: htmlCode, ack: true}),
adapter.setStateAsync({device: '' , channel: '',state: 'noOfAlarms'}, {val: 0, ack: true}),
adapter.setStateAsync({device: '' , channel: '',state: 'JSON'}, {val: '', ack: true}),
adapter.setStateAsync({device: '' , channel: '',state: 'location'}, {val: 'Check Setup!', ack: true})
])
adapter.terminate ? adapter.terminate(0) : process.exit(0);
}
else{
adapter.log.debug('0.1 Setup found: country ' + geocodeCountry + ' with geocode(s) ' + locationArray + ' for location ' + geocodeLocationConfig+ ' and Lat ' + latConfig + ' Long ' + longConfig )
if (Sentry){
adapter.log.debug('Sentry aktiv - Breadcrumb gesetzt')
Sentry.addBreadcrumb({
category: "info",
message: 'Country ' + geocodeCountry + ', Location '+ latConfig + ' - ' + longConfig,
level: "info",
});
}
/*
if (!geoCodeLoaded){
findGeoCode()
geoCodeLoaded = true
adapter.log.debug('0.2: Geocode loaded. Result: ' + locationArray)
}
*/
urlAtom = getCountryLink(geocodeCountry)
xmlLanguage = getXMLLanguage(geocodeCountry)
if (xmlLanguage == ""){
xmlLanguage = 'en-GB'
}
adapter.log.debug('0.3 XML Language: ' + xmlLanguage)
const checkState = await adapter.getStateAsync('weatherMapCountry')
if (checkState != null ){
adapter.log.debug('0.3: Cleaning up old objects');
const cleaned = await cleanupOld()
}
const csv = await getCSVData()
const temp = await adapter.getStateAsync('noOfAlarms')
if (temp){
noOfAlarmsAtStart = temp.val
}
adapter.log.debug('0.4: Existing alarm objects at adapter start: ' + noOfAlarmsAtStart)
const temp2 = await saveAlarmNamesForLater()
for (const alarmLoop of alarmOldIdentifier) {
const temp1 = await saveAlarmsForLater(alarmLoop)
};
adapter.log.debug('1: Parsed CSV File')
adapter.log.debug('2: Request Atom from ' + urlAtom )
const getJSON = bent('string')
let xmlAtom
try {
xmlAtom = await getJSON(urlAtom)
} catch (err){
adapter.log.warn('2.1: Atom URL ' + urlAtom + ' not available - error ' + err)
adapter.terminate ? adapter.terminate(0) : process.exit(0);
}
if (xmlAtom){
adapter.log.debug('3: Received Atom')
parseString(xmlAtom, {
//mergeAttrs: true
explicitArray: false
},
function (err, result) {
if (err) {
adapter.log.error("Fehler: " + err);
adapter.terminate ? adapter.terminate(0) : process.exit(0);
} else {
adapter.log.debug('4: Process Atom')
var newdate = moment(new Date()).local().format('DD.MM.YYYY HH:mm')
adapter.setState({device: '' , channel: '',state: 'lastUpdate'}, {val: newdate, ack: true});
//adapter.log.debug('4.1 Content: ' + util.inspect(result.feed.entry, {showHidden: false, depth: null, colors: true}))
if (result.feed.entry){
if (result.feed.entry[0]){
adapter.log.debug('4.1.1: Check Entries')
checkRelevante(result.feed.entry)
}
else {
// try to fix the damaged xml
adapter.log.debug('4.2.1 tried to fix xml')
let newObject = [result.feed.entry]
if (newObject[0]){
adapter.log.debug('4.2.2 new object after fixing: ' + util.inspect(newObject, {showHidden: false, depth: null, colors: true}))
checkRelevante(newObject)
}
}
}
}
});
}
// continue now to request details
var countEntries = 0
//adapter.log.debug('Object Result: ' + util.inspect(urlArray, {showHidden: false, depth: null}))
urlArray.sort(function(a, b) {
var keyA = new Date(a.effective),
keyB = new Date(b.effective);
// Compare the 2 dates
if (keyA < keyB) return -1;
if (keyA > keyB) return 1;
return 0;
});
//adapter.log.debug('Object Sorted Result: ' + util.inspect(urlArray, {showHidden: false, depth: null}))
adapter.log.debug('5: Processed Atom')
var countTotalURLs = urlArray.length
adapter.log.debug('5.1 Found ' + countTotalURLs + ' URLs')
var countURL = 0
var detailsType = ""
var detailsIdentifier = ""
var detailsReference = ""
var detailssent = ""
for (var i = 0, l = urlArray.length; i < l; i++){
countURL += 1
var jsonResult;
var awarenesstype = ""
adapter.log.debug('6: Request Details from URL ' + countURL + ': ' + urlArray[i].url)
const getJSON1 = bent('string')
let xmlDetails
try {
xmlDetails = await getJSON1(urlArray[i].url)
} catch (err){
adapter.log.debug('6.1: Details URL ' + urlArray[i].url + ' not valid any more - error ' + err)
updateError = true
}
var typeRelevant = false
if (xmlDetails ){
// Just go here if Request for Details is successful
adapter.log.debug('7: Received Details for URL ' + countURL)
parseString(xmlDetails, {
explicitArray: false
},
function (err, result) {
if (err) {
adapter.log.error("Fehler: " + err);
adapter.terminate ? adapter.terminate(0) : process.exit(0);
} else {
var info = []
if (result.alert.info[0]){
info = result.alert.info
}
else {
info = [result.alert.info]
}
detailsType= result.alert.msgType
detailsIdentifier = result.alert.identifier
detailsIdentifier = detailsIdentifier.replace(/\./g,'') // remove dots
detailssent = result.alert.sent
if (detailsType != "Alert" && result.alert.references != ""){
detailsReference = result.alert.references
var searchTerm = ","
const indexOfFirstComma = detailsReference.indexOf(searchTerm);
const indexOfSecondComma = detailsReference.indexOf(searchTerm, indexOfFirstComma +1);
detailsReference = detailsReference.substring(indexOfFirstComma +1,indexOfSecondComma)
detailsReference = detailsReference.replace(/\./g,'') // remove dots
}
for (var j = 0, l = info.length; j < l; j++){
var element = info[j]
if (element.language == xmlLanguage){
element.parameter.forEach(function (parameter){
if (parameter.valueName == "awareness_type") {
awarenesstype =parameter.value
var n = awarenesstype.indexOf(";");
awarenesstype = awarenesstype.substring(0, n)
typeRelevant = checkTypeRelevant(awarenesstype,"general")
//adapter.log.debug('Alarm ' + countURL + ' with type ' + awarenesstype + ' relevant: ' + typeRelevant)
}
})
jsonResult = element
}
}
}
});
}
if (jsonResult && typeRelevant){
countEntries += 1
const promises = await processDetails(jsonResult,countEntries,detailsType,detailsIdentifier,detailsReference,detailssent)
adapter.log.debug('8: Processed Details for Alarm ' + countURL)
}
}
//const widget = await createHTMLWidget()
adapter.log.debug('9: Checking for duplicate alarms')
adapter.log.debug('9.0.1 alarmAll Array before removing duplicates: ' + JSON.stringify(alarmAll))
checkDuplicates()
//const created = await createAlarms(countEntries)
// adapter.log.debug('8: Alarm States created for Alarm ' + countURL + ' type: ' + awarenesstype)
notificationAlarmArray = []
adapter.log.debug('10: Create alarm states')
for (var j = 0, l = alarmAll.length; j < l; j++){
//adapter.log.debug('10.TEMP: level= ' + alarmAll[j].Level)
if (checkRelevanceAlarmLevel(String(alarmAll[j].Level),"general","")){
const promises = await fillAlarm(alarmAll, j)
}
}
adapter.log.debug('10.2: Created alarm states')
adapter.log.debug('11: Cleaning up obsolete alarms')
if (!updateError){
const clean = await cleanObsoleteAlarms(alarmAll)
adapter.log.debug('11.1: Cleaned up obsolete alarms')
}
adapter.log.debug('12: Creating HTML Widget')
htmlCode = ''
var JSONAll = []
var warningCount = 0
if (channelNames.length >= 1){
htmlCode += '<table style="border-collapse: collapse; width: 100%;"><tbody>'
for (const channelLoop of channelNames) {
warningCount += 1
var path = 'alarms.' + channelLoop
var colorHTML = ''
let event = await adapter.getStateAsync(path + '.event')
let headline = await adapter.getStateAsync(path + '.headline')
let description = await adapter.getStateAsync(path + '.description');
let icon = await adapter.getStateAsync(path + '.icon');
let color = await adapter.getStateAsync(path + '.color');
let effectiveDate = await adapter.getStateAsync(path + '.effective');
let expiresDate = await adapter.getStateAsync(path + '.expires');
let level = await adapter.getStateAsync(path + '.level');
let alarmType = await adapter.getStateAsync(path + '.typeText');
if (color && color.val){
if (!adapter.config.noBackgroundColor){
colorHTML = 'background-color: ' + color.val
}
}
if (level && level.val){
if (level.val > maxAlarmLevel){
maxAlarmLevel = Number(level.val)
}
}
if (!adapter.config.noIcons){
// Dummy cell to move picture away from the left side
htmlCode += '<tr><td style="width: 1%; border-style: none; ' + colorHTML + '"></td>'
htmlCode += '<td style="width: 9%; border-style: none; ' + colorHTML + '">'
htmlCode += '<img style="display:block;"'
var imageSize = ''
if (icon && icon.val){
switch (imageSizeSetup) {
case 0:
imageSize = ' width="20" height="20"';
break;
case 1:
imageSize = ' width="35" height="35"';
break;
case 2:
imageSize = ' width="50" height="50"';
break;
default:
imageSize = ' width="35" height="35"';
break;
}
//adapter.log.debug('Image Size: ' + imageSizeSetup + ' -> Result: ' + imageSize)
htmlCode += imageSize
htmlCode += ' alt="Warningimmage" src="' + icon.val + '"/>'
}
htmlCode += '</td>'
}
htmlCode += '<td style="width: 90%; border-style: none; ' + colorHTML + '">'
if (headline && headline.val){
adapter.log.debug('12.1: Added Alarm to widget for ' + headline.val)
htmlCode += '<h4 style = "margin-top: 5px;margin-bottom: 1px;">' + headline.val + ': '
}
if (effectiveDate && effectiveDate.val && expiresDate && expiresDate.val){
htmlCode += getAlarmTime(effectiveDate.val, expiresDate.val) + '</h4>'
}
if (description && description.val){
htmlCode += description.val
}
htmlCode += '</td></tr>'
if (effectiveDate && effectiveDate.val && expiresDate && expiresDate.val){
JSONAll.push(
{
Event: event.val,
Description: description.val,
Level: level.val,
Effective: getAlarmTime(effectiveDate.val, expiresDate.val),
Icon: icon.val,
AlarmType: alarmType.val
}
);
}
}
}
else{
// No Alarm Found
htmlCode += '<table style="border-collapse: collapse; width: 100%;"><tbody>'
htmlCode += '<tr><td style= "border-style: none; '
if (!adapter.config.noBackgroundColor){
htmlCode += 'background-color: ' + getColor('1')
}
htmlCode += '">' + getLevelName('1')
htmlCode += '</td></tr>'
maxAlarmLevel = 1
}
if (htmlCode){
htmlCode += '</tbody></table>'
}
// Check if no alarms are found, then add "no alarm found"
if (JSONAll.length == 0){
JSONAll.push(
{
Event: "",
Description: getLevelName('1'),
Level: "1",
Effective: "",
Icon: ""
}
);
}
noOfAlarmsAtEnd = warningCount
await Promise.all([
adapter.setStateAsync({device: '' , channel: '',state: 'level'}, {val: maxAlarmLevel, ack: true}),
adapter.setStateAsync({device: '' , channel: '',state: 'htmlToday'}, {val: htmlCode, ack: true}),
adapter.setStateAsync({device: '' , channel: '',state: 'location'}, {val: geocodeLocationConfig, ack: true}),
adapter.setStateAsync({device: '' , channel: '',state: 'link'}, {val: urlAtom, ack: true}),
adapter.setStateAsync({device: '' , channel: '',state: 'color'}, {val: getColor(maxAlarmLevel.toString()), ack: true}),
adapter.setStateAsync({device: '' , channel: '',state: 'noOfAlarms'}, {val: warningCount, ack: true}),
adapter.setStateAsync({device: '' , channel: '',state: 'JSON'}, {val: JSON.stringify(JSONAll), ack: true})
])
adapter.log.debug('13: Set State for Widget')
adapter.log.debug('14: Processing notifications')
// Important, also go in there if no notifications are valid, because it could be that we need to trigger the "All warnings done" message
const promises = await processNotifications(alarmAll)
adapter.log.debug('15: All Done')
if (geocodeLocationConfig){
adapter.log.info('15.1: Updated Weather Alarms for ' + geocodeLocationConfig + ' -> ' + warningCount + ' alarm(s) found')
}
adapter.terminate ? adapter.terminate('All data processed. Adapter stopped until next scheduled process.') : process.exit(0);
}
}
function checkDuplicates(){
var alarmAllChecked = []
// 1. check for duplicate entries of type Alarm with the same Type, Level, Onset and Expires Date -> saved in Alarm_Key
for(var i = 0; i < alarmAll.length; i += 1) {
if (alarmAll[i].Alarm_Type == "Alert")
{
let check = alarmAllChecked.some(function(item) {
return item.Alarm_Key === alarmAll[i].Alarm_Key})
if (!check){
alarmAllChecked.push(alarmAll[i])
}
}
else{
alarmAllChecked.push(alarmAll[i])
}
}
//2. Check for Alarmupdates, duplicate updates and cancles
alarmAll = alarmAllChecked
adapter.log.debug('9.1 Finished checking alerts - ' + alarmAll.length + ' relevant alarm(s)')
//adapter.log.debug('9.3 alarmAll Array after removing duplicates: ' + JSON.stringify(alarmAll))
//adapter.log.debug('9.3.1 alarmAll sorted by sent1 date:' + JSON.stringify(alarmAll.sort((a, b) => a.Alarm_Sent - b.Alarm_Sent)))
}
function createPolyDataString(PolyDataToConvert){
var result = []
var first = true
var i = 0
var lat = ''
var long = ''
do {
var loc = PolyDataToConvert.indexOf(' ')
var countComma = (PolyDataToConvert.match(/,/g) || []).length;
var lengthpolyDataToConvert = PolyDataToConvert.length
var tempString = PolyDataToConvert.substring(0, loc)
var locComma = tempString.indexOf(',')
if (countComma >1){
// still multiple objects
PolyDataToConvert = PolyDataToConvert.substring(loc+1,lengthpolyDataToConvert)
long = tempString.substring(locComma+1,tempString.length)
lat = tempString.substring(0,locComma)
i ++
result.push([long, lat ])
}
else{
//last object
var locComma = PolyDataToConvert.indexOf(',')
var locComma = tempString.indexOf(',')
var longLast = PolyDataToConvert.substring(locComma+1,PolyDataToConvert.length)
var latLast = PolyDataToConvert.substring(0,locComma)
if (longLast != long && latLast != lat){
result.push([long, lat ])
}
PolyDataToConvert = ''
}
lengthpolyDataToConvert = PolyDataToConvert.length
} while (lengthpolyDataToConvert > 1);
return result
}
function checkIfInPoly(polyData){
var polyArray = createPolyDataString(polyData)
var myLoc = {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates":
[longConfig, latConfig]
}
};
let i = 0;
let pathArray = [];
while (i < polyArray.length) {
var lat = polyArray[i][0]
var long = polyArray[i][1]
pathArray.push([Number(lat), Number(long)])
i++;
}
var poly = {
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates":
[pathArray]
}
}
var isInside = turf.booleanPointInPolygon(myLoc, poly);
return isInside
}
function checkRelevante(entry){
var i = 0
var now = new Date();
entry.forEach(function (element){
var expiresDate = new Date(element['cap:expires']);
var effectiveDate = new Date(element['cap:onset']);
var messagetype = ""
var messagetypeRelevant = false
if (element['cap:message_type']){
messagetype = element['cap:message_type']
}
// Ignore Cancles
if (messagetype == "Alert"){
// show Alert only if no Update and no cancle found
messagetypeRelevant = true
}
if (messagetype == "Update"){
// Show all updates
messagetypeRelevant = true
}
var locationRelevant = false
if (element['cap:geocode'] && element['cap:geocode'].valueName ){
locationRelevant = checkLocation(element['cap:geocode'].valueName , element['cap:geocode'].value)
}
if (element['cap:polygon']) {
// found polygon
let polygon = element['cap:polygon']
var areaDesc = ''
if (element['cap:areaDesc']) {
areaDesc = element['cap:areaDesc']
}
locationRelevant = checkIfInPoly(polygon)
if (locationRelevant){
adapter.log.debug('4.1.2: Found relevant polygon warning for location ' + areaDesc)
}
}
var statusRelevant = false
if (element['cap:status'] == 'Actual'){
statusRelevant = true
}
var given = moment(effectiveDate);
var current = moment().startOf('day');
var daysDifference = moment.duration(given.diff(current)).asDays()
var dateRelevant = false
if ((expiresDate >= now)&&(daysDifference < 2)){
dateRelevant = true
}
var eventType = element['cap:event']
if (locationRelevant){
//adapter.log.debug('4.1.2: Check Result: dateRelevant = ' + dateRelevant + "statusrelevant= " + statusRelevant + " messagetyperelevant = " + messagetypeRelevant )
}
if (locationRelevant && (dateRelevant) && statusRelevant && messagetypeRelevant){
for(var i = 0; i < element.link.length; i += 1) {
//adapter.log.debug('4.1.1: Link ' + i + ': ' + element.link[i].$.href)
if (element.link[i].$.type){
//adapter.log.debug('4.1.1: Typ ' + i + ': ' + element.link[i].$.type)
if (element.link[i].$.type == 'application/cap+xml'){
var detailsLink = element.link[i].$.href
}
}
}
adapter.log.debug('4.2: Warning found: ' + detailsLink + ' of message type ' + messagetype)
let obj = {
"id": i,
"event": eventType,
"url": detailsLink,
"effective": effectiveDate,
"expires": expiresDate
}
urlArray.push(obj)
i += 1;
}
});
adapter.log.debug('4.2: Checked relevance, found ' + urlArray.length + ' relevant alarms')
}
function checkLocation(type,locationValue){
//check which type it is and if it is relevant for us
if (type == "EMMA_ID"){
return locationArray.includes(locationValue)
}
else{
var successful = false
for(var i = 0; i < csvContent.length; i += 1) {
if((locationArray.includes(csvContent[i][0])) && (csvContent[i][2] == type) ) {
if (locationValue == csvContent[i][1] ){
successful = true
}
}
}
return successful
}
}
function getAlarmTime(onset,expires){
var expiresDate = new Date(expires)
var onsetDate = new Date(onset)
var dateString = ''
var expiresToday = today.toDateString() == expiresDate.toDateString()
var onsetToday = today.toDateString() == onsetDate.toDateString()
var expiresDay = moment(expires).locale(lang).format("ddd")
var onsetDay = moment(onset).locale(lang).format("ddd")
//if (expiresToday && onsetToday){
if (expiresDate.toDateString() == onsetDate.toDateString()){
if (adapter.config.dayInWords) {
dateString = dateDifferenceInWord(onsetDate,today) + ' ' + getDateFormatedShort(onset) + ' - ' + getDateFormatedShort(expires)
}
else{
dateString = onsetDay + ' ' + getDateFormatedShort(onset) + ' - ' + getDateFormatedShort(expires)
}
}
else{
//adapter.log.debug('Days difference onset: ' + dateDifferenceInWord(onsetDate,today) + ' : ' + onsetDate)
//adapter.log.debug('Days difference expires: ' + dateDifferenceInWord(expiresDate,today)+ ' : ' + expiresDate)
if (adapter.config.dayInWords) {
dateString = dateDifferenceInWord(onsetDate,today) + ' ' + getDateFormatedShort(onset) + ' - ' + dateDifferenceInWord(expiresDate,today) + ' ' + getDateFormatedShort(expires)
}
else{
dateString = onsetDay + ' ' + getDateFormatedShort(onset) + ' - ' + expiresDay + ' ' + getDateFormatedShort(expires)
}
}
return dateString
}
function getDateFormatedShort(dateTimeString)
{
return new Date(dateTimeString).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
}
function dateDifferenceInWord(inputDate,comparison){
// Take the difference between the dates and divide by milliseconds per day.
// Round to nearest whole number to deal with DST.
//var difference = Math.round((comparison-inputDate)/(1000*60*60*24))
var difference = 0
//adapter.log.debug('Days difference: ' + inputDate + ' - ' + difference)
var date1_tomorrow = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1);
var date1_today = new Date(today.getFullYear(), today.getMonth(), today.getDate() );
var date1_yesterday = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 1);
//adapter.log.debug('Date tomorrow ' + date1_tomorrow)
//adapter.log.debug('Date today ' + date1_today)
//adapter.log.debug('Date yesterday ' + date1_yesterday)
if (date1_tomorrow.getFullYear() == inputDate.getFullYear() && date1_tomorrow.getMonth() == inputDate.getMonth() && date1_tomorrow.getDate() == inputDate.getDate()) {
//date is tomorrow
difference = 1
}
if (date1_today.getFullYear() == inputDate.getFullYear() && date1_today.getMonth() == inputDate.getMonth() && date1_today.getDate() == inputDate.getDate()) {
//date is today
difference = 2
}
if (date1_yesterday.getFullYear() == inputDate.getFullYear() && date1_yesterday.getMonth() == inputDate.getMonth() && date1_yesterday.getDate() == inputDate.getDate()) {
//date is yesterday
difference = 3
}
switch (difference) {
case 2:
return i18nHelper.today[lang]
break;
case 3:
return i18nHelper.yesterday[lang]
break;
case 1:
return i18nHelper.tomorrow[lang]
break;