Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
executable file
·1338 lines (1245 loc) · 53.9 KB
/
Copy pathapp.js
File metadata and controls
executable file
·1338 lines (1245 loc) · 53.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
const Homey = require('homey');
const { HomeyAPI } = require('athom-api')
const delay = time => new Promise(res=>setTimeout(res,time));
// Flow triggers
let triggerSurveillanceChanged = new Homey.FlowCardTrigger('SurveillanceChanged');
let triggerSensorActiveAtArming = new Homey.FlowCardTrigger('sensorActiveAtArming');
let triggerSensorActive = new Homey.FlowCardTrigger('sensorActiveAtSensorCheck');
let triggerAlarmActivated = new Homey.FlowCardTrigger('AlarmActivated');
let triggerAlarmDeactivated = new Homey.FlowCardTrigger('AlarmDeactivated');
let triggerAlarmDelayActivated = new Homey.FlowCardTrigger('AlarmDelayActivated');
let triggerArmDelayActivated = new Homey.FlowCardTrigger('ArmDelayActivated');
let triggerTimeTillAlarmChanged = new Homey.FlowCardTrigger('TimeTillAlarm');
let triggerTimeTillArmedChanged = new Homey.FlowCardTrigger('TimeTillArmed');
let triggerLogLineWritten = new Homey.FlowCardTrigger('LogLineWritten');
let triggerSensorTrippedInAlarmstate = new Homey.FlowCardTrigger('SensorTrippedInAlarmstate');
let triggerNoInfoReceived = new Homey.FlowCardTrigger('noInfoReceived');
// Flow conditions
const conditionSurveillanceIs = new Homey.FlowCardCondition('SurveillanceIs');
const conditionArmingCountdown = new Homey.FlowCardCondition('ArmingCountdown');
const conditionAlarmCountdown = new Homey.FlowCardCondition('AlarmCountdown');
const conditionAlarmActive = new Homey.FlowCardCondition('AlarmActive');
// Flow actions
const actionInputHistory = new Homey.FlowCardAction('SendInfo');
const actionClearHistory = new Homey.FlowCardAction('ClearHistory');
const actionActivateAlarm = new Homey.FlowCardAction('ActivateAlarm');
const actionDeactivateAlarm = new Homey.FlowCardAction('DeactivateAlarm');
const actionCheckLastCommunication = new Homey.FlowCardAction('CheckLastCommunication');
const actionAllDevicesStateCheck = new Homey.FlowCardAction('DevicesStateCheck');
const actionInputNotification = new Homey.FlowCardAction('SendNotification');
var surveillance;
var alarm = false;
var heimdallSettings = [];
var defaultSettings = {
"armingDelay": "30",
"alarmDelay": "30",
"delayArmingFull": false,
"delayArmingPartial": false,
"logArmedOnly": false,
"logTrueOnly": false,
"useTampering": false,
"checkMotionAtArming": false,
"checkContactAtArming": false,
"checkBeforeCountdown": false,
"spokenSmodeChange": false,
"spokenAlarmCountdown": false,
"spokenArmCountdown": false,
"spokenAlarmChange": false,
"spokenMotionTrue": false,
"spokenTamperTrue": false,
"spokenDoorOpen": false,
"spokenMotionAtArming": false,
"spokenDoorOpenAtArming": false,
"notificationSmodeChange": false,
"notificationAlarmChange": false,
"notificationNoCommunicationMotion": false,
"notificationNoCommunicationContact": false,
"noCommunicationTime": 24
};
var sModeDevice;
var aModeDevice;
var armCounterRunning = false;
var alarmCounterRunning = false;
var lastDoor = false;
var changeTta = false;
var devicesNotReadyAtStart = [];
var devicesNotReady = [];
class Heimdall extends Homey.App {
// Get API control function
getApi() {
if (!this.api) {
this.api = HomeyAPI.forCurrentHomey();
}
return this.api;
}
// Get all devices function for API
async getDevices() {
const api = await this.getApi();
return await this.api.devices.getDevices();
}
async getZones() {
const api = await this.getApi();
return await this.api.zones.getZones();
}
async getZone(zoneId) {
var result = "unknown";
let allZones = await this.getZones();
for (let zone in allZones) {
if ( allZones[zone].id == zoneId ) {
result = allZones[zone].name;
}
};
return result;
}
async onInit() {
this.log('init Heimdall')
let nu = getDateTime();
this.api = await this.getApi();
surveillance = Homey.ManagerSettings.get('surveillanceStatus');
this.log('Surveillance Mode: ' + surveillance);
let logLine = "ao " + nu + readableMode(surveillance) + " || Heimdall || Heimdall start"
this.writeLog(logLine)
if ( surveillance == null ) {
surveillance = true
};
heimdallSettings = Homey.ManagerSettings.get('settings');
if (heimdallSettings == (null || undefined)) {
heimdallSettings = defaultSettings
};
if ( heimdallSettings.armingDelay == (null || undefined)) {
heimdallSettings.armingDelay = heimdallSettings.triggerDelay
heimdallSettings.alarmDelay = heimdallSettings.triggerDelay
};
if ( heimdallSettings.noCommunicationTime == (null || undefined) || heimdallSettings.noCommunicationTime == 12 ) {
heimdallSettings.noCommunicationTime = 24
};
let language = Homey.ManagerI18n.getLanguage()
Homey.ManagerSettings.set('language', language, function( err ){
if( err ) return Homey.alert( err );
});
this.enumerateDevices();
}
// Get all devices and add them
async enumerateDevices() {
// Get the homey object
const api = await this.getApi();
api.devices.on('device.create', async(id) => {
await this.log('New device found!')
var device = await this.waitForDevice(id,0)
if ( device ) {
await this.addDevice(device);
}
});
api.devices.on('device.delete', async(id) => {
await this.log('Device deleted!: ')
});
let allDevices = await this.getDevices();
for (let id in allDevices) {
var device = await this.waitForDevice(allDevices[id],0)
if ( device ) {
await this.addDevice(device);
}
};
this.log('Enumerating devices: done.')
}
// Yolo function courtesy of Robert Klep ;)
async waitForDevice(id, addCounter) {
const device = await this.api.devices.getDevice({ id: id.id });
if (device.ready) {
return device;
}
await delay(1000);
addCounter++;
if ( addCounter < 10 ) {
return this.waitForDevice(id,addCounter);
} else {
this.log("Found Device, not ready: " + device.name)
devicesNotReadyAtStart.push(device.name)
let nu = getDateTime();
// let logLine = "al " + nu + readableMode(surveillance) + " || Enumerate Devices || " + device.name + " is not ready at Enumerating Devices"
let logLine = "al " + nu + readableMode(surveillance) + " || " + Homey.__("enumerate.source") + " || " + device.name + Homey.__("enumerate.warning")
this.writeLog(logLine)
return false
}
}
// Add device function, all device types with motion-, contact-, vibration- and tamper capabilities are added.
addDevice(device) {
// Find Surveillance Mode Switch
if ( device.data.id === 'sMode' ) {
sModeDevice = device;
this.log('Found Mode Switch named: ' + device.name)
}
// Find Alarm Off Button
if ( device.data.id === 'aMode' ) {
aModeDevice = device;
this.log('Found Alarm Button named: ' + device.name)
}
if ( 'alarm_motion' in device.capabilitiesObj ) {
this.log('Found motion sensor: ' + device.name)
this.attachEventListener(device,'motion')
}
if ( 'alarm_contact' in device.capabilitiesObj ) {
this.log('Found contact sensor: ' + device.name)
this.attachEventListener(device,'contact')
}
if ( 'alarm_vibration' in device.capabilitiesObj ) {
this.log('Found vibration sensor: ' + device.name)
this.attachEventListener(device,'vibration')
}
if ( 'alarm_tamper' in device.capabilitiesObj ) {
this.log('Found tamper sensor: ' + device.name)
this.attachEventListener(device,'tamper')
}
}
attachEventListener(device,sensorType) {
switch (sensorType) {
case "motion":
device.makeCapabilityInstance('alarm_motion',function(device, state) {
this.stateChange(device,state,sensorType)
}.bind(this, device));
break;
case "contact":
device.makeCapabilityInstance('alarm_contact',function(device, state) {
this.stateChange(device,state,sensorType)
}.bind(this, device));
break;
case "vibration":
device.makeCapabilityInstance('alarm_vibration',function(device, state) {
this.stateChange(device,state,sensorType)
}.bind(this, device));
break;
case "tamper":
device.makeCapabilityInstance('alarm_tamper',function(device, state) {
this.stateChange(device,state,sensorType)
}.bind(this, device));
break;
}
let monFull = "", monPartial = "", monLogged = ""
if ( isMonitoredFull(device) ) {
monFull = ", Fully Monitored"
}
if ( isMonitoredPartial(device) ) {
monPartial = ", Partially Monitored"
}
if ( isLogged(device) ) {
monLogged = ", Logged"
}
this.log('Attached Eventlistener to: ' + device.name + ': ' + sensorType + monFull + monPartial + monLogged)
}
// this function gets called when a device with an attached eventlistener fires an event.
async stateChange(device,sensorState,sensorType) {
if ( sensorType == 'tamper' && !heimdallSettings.useTampering ) {
this.log("StateChange detected for tampering but shouldn't act on it")
return
}
let nu = getDateTime();
let color = " ";
let logLine = "";
let sourceDeviceFull = isMonitoredFull(device)
let sourceDevicePartial = isMonitoredPartial(device)
let sourceDeviceLog = isLogged(device)
console.log('-----------------------------------------------')
this.log('stateChange: ' + device.name)
this.log('sourceDeviceFull: ' + sourceDeviceFull)
this.log('sourceDevicePartial: ' + sourceDevicePartial)
this.log('sourceDeviceLog: ' + sourceDeviceLog)
// is the device monitored?
if ( sourceDeviceFull || sourceDevicePartial || sourceDeviceLog ) {
this.log('Full||Partial||Log: Yes')
let sensorStateReadable;
surveillance = Homey.ManagerSettings.get('surveillanceStatus');
sensorStateReadable = readableState(sensorState, sensorType)
this.log('sensorStateReadable: ' + sensorStateReadable)
// Select the desired color
if ( surveillance == "disarmed" ) {
color = "md-"
}
else if ( surveillance == "armed" ) {
color = "ma-"
}
else if ( surveillance == "partially_armed" ) {
color = "mp-"
}
if ( sourceDeviceLog ) {
color = "l- "
}
// Set logLine for the statechange
logLine = color + nu + readableMode(surveillance) + " || Heimdall || " + device.name + " " + sensorType + ": " + sensorStateReadable;
// Is sensorState true?
if ( sensorState ) {
if (sensorType='contact' && isDelayed(device) && armCounterRunning) {
// a Doorsensor with a delay is opened while the arming countdown is running
this.log('lastDoor: Opened')
lastDoor = true;
}
// is there no delayed trigger and Alarm state active?
if ( !alarmCounterRunning && !alarm) {
if ( ( surveillance == 'armed' && sourceDeviceFull ) || ( surveillance == 'partially_armed' && sourceDevicePartial ) ) {
this.log('Alarm is triggered: Yes')
let zone = await this.getZone(device.zone)
logLine = "al " + nu + readableMode(surveillance) + " || Heimdall || " + device.name + " in " + zone + Homey.__("history.triggerdalarm")
if ( sensorType == 'motion' ) {
this.speak("motionTrue", device.name + " detected motion")
}
if ( sensorType == 'contact' ) {
this.speak("doorOpen", device.name + " is opened")
}
if ( sensorType == 'tamper') {
this.speak("tamper", device.name + " detected tampering")
}
if ( isDelayed(device) ) {
// The device has a delayed trigger
alarmCounterRunning = true;
this.log('alarmCounterRunning: true')
logLine = "ad "+ nu + readableMode(surveillance) + " || Heimdall || " + Homey.__("history.alarmdelayed") + heimdallSettings.alarmDelay + Homey.__("history.seconds") + '\n' + logLine
let delay = heimdallSettings.alarmDelay * 1000;
// Trigger delay flow card
var tokens= { 'Reason': device.name + ': '+ sensorStateReadable , 'Duration': heimdallSettings.alarmDelay * 1 };
triggerAlarmDelayActivated.trigger(tokens, function(err, result){
if( err ) {
return Homey.error(err)} ;
});
this.log('alarmCounterRunning: true')
this.log('alarm is delayed: Yes, ' + heimdallSettings.alarmDelay + ' seconden')
//speak("The alarm will go off in " + heimdallSettings.alarmDelay + " seconds.")
this.speak("alarmCountdown", Homey.__("speech.startalarmcountdown") + heimdallSettings.alarmDelay + Homey.__("speech.seconds"))
this.log('ttAlarmCountdown start: ' + heimdallSettings.alarmDelay)
// Trigger Time Till Alarm flow card
let tta = heimdallSettings.alarmDelay - 1;
this.ttAlarmCountdown(tta, device,sensorStateReadable);
}
else {
this.log('Trigger is delayed: No')
this.activateAlarm(device, sensorStateReadable, nu, "Heimdall");
}
}
else {
this.log('Alarm is triggered: No')
}
}
else if ( alarmCounterRunning ) {
// Delayed trigger is active
if ( ( surveillance == 'armed' && sourceDeviceFull ) || ( surveillance == 'partially_armed' && sourceDevicePartial ) ) {
this.log('alarmCounterRunning: true so sensorstate true is cancelled')
logLine = color + nu + readableMode(surveillance) + " || Heimdall || " + device.name + ": " + sensorStateReadable + Homey.__("history.noalarmtriggercountdown");
}
}
else if ( alarm ) {
// Alarm state is active
if ( ( surveillance == 'armed' && sourceDeviceFull ) || ( surveillance == 'partially_armed' && sourceDevicePartial ) ) {
this.log('Alarmstate Active: The Alarm State is active so just log the sensorstate')
logLine = color + nu + readableMode(surveillance) + " || Heimdall || " + device.name + ": " + sensorStateReadable + Homey.__("history.noalarmtriggeralarmstate");
let zone = await this.getZone(device.zone)
var tokens = {'Zone': zone, 'Device': device.name, 'State': sensorStateReadable};
triggerSensorTrippedInAlarmstate.trigger(tokens, function(err, result){
if( err ) {
return Homey.error(err)} ;
});
}
}
}
else {
// sensorState is false
if ( sensorType='contact' && isDelayed(device) && armCounterRunning && lastDoor ) {
// a Doorsensor with a delay is opened and closed while the arming countdown is running
this.log('lastDoor: Closed, countdown will be lowered')
changeTta = true;
}
}
let shouldLog = true;
this.log('logArmedOnly: ' + heimdallSettings.logArmedOnly + ', Surveillance Mode: ' + surveillance)
this.log('logTrueOnly: ' + heimdallSettings.logTrueOnly + ', Sensorstate: ' + sensorState)
if ( heimdallSettings.logArmedOnly && surveillance === 'disarmed' && !sourceDeviceLog) {
shouldLog = false;
this.log('LogArmedOnly is true and Surveillance is off, so no log line')
}
if ( heimdallSettings.logTrueOnly && !sensorState && !sourceDeviceLog ) {
shouldLog = false;
this.log('logTrueOnly is true and sensorstate is false, so no log line')
}
if ( shouldLog ) {
this.writeLog(logLine)
}
if ( sourceDeviceLog ) {
// trigger the flowcard when a device with logging changes state
var tokens = {'Device': device.name, 'State': sensorStateReadable};
triggerLogLineWritten.trigger(tokens, function(err, result){
if( err ) {
return Homey.error(err)} ;
});
}
}
}
// sets Surveillance Mode, called from Surveillance Mode Device, will call setSurveillanceValue after evaluating conditions.
setSurveillanceMode(value, source) {
this.log('setSurveillanceMode: ' + value);
let nu = getDateTime();
let logLine = "";
surveillance = Homey.ManagerSettings.get('surveillanceStatus');
if ( value == 'disarmed' ) {
logLine = readableMode(value) + " || " + source + " || " + Homey.__("history.smodedisarmed")
this.setSurveillanceValue("sd ",value, logLine)
Homey.app.deactivateAlarm(false, Homey.__("devices.surveillancemode.name"))
if ( armCounterRunning ) {
// code to cancel an arm command during delayArming
this.log('Need to stop arming!')
armCounterRunning = false;
}
} else {
if ( value == 'armed' ) {
logLine = readableMode(value) + " || " + source + " || " + Homey.__("history.smodearmed")
} else {
logLine = readableMode(value) + " || " + source + " || " + Homey.__("history.smodepartiallyarmed")
}
if ( (value == 'armed' && heimdallSettings.delayArmingFull) || (value == 'partially_armed' && heimdallSettings.delayArmingPartial ) ) {
this.log('Arming is delayed: Yes, ' + heimdallSettings.armingDelay + ' seconds.')
if ( armCounterRunning ) {
this.log('Armingdelay already active: Not starting a new one')
return
}
let delay = heimdallSettings.armingDelay * 1000;
this.log('setSurveillanceValue in:' + heimdallSettings.armingDelay + ' seconds.')
//speak("The Surveillance mode will be set to " + readableMode(value) + " in " + heimdallSettings.armingDelay + " seconds.")
this.speak("armCountdown", Homey.__("speech.startarmcountdown") + readableMode(value) + Homey.__("speech.in") + heimdallSettings.armingDelay + Homey.__("speech.seconds"))
armCounterRunning = true;
let tta = heimdallSettings.armingDelay;
this.ttArmedCountdown(tta,"sa ", value, logLine);
var tokens= { 'Duration': heimdallSettings.armingDelay * 1 };
triggerArmDelayActivated.trigger(tokens, function(err, result){
if( err ) {
return Homey.error(err)} ;
});
if ( value == 'armed' ) {
logLine = "st " + nu + readableMode(surveillance) + " || " + source + " || " + Homey.__("history.smodedelayarmed") + heimdallSettings.armingDelay + Homey.__("history.seconds")
} else {
logLine = "st " + nu + readableMode(surveillance) + " || " + source + " || " + Homey.__("history.smodedelaypartiallyarmed") + heimdallSettings.armingDelay + Homey.__("history.seconds")
}
this.writeLog(logLine)
// check for tripped sensor before Arming Delay
if ( heimdallSettings.checkBeforeCountdown ) {
Homey.app.checkDevicesState(value, nu)
}
} else {
this.log('Arming is delayed: No')
armCounterRunning = true;
this.setSurveillanceValue("sa ",value, logLine)
}
if ( value === 'armed' || value === 'partially_armed' ) {
Homey.app.checkDevicesLastCom(value)
}
}
}
// Check the status of the devices triggered by setting a Surveillance Mode
async checkDevicesState(value, nu) {
let allDevices = await this.getDevices()
for (let device in allDevices) {
this.checkDeviceState(allDevices[device], value, nu)
};
}
// Check the last communication of a device at setting a Surveillance Mode or from a flow
async checkDevicesLastCom(value) {
let allDevices = await this.getDevices()
for (let device in allDevices) {
this.checkDeviceLastCom(allDevices[device], value)
};
}
// Check the status of the devices triggered by a flow
async checkAllDevicesState() {
let allDevices = await this.getDevices()
for (let device in allDevices) {
this.checkAllDeviceState(allDevices[device])
};
}
async checkDeviceState(device, value, nu) {
if ( await this.checkReadyState(device) ) return
let sensorState
let sensorStateReadable
let sensorType
if ( 'alarm_motion' in device.capabilitiesObj && heimdallSettings.checkMotionAtArming ) {
sensorState = device.capabilitiesObj.alarm_motion.value
sensorStateReadable = readableState(sensorState, 'motion')
sensorType = 'motion'
this.log("checkDeviceState: " + device.name + " - " + sensorType + ": " + sensorStateReadable)
}
if ( 'alarm_contact' in device.capabilitiesObj && heimdallSettings.checkContactAtArming ) {
sensorState = device.capabilitiesObj.alarm_contact.value
sensorStateReadable = readableState(sensorState, 'contact')
sensorType = 'contact'
this.log("checkDeviceState: " + device.name + " - " + sensorType + ": " + sensorStateReadable)
};
if ( value == 'armed') {
if ( isMonitoredFull(device) ) {
if ( sensorState ) {
let delayText = ""
if ( isDelayed(device) ) {
delayText = Homey.__("atarming.delayText")
}
if ( sensorType == 'motion' ) {
this.alertSensorActiveAtArming(value, nu, sensorType, Homey.__("atarming.warningMotion") + sensorStateReadable + Homey.__("atarming.on") + device.name + delayText)
} else if ( sensorType == 'contact') {
this.alertSensorActiveAtArming(value, nu, sensorType, Homey.__("atarming.warningContact") + device.name + Homey.__("atarming.is") + sensorStateReadable + delayText)
}
}
}
}
else if ( value == 'partially_armed' ) {
if ( isMonitoredPartial(device) ) {
if ( sensorState ) {
let delayText = ""
if ( isDelayed(device) ) {
delayText = Homey.__("atarming.delayText")
}
if ( sensorType == 'motion' ) {
this.alertSensorActiveAtArming(value, nu, sensorType, Homey.__("atarming.warningMotion") + sensorStateReadable + Homey.__("atarming.on") + device.name + delayText)
} else if ( sensorType == 'contact' ) {
this.alertSensorActiveAtArming(value, nu, sensorType, Homey.__("atarming.warningContact") + device.name + Homey.__("atarming.is") + sensorStateReadable + delayText)
}
}
}
}
}
async checkDeviceLastCom(device, value) {
if ( !device.ready ) return
if ( isMonitoredFull(device) || isMonitoredPartial(device) ) {
let nu = getDateTime();
let nuEpoch = Date.now();
if ( 'alarm_motion' in device.capabilitiesObj || 'alarm_contact' in device.capabilitiesObj ) {
let mostRecentComE = 0
for ( let capability in device.capabilitiesObj ) {
let lu = Date.parse(device.capabilitiesObj[capability].lastUpdated)
if ( lu > mostRecentComE ) {
mostRecentComE = lu
}
//console.log(mostRecentComE)
}
let mostRecentComH = new Date( mostRecentComE )
let verschil = Math.round((nuEpoch - mostRecentComE)/1000)
if ( verschil > heimdallSettings.noCommunicationTime * 3600 ) {
let d = new Date(0);
d.setUTCSeconds(Date.parse(mostRecentComH)/1000);
let lastUpdateTime = d.toLocaleString();
let tempColor = 'mp-'
let zone = await this.getZone(device.zone)
let tempLogLine = tempColor + nu + readableMode(value) + " || Heimdall || " + device.name + " in " + zone + Homey.__("history.noreport") + heimdallSettings.noCommunicationTime + Homey.__("history.lastreport") + lastUpdateTime
this.writeLog(tempLogLine)
this.log("checkDeviceLastCom: " + device.name + " - did not communicate in last 24 hours")
if ( heimdallSettings.notificationNoCommunicationMotion && 'alarm_motion' in device.capabilitiesObj ) {
let message = '**' + device.name + '** in ' + zone + Homey.__("history.noreport") + heimdallSettings.noCommunicationTime + Homey.__("history.lastreport") + lastUpdateTime
this.writeNotification(message)
}
if ( heimdallSettings.notificationNoCommunicationContact && 'alarm_contact' in device.capabilitiesObj ) {
let message = '**' + device.name + '** in ' + zone + Homey.__("history.noreport") + heimdallSettings.noCommunicationTime + Homey.__("history.lastreport") + lastUpdateTime
this.writeNotification(message)
}
var tokens = {'Zone': zone, 'Device': device.name, 'LastUpdate': lastUpdateTime, 'Duration': heimdallSettings.noCommunicationTime};
triggerNoInfoReceived.trigger(tokens, function(err, result){
if( err ) {
return Homey.error(err)} ;
});
} else {
this.log("checkDeviceLastCom: " + device.name + " - communicated in last 24 hours")
}
}
}
}
async checkAllDeviceState(device) {
if ( await this.checkReadyState(device) ) return
let sensorState = false
let sensorStateReadable
let sensorType
if ( 'alarm_motion' in device.capabilitiesObj ) {
sensorState = device.capabilitiesObj.alarm_motion.value
sensorStateReadable = readableState(sensorState, 'motion')
sensorType = 'Motion'
this.log("checkAllDeviceState: " + device.name + " - " + sensorType + ": " + sensorStateReadable)
}
if ( 'alarm_contact' in device.capabilitiesObj ) {
sensorState = device.capabilitiesObj.alarm_contact.value
sensorStateReadable = readableState(sensorState, 'contact')
sensorType = 'Contact'
this.log("checkAllDeviceState: " + device.name + " - " + sensorType + ": " + sensorStateReadable)
};
if ( sensorState ) {
this.alertSensorActive (device, sensorType, sensorStateReadable)
}
}
async checkReadyState(device) {
if ( !device.ready ) {
// The device is not ready
// Check if the device is in the devicesNotReadyAtStart list
for (let deviceNotReady in devicesNotReadyAtStart) {
if ( device.name == devicesNotReadyAtStart[deviceNotReady] ) {
// The device has not been ready yet, no action
return true
}
}
// The device is not in the devicesNotReadyAtStart list so it has been ready
// Add to the devicesNotReady list
devicesNotReady.push(device.name)
// And log this
this.log("Device no longer ready: " + device.name)
let nu = getDateTime();
let logLine = "al " + nu + readableMode(surveillance) + " || " + Homey.__("devicecheck.source") + " || " + device.name + Homey.__("devicecheck.warning")
this.writeLog(logLine)
return true
} else {
// The device is ready
// Check if the device is in the devicesNotReadyAtStart list
for (let deviceNotReady in devicesNotReadyAtStart) {
if ( device.name == devicesNotReadyAtStart[deviceNotReady] ) {
// The device has not been ready yet
// So add the device
await this.addDevice(device);
// Remove device from devicesNotReadyAtStart list
let x = devicesNotReadyAtStart.splice(deviceNotReady,1)
devicesNotReadyAtStart = devicesNotReadyAtStart.splice(deviceNotReady,1)
// And log it
this.log("Device now ready: " + device.name)
let nu = getDateTime();
let logLine = "ao " + nu + readableMode(surveillance) + " || " + Homey.__("devicecheck.source") + " || " + device.name + Homey.__("devicecheck.ready")
this.writeLog(logLine)
return false
}
}
// Check if the device is in the devicesNotReady list
for (let deviceReady in devicesNotReady) {
if ( device.name == devicesNotReady[deviceReady] ) {
// The device has been ready, was unready and is ready again
// Log this
this.log("Device became ready again: " + device.name)
let nu = getDateTime();
let logLine = "ao " + nu + readableMode(surveillance) + " || " + Homey.__("devicecheck.source") + " || " + device.name + Homey.__("devicecheck.readyagain")
this.writeLog(logLine)
// Remove the device from deviceNotReady list
let x = devicesNotReady.splice( deviceReady, 1 )
devicesNotReady = devicesNotReady.splice( deviceReady, 1 )
return false
}
}
return false
}
}
// Actually sets the Surveillance Mode
setSurveillanceValue(color,value, logLine) {
let nu = getDateTime();
logLine = color + nu + logLine;
surveillance = Homey.ManagerSettings.get('surveillanceStatus');
lastDoor = false;
changeTta = false;
if ( armCounterRunning || value === 'disarmed') {
Homey.ManagerSettings.set('surveillanceStatus', value, function( err ){
if( err ) return Homey.alert( err );
});
this.logRealtime("Surveillance Mode", value)
//speak("sModeChange", "The surveillance mode is set to " + readableMode(value))
this.speak("sModeChange", Homey.__("speech.smodeset") + readableMode(value))
this.log('setSurveillanceValue: '+ value)
if ( heimdallSettings.notificationSmodeChange ) {
let message = '**Surveillance Mode** set to ' + readableMode(value)
this.writeNotification(message)
}
var tokens = { 'mode': readableMode(value) };
triggerSurveillanceChanged.trigger(tokens, function(err, result){
if( err ) {
return Homey.error(err)} ;
} );
// check the states of the sensors
if ( value != 'disarmed' && !heimdallSettings.checkBeforeCountdown ) {
Homey.app.checkDevicesState(value, nu)
}
} else {
logLine = "sd " + nu + readableMode(surveillance) + " || Heimdall || " + Homey.__("history.smodechangedisabled")
}
this.writeLog(logLine)
armCounterRunning = false;
}
async activateAlarm(device,sensorState,nu,source) {
if ( nu == "" ) {
nu = getDateTime()
}
let logLine = "";
alarm=true;
surveillance = Homey.ManagerSettings.get('surveillanceStatus');
if ( surveillance != 'disarmed' || source == "Flowcard" ) {
// Surveillance mode is active
let zone = await this.getZone(device.zone)
if ( source == "Heimdall") {
// let zone = await this.getZone(device.zone)
var tokens= {'Reason': device.name + ': '+ sensorState , 'Zone': zone };
logLine = "al " + nu + readableMode(surveillance) + " || " + source + " || " + Homey.__("history.alarmactivated") + device.name + ": " + sensorState;
} else {
var tokens= {'Reason': 'Flowcard' , 'Zone': "" };
logLine = "al " + nu + readableMode(surveillance) + " || " + source + " || " + Homey.__("history.alarmactivatedflowcard");
}
triggerAlarmActivated.trigger(tokens, function(err, result){
if( err ) {
return Homey.error(err)} ;
});
if ( heimdallSettings.notificationAlarmChange ) {
let message = '**'+device.name+'** in '+ zone + Homey.__("history.triggerdalarm")
this.writeNotification(message)
}
// speak("alarmChange", "The alarm is activated")
this.speak("alarmChange", Homey.__("speech.alarmactivated"))
// save alarm status
Homey.ManagerSettings.set('alarmStatus', alarm, function( err ){
if( err ) return Homey.alert( err );
});
// Check if Alarm Off Button exists and turn on
if ( aModeDevice != undefined) {
this.log("aModeDevice alarm_heimdall: activated")
aModeDevice.setCapabilityValue('alarm_heimdall', true)
aModeDevice.setCapabilityValue('alarm_generic', true)
}
if ( sModeDevice != undefined) {
this.log("sModeDevice alarm_heimdall: activated")
sModeDevice.setCapabilityValue('alarm_heimdall', true)
sModeDevice.setCapabilityValue('alarm_generic', true)
}
}
else {
// Surveillance mode is not active
logLine = "ao " + nu + readableMode(surveillance) + " || " + source + " || " + Homey.__("history.alarmnotactivated")
alarm=false;
Homey.ManagerSettings.set('alarmStatus', alarm, function( err ){
if( err ) return Homey.alert( err );
});
}
// write information to log
this.writeLog(logLine)
this.logRealtime("Alarm Status", alarm)
}
alertSensorActiveAtArming ( value, nu, sensorType, warningText ) {
// write log
let color = 'm' + value.substring(0,1) + '-'
let logLine = color + nu + readableMode(value) + " || Heimdall || " + warningText
this.writeLog(logLine)
// activate triggercard
var tokens = { 'warning': warningText };
triggerSensorActiveAtArming.trigger(tokens, function(err, result){
if( err ) {
return Homey.error(err)} ;
} );
// tell user
if ( sensorType == 'motion' && heimdallSettings.spokenMotionAtArming) {
this.speak("sensorActive", warningText)
} else if ( sensorType == 'contact' && heimdallSettings.spokenDoorOpenAtArming ) {
this.speak("sensorActive", warningText)
}
}
async alertSensorActive ( device, sensorType, sensorstateReadable ) {
let zone = await this.getZone(device.zone)
var tokens = { 'Device': device.name, 'Device type': sensorType, 'Zone': zone, 'State': sensorstateReadable}
triggerSensorActive.trigger(tokens, function(err, result){
if( err ) {
return Homey.error(err)} ;
} );
}
deactivateAlarm(value, source) {
if ( alarm === true || source == "Flowcard") {
let nu = getDateTime();
alarm = false
surveillance = Homey.ManagerSettings.get('surveillanceStatus');
Homey.ManagerSettings.set('alarmStatus', alarm, function( err ){
if( err ) return Homey.alert( err );
});
// speak("alarmChange", "The alarm is deactivated")
this.speak("alarmChange", Homey.__("speech.alarmdeactivated"))
// Check if Alarm Off Button exists and turn off
if ( aModeDevice != undefined) {
aModeDevice.setCapabilityValue('alarm_heimdall', false)
aModeDevice.setCapabilityValue('alarm_generic', false)
}
if ( sModeDevice != undefined) {
sModeDevice.setCapabilityValue('alarm_heimdall', false)
sModeDevice.setCapabilityValue('alarm_generic', false)
}
var tokens = { 'Source': source }
triggerAlarmDeactivated.trigger(tokens, function(err, result){
if ( err ) {
return Homey.error(err)} ;
});
let logLine = "ao "+ nu + readableMode(surveillance) + " || " + source + " || " + Homey.__("history.alarmdeactivated") + source
this.writeLog(logLine)
if ( heimdallSettings.notificationAlarmChange ) {
let message = Homey.__("history.alarmdeactivated") + '**' + source + '**'
this.writeNotification(message)
}
}
}
// Write information to history and cleanup 20% when history above 2000 lines
async writeLog(logLine) {
// console.log(logLine);
let savedHistory = Homey.ManagerSettings.get('myLog');
if (savedHistory != undefined) {
// cleanup history
let lineCount = savedHistory.split(/\r\n|\r|\n/).length;
if ( lineCount > 2000 ) {
let deleteItems = parseInt( lineCount * 0.2 );
let savedHistoryArray = savedHistory.split(/\r\n|\r|\n/);
let cleanUp = savedHistoryArray.splice(-1*deleteItems, deleteItems, "" );
savedHistory = savedHistoryArray.join('\n');
}
// end cleanup
logLine = logLine+"\n"+savedHistory;
}
Homey.ManagerSettings.set('myLog', logLine );
logLine = "";
}
async writeNotification(message) {
var notification = new Homey.Notification({ excerpt: message });
notification.register();
}
async speak(type, text) {
if (type == "sModeChange" && heimdallSettings.spokenSmodeChange ) {
this.log('Say: ' + text)
Homey.ManagerSpeechOutput.say(text.toString())
}
if (type == "alarmCountdown" && heimdallSettings.spokenAlarmCountdown ) {
this.log('Say: ' + text)
Homey.ManagerSpeechOutput.say(text.toString())
}
if (type == "armCountdown" && heimdallSettings.spokenArmCountdown ) {
this.log('Say: ' + text)
Homey.ManagerSpeechOutput.say(text.toString())
}
if (type == "alarmChange" && heimdallSettings.spokenAlarmChange ) {
this.log('Say: ' + text)
Homey.ManagerSpeechOutput.say(text.toString())
}
if (type == "motionTrue" && heimdallSettings.spokenMotionTrue ) {
this.log('Say: ' + text)
Homey.ManagerSpeechOutput.say(text.toString())
}
if (type == "doorOpen" && heimdallSettings.spokenDoorOpen ) {
this.log('Say: ' + text)
Homey.ManagerSpeechOutput.say(text.toString())
}
if (type == "tamper" && heimdallSettings.spokenTamperTrue ) {
this.log('Say: ' + text)
Homey.ManagerSpeechOutput.say(text.toString())
}
if (type == "sensorActive") {
this.log('Say: ' + text)
Homey.ManagerSpeechOutput.say(text.toString())
}
}
ttArmedCountdown(delay, color, value, logLine) {
this.log('ttArmedCountdown: ' + delay)
if ( armCounterRunning ) {
if (changeTta && delay > 9 ) {
delay = 10;
changeTta = false
var prevLogLine = logLine
logLine = "st " + getDateTime() + readableMode(surveillance) + " || Heimdall || " + Homey.__("history.smodedelaychanged")
this.writeLog(logLine)
logLine = prevLogLine
}
var tokens = { 'ArmedTimer': delay * 1};
triggerTimeTillArmedChanged.trigger(tokens, function(err, result){
if( err ) {
return Homey.error(err)} ;
});
if (delay > 9 ) {
if (delay/5 == parseInt(delay/5)) {
this.speak("armCountdown", delay)
}
}
else if ( delay > 0 ) {
this.speak("armCountdown", delay)
}
if ( delay > 0 ) {
setTimeout(function(){
Homey.app.ttArmedCountdown(delay-1, color, value, logLine)
}, 1000);
}
else if ( delay == 0) {
this.setSurveillanceValue(color, value, logLine)
}
}
else {
this.log('ttArmedCountdown: armCounterRunning = false')
this.setSurveillanceValue(color, value, logLine)
}
}
ttAlarmCountdown(delay,device,sensorStateReadable) {
this.log('ttAlarmCountdown: ' + delay)
surveillance = Homey.ManagerSettings.get('surveillanceStatus');
if ( surveillance != 'disarmed' ) {
var tokens = { 'AlarmTimer': delay * 1};
triggerTimeTillAlarmChanged.trigger(tokens, function(err, result){
if( err ) {
return Homey.error(err)} ;
});
if (delay > 9 ) {
if (delay/5 == parseInt(delay/5)) {
this.speak("alarmCountdown", delay)
}
}
else if ( delay > 0 ) {
this.speak("alarmCountdown", delay)
}
if ( delay > 0 ) {
setTimeout(function(){
Homey.app.ttAlarmCountdown(delay-1,device,sensorStateReadable)
}, 1000);
}
else if ( delay == 0) {
alarmCounterRunning = false
this.log('alarmCounterRunning: false due to reaching 0')
this.activateAlarm(device, sensorStateReadable, "", "Heimdall")
}
}
else {
alarmCounterRunning = false
this.log('alarmCounterRunning: false')
this.log('ttAlarmCountdown: canceled due to disarm')
this.activateAlarm(device, sensorStateReadable, "", "Heimdall")
}
}
logRealtime(event, details)
{
Homey.ManagerApi.realtime(event, details)
}
}
module.exports = Heimdall;
Homey.ManagerSettings.on('set', (variable) => {
if ( variable === 'settings' ) {
heimdallSettings = Homey.ManagerSettings.get('settings')
console.log('New settings:')
console.log(heimdallSettings)
}
});
// Flow card functions //////////////////////////////////////////////////////
// Flow triggers functions
triggerSurveillanceChanged
.register()
.on('run', ( args, callback ) => {
if ( true ) {
callback( null, true );
}
else {
callback( null, false );
}
});
triggerSensorActiveAtArming
.register()
.on('run', ( args, callback ) => {
if ( true ) {
callback( null, true );
}
else {
callback( null, false );
}
});