forked from neptunix/homebridge-occupancy-delay
-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
862 lines (743 loc) · 28.3 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
'use strict';
var inherits = require('util').inherits;
var Service, Characteristic, HomebridgeAPI;
const TIME_REMAINING_CHARACTERISTIC_NAME = 'Time Remaining';
const TIME_REMAINING_CHARACTERISTIC_UUID = '2000006D-0000-1000-8000-0026BB765291';
const TIMEOUT_DELAY_CHARACTERISTIC_NAME = 'Post-Activity Timeout Delay';
const TIMEOUT_DELAY_CHARACTERISTIC_UUID = '94a765c6-e114-11eb-ba80-0242ac130004';
// OccupancyTriggerSwitch is 100% based on https://github.com/nfarina/homebridge-dummy
module.exports = function (homebridge) {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
HomebridgeAPI = homebridge;
// Register
homebridge.registerAccessory(
'homebridge-magic-occupancy',
'MagicOccupancy',
MagicOccupancy
);
}
class MagicOccupancy {
constructor (log, config, api) {
this.log = log;
this.config = config;
this.api = api;
this.occupancyLogging = config.occupancyLogging ?? true;
this.name = config.name.trim() ?? 'MagicOccupancy';
this.lightSwitchesNames = (config.lightSwitchesNames ?? '').split(',');
this.statefulSwitchesNames = (config.statefulSwitchesNames ?? '').split(',');
this.triggerSwitchesNames = (config.triggerSwitchesNames ?? '').split(',');
this.statefulStayOnSwitchesNames = (
config.statefulStayOnSwitchesNames ?? ''
).split(',');
this.triggerStayOnSwitchesNames = (
config.triggerStayOnSwitchesNames ?? ''
).split(',');
this.stayOccupiedDelay = Math.max(
0,
parseInt(config.stayOccupiedDelay ?? 0, 10) ?? 0
);
this.maxOccupationTimeout = Math.max(
0,
parseInt(config.maxOccupationTimeout ?? 0, 10) ?? 0
);
this.serial = (config.serial ?? 'JmoMagicOccupancySwitch').trim();
this.persistBetweenReboots = config.persistBetweenReboots != false;
this.startOnReboot = config.startOnReboot || false;
this.triggerSwitchToggleTimeout = 1000;
this.initializationCompleted = false;
this.locksCounter = 0;
this.isPendingCheckOccupancy = false;
this.isClearingOccupancy = false;
this._max_occupation_timer = null;
this.modeState = 'Unoccupied';
this.cacheDirectory = HomebridgeAPI.user.persistPath();
this.storage = require('node-persist');
this.storage.initSync({
dir: this.cacheDirectory,
forgiveParseErrors: true
});
const savedState = this._getInitialMainCacheState();
this._timer = null;
this._timer_started = null;
this._timer_delay = 0;
this._interval = null;
this._interval_last_value = 0;
this.switches = [];
this.occupancyService = new Service.OccupancySensor(this.name);
this.informationService = new Service.AccessoryInformation()
.setCharacteristic(
Characteristic.Manufacturer,
'https://github.com/Jason-Morcos/homebridge-magic-occupancy'
)
.setCharacteristic(Characteristic.Model, '2')
.setCharacteristic(Characteristic.SerialNumber, this.serial);
//Fix names getting messed up by iOS 16
this.occupancyService.addOptionalCharacteristic(Characteristic.ConfiguredName);
this.occupancyService.setCharacteristic(Characteristic.ConfiguredName, this.name.trim());
this.occupancyService.addCharacteristic(new Characteristic(
TIMEOUT_DELAY_CHARACTERISTIC_NAME,
TIMEOUT_DELAY_CHARACTERISTIC_UUID,
{
format: this.api.hap.Formats.UINT64,
unit: this.api.hap.Units.SECONDS,
maxValue: 2147483647,
minValue: 0,
minStep: 1,
perms: [
this.api.hap.Perms.READ,
this.api.hap.Perms.WRITE,
this.api.hap.Perms.NOTIFY
]
}
));
this.occupancyService.setCharacteristic(
TIMEOUT_DELAY_CHARACTERISTIC_NAME,
Math.min(2147483647, this.stayOccupiedDelay)
);
this.occupancyService
.getCharacteristic(TIMEOUT_DELAY_CHARACTERISTIC_NAME)
.on('change', event => {
this.log.debug('Setting stay occupied delay to:', event.newValue)
this.stayOccupiedDelay = event.newValue
});
this.occupancyService.addCharacteristic(new Characteristic(
TIME_REMAINING_CHARACTERISTIC_NAME,
TIME_REMAINING_CHARACTERISTIC_UUID,
{
format: this.api.hap.Formats.UINT64,
unit: this.api.hap.Units.SECONDS,
maxValue: 2147483647,
minValue: 0,
minStep: 1,
perms: [
this.api.hap.Perms.READ,
this.api.hap.Perms.WRITE,
this.api.hap.Perms.NOTIFY
]
}
));
this.occupancyService.setCharacteristic(
TIME_REMAINING_CHARACTERISTIC_NAME,
this.stayOccupiedDelay ? Math.min(2147483647, savedState.TimeRemaining) : 0
);
//Restore past state
this._setOccupancyState(savedState.ModeState);
this.occupancyService
.getCharacteristic(TIME_REMAINING_CHARACTERISTIC_NAME)
.on('change', event => {
if (event.newValue === 0 && event.oldValue > 0) {
this.log.debug('Cancel timer and set occupancy to "NotDetected"')
this.setOccupancyNotDetected()
}
});
/* Make the lightSwitches */
if (this.lightSwitchesNames.length > 0) {
this.log.debug(
'Making ' +
this.lightSwitchesNames.length +
' Light Switches'
);
this.lightSwitchesNames.forEach(
function (switchName) {
if (switchName.length == 0) {
return true //continue
}
this.switches.push(
new LightSwitchMirrorSwitch(this, {
name: switchName,
stayOnOnly: false
})
)
}.bind(this)
);
}
/* Make the statefulSwitches */
if (this.statefulSwitchesNames.length > 0) {
this.log.debug(
'Making ' +
this.statefulSwitchesNames.length +
' Stateful trigger switches'
);
this.statefulSwitchesNames.forEach(
function (switchName) {
if (switchName.length == 0) {
return true //continue
}
this.switches.push(
new StatefulSwitch(this, {
name: switchName,
stayOnOnly: false
})
)
}.bind(this)
);
}
/* Make the triggerSwitches */
if (this.triggerSwitchesNames.length > 0) {
this.log.debug(
'Making ' +
this.triggerSwitchesNames.length +
' Trigger trigger switches'
);
this.triggerSwitchesNames.forEach(
function (switchName) {
if (switchName.length == 0) {
return true //continue
}
this.switches.push(
new TriggerSwitch(this, {
name: switchName,
stayOnOnly: false
})
)
}.bind(this)
);
}
/* Make the statefulStayOnSwitches */
if (this.statefulStayOnSwitchesNames.length > 0) {
this.log.debug(
'Making ' +
this.statefulStayOnSwitchesNames.length +
' StayOn Stateful trigger switches'
);
this.statefulStayOnSwitchesNames.forEach(
function (switchName) {
if (switchName.length == 0) {
return true //continue
}
this.switches.push(
new StatefulSwitch(this, {
name: switchName,
stayOnOnly: true
})
)
}.bind(this)
);
}
/* Make the triggerStayOnSwitches */
if (this.triggerStayOnSwitchesNames.length > 0) {
this.log.debug(
'Making ' +
this.triggerStayOnSwitchesNames.length +
' StayOn Trigger trigger switches'
);
this.triggerStayOnSwitchesNames.forEach(
function (switchName) {
if (switchName.length == 0) {
return true //continue
}
this.switches.push(
new TriggerSwitch(this, {
name: switchName,
stayOnOnly: true
})
)
}.bind(this)
);
}
//Create master shutoff
if (config.createMasterShutoff == true) {
this.switches.push(
new MasterShutoffSwitch(this, {
name: 'Master Shutoff'
})
);
}
//Mark that we're done initializing here, final setup below
this.initializationCompleted = true;
//Handle start on reboot
if (this.startOnReboot) {
this.log.debug(`startOnReboot==true - setting to active`)
//Run the set after homebridge should have booted to ensure events fire
setTimeout(
function () {
this.setOccupancyDetected()
this.checkOccupancy(10)
}.bind(this),
10000
);
}
//Handle restoring state - gotta restart the decaying timer if we rebooted
else if (this.persistBetweenReboots && savedState.ModeState == 'UnoccupiedDelay') {
this.startUnoccupiedDelay(
this.stayOccupiedDelay ? savedState.TimeRemaining : 0
);
}
//Handle restoring state - gotta restart the max runtime timer if we rebooted
else if (this.persistBetweenReboots && savedState.ModeState == 'Occupied') {
this.setOccupancyDetected();
}
//Handle restoring state - gotta make sure all the timers are stopped
else if (this.persistBetweenReboots && savedState.ModeState == 'Occupied') {
this.setOccupancyNotDetected();
}
//Do an initial occupancy check
this.checkOccupancy(10);
}
//Helper to get a cached state value
_getInitialMainCacheState () {
const defaultState = {
TimeRemaining: 0,
ModeState: 'Unoccupied'
};
try {
var state = this.getCachedState('_MAIN', defaultState);
//Handle migrating a v1 cache
if (!('ModeState' in state)) {
state.ModeState = 'UnoccupiedDelay';
}
return state
} catch (error) {
this.log.debug(`Error initializing past state, falling back on default - ${error}`);
return defaultState;
}
}
/**
* startUnoccupiedDelays the countdown timer.
*/
startUnoccupiedDelay (overrideTimeRemaining = null) {
var timeRemaining = this.stayOccupiedDelay ?? 0;
if(overrideTimeRemaining != null && overrideTimeRemaining < timeRemaining) {
timeRemaining = overrideTimeRemaining;
}
if (timeRemaining <= 0) {
this.setOccupancyNotDetected();
return;
}
//Set state
this._setOccupancyState('UnoccupiedDelay');
this.locksCounter += 1;
this.stop();
this._timer_started = new Date().getTime();
this.log.debug('Timer startUnoccupiedDelayed:', timeRemaining);
this._timer = setTimeout(
this.setOccupancyNotDetected.bind(this),
Math.round(timeRemaining * 1000)
);
this._timer_delay = timeRemaining;
this._interval = setInterval(() => {
var elapsed = (new Date().getTime() - this._timer_started) / 1000;
var newValue = Math.round(this._timer_delay - elapsed);
if (newValue !== this._interval_last_value) {
this.occupancyService.setCharacteristic(
TIME_REMAINING_CHARACTERISTIC_NAME,
Math.min(2147483647, newValue)
);
this._interval_last_value = newValue;
this.saveCachedState('_MAIN', {
TimeRemaining: newValue,
ModeState: 'UnoccupiedDelay'
});
}
}, 250);
this.saveCachedState('_MAIN', {
TimeRemaining: timeRemaining,
ModeState: 'UnoccupiedDelay'
});
this.locksCounter -= 1;
}
/**
* Stops the countdown timer
*/
stop () {
if (this._timer) {
this.log.debug('Delay timer stopped');
clearTimeout(this._timer);
clearInterval(this._interval);
this._timer = null;
this._timer_started = null;
this._timer_delay = null;
this._interval = null;
}
}
//Helper to get a cached state value
getCachedState (key, defaultValue) {
if (!this.persistBetweenReboots && !this.initializationCompleted) {
this.log.debug(`Persistence disabled - ignoring cached value for ${key}`);
return defaultValue;
}
this.log.debug(`Loading cached value for ${key}`);
const cachedValue = this.storage.getItemSync(this.name + '-HMO-' + key);
if (cachedValue == undefined || cachedValue == null) {
return defaultValue;
}
return cachedValue;
}
//Helper to set/save a cached state value
saveCachedState (key, value) {
setTimeout(
function () {
this.storage.setItemSync(this.name + '-HMO-' + key, value)
}.bind(this),
10
);
}
setOccupancyDetected () {
this.locksCounter += 1;
this.stop();
this._setOccupancyState('Occupied');
if (this.stayOccupiedDelay) {
this.occupancyService.setCharacteristic(
TIME_REMAINING_CHARACTERISTIC_NAME,
this.stayOccupiedDelay
);
}
if (this.maxOccupationTimeout > 0 && this._max_occupation_timer == null) {
this._max_occupation_timer = setTimeout(
this.setOccupancyNotDetected.bind(this),
Math.round(this.maxOccupationTimeout * 1000)
);
}
//Save state
this.saveCachedState('_MAIN', {
TimeRemaining: this.stayOccupiedDelay ?? 0,
ModeState: 'Occupied'
});
this.locksCounter -= 1;
}
_setOccupancyState (newVal) {
// Capture the previous state and determine if the state change should be logged
this.previousModeState = this.modeState;
const occupancyLoggingCondition = (newVal == 'Occupied' && this.previousModeState == 'Unoccupied' || newVal == 'Unoccupied')
if (this.occupancyLogging && occupancyLoggingCondition) {
this.log(`Setting state to ${newVal}`)
}
// Set the new state
this.modeState = newVal;
this.log.debug(`Previous state was ${this.previousModeState} and is now ${this.modeState}`)
this.occupancyService.setCharacteristic(
Characteristic.OccupancyDetected,
newVal != 'Unoccupied'
? Characteristic.OccupancyDetected.OCCUPANCY_DETECTED
: Characteristic.OccupancyDetected.OCCUPANCY_NOT_DETECTED
);
}
setOccupancyNotDetected () {
var _this = this;
this.locksCounter += 1;
this.stop();
this._setOccupancyState('Unoccupied');
if (this.stayOccupiedDelay) {
this.occupancyService.setCharacteristic(TIME_REMAINING_CHARACTERISTIC_NAME, 0);
}
if (this.maxOccupationTimeout > 0 && this._max_occupation_timer == null) {
this._max_occupation_timer = setTimeout(
this.setOccupancyNotDetected.bind(this),
Math.round(this.maxOccupationTimeout * 1000)
);
}
//Clear max timeout
if (this._max_occupation_timer != null) {
this.log.debug('Max occupation timer stopped');
clearTimeout(this._max_occupation_timer);
this._max_occupation_timer = null;
}
//Turn all switches off
var shutoff_switch = aSwitch => {
let theValue = aSwitch
.getCharacteristic(Characteristic.On)
.value;
//still on, turn it off
if (theValue) {
_this.isClearingOccupancy = true;
aSwitch.setCharacteristic(Characteristic.On, false);
_this.isClearingOccupancy = false;
}
}
for (let i = 0; i < this.switches.length; i += 1) {
shutoff_switch(this.switches[i]._service);
}
//Save state
this.saveCachedState('_MAIN', {
TimeRemaining: 0,
ModeState: 'Unoccupied'
});
this.locksCounter -= 1;
}
/**
* Checks all the trigger switches to see if any of them are on. If so this
* Occupancy Sensor will remain "Occupied". This is used as a callback when
* the "On" state changes on any of the trigger switches.
*/
checkOccupancy (timeoutUntilCheck = 0) {
if (this.locksCounter > 0) {
this.log.debug(
`checking occupancy waiting for ${this.locksCounter} to clear; waiting for at least 100ms`
);
timeoutUntilCheck = Math.max(100, timeoutUntilCheck);
}
if (timeoutUntilCheck > 0) {
if (!this.isPendingCheckOccupancy) {
this.isPendingCheckOccupancy = true;
setTimeout(
function () {
this.isPendingCheckOccupancy = false
this.checkOccupancy()
}.bind(this),
timeoutUntilCheck
);
}
return
}
this.locksCounter += 1
const switchesToCheck = this.switches;
//Interpolate string to copy
const previousModeState = `${this.modeState}`;
this.log.debug(`checking occupancy. Total: ${switchesToCheck.length} switches`);
var result = {
already_acted: false,
remainingCount: switchesToCheck.length
};
var handleResponse = function (value) {
result.remainingCount -= 1;
if (result.already_acted) {
return;
}
if (value == true) {
result.already_acted = true;
if (this.modeState != 'Occupied') {
this.setOccupancyDetected();
}
this.log.debug(
`checkOccupancy result: true. Previous state: ${previousModeState}, current state: ${this.modeState}`
);
}
if (value == false && result.remainingCount == 0) {
result.already_acted = true;
if(previousModeState == 'Occupied') {
this.startUnoccupiedDelay();
}
this.log.debug(
`checkOccupancy result: false. Previous state: ${previousModeState}, current state: ${this.modeState}`
);
}
}.bind(this);
/* look at all the trigger switches "KeepingOccupancyTriggered" characteristic */
for (let i = 0; i < switchesToCheck.length; i += 1) {
if (result.already_acted) {
break;
}
handleResponse(switchesToCheck[i]._getIsKeepingOccupancyTriggered());
}
if (
switchesToCheck.length == 0 &&
this.modeState == 'Occupied' &&
result.already_acted == false
) {
this.startUnoccupiedDelay();
this.log.debug(
`checkOccupancy result: false (0 switches). Previous occupied state: ${previousModeState}, current state: ${this.modeState}`
);
}
this.locksCounter -= 1;
}
/**
* Homebridge function to return all the Services associated with this
* Accessory.
*
* @returns {*[]}
*/
getServices () {
var services = [this.occupancyService, this.informationService];
return services.concat(this.switches.map(switchItem => switchItem._service));
}
}
class BaseHelperSwitch {
constructor (occupancySensor, config, isStateful) {
this.log = occupancySensor.log;
this.config = occupancySensor.config;
this.api = occupancySensor.api;
this.occupancySensor = occupancySensor;
this.name = occupancySensor.name.trim() + ' ' + config.name.trim();
this._service = new Service.Switch(this.name.trim(), this.name.trim());
this.isStateful = isStateful;
this._offDelayTimer = null;
this._is_on = this.isStateful ? this.occupancySensor.getCachedState('PMS-' + this.name, false) : false;
this._service.setCharacteristic(Characteristic.On, this._is_on);
//Fix names getting messed up by iOS 16
this._service.addOptionalCharacteristic(Characteristic.ConfiguredName);
this._service.setCharacteristic(Characteristic.ConfiguredName, this.name.trim());
//Attach to changes
this._service
.getCharacteristic(Characteristic.On)
.on('set', this._internalStateChangeTrigger.bind(this));
}
_getIsKeepingOccupancyTriggered () {
//Overwritten in child classes
return this._is_on;
}
_killOccupancy () {
this.occupancySensor.locksCounter += 1;
this.occupancySensor.setOccupancyNotDetected();
setTimeout(
function () {
this.occupancySensor.checkOccupancy()
this.occupancySensor.locksCounter -= 1
}.bind(this),
10
);
}
_setOccupancyOn () {
this.occupancySensor.locksCounter += 1;
this.occupancySensor.setOccupancyDetected();
setTimeout(
function () {
this.occupancySensor.checkOccupancy();
this.occupancySensor.locksCounter -= 1;
}.bind(this),
10
);
}
_internalStateChangeTrigger (on, callback) {
//execute callback
try {
callback();
} catch (error) {
this.log.debug(`Callback error: BaseHelperSwitch._internalStateChangeTrigger - ${error}`);
}
//Determine if the state is different
const previousOn = this._is_on;
//Store new state
if(on != previousOn) {
this._is_on = on;
}
//Handle off switch canceling timer
this._handleOffDelayTimer(on);
//Make sure we're actually full initialized
if (!this.occupancySensor.initializationCompleted) {
this.log.debug(
'Setting ' + this.name + ' initial state and bypassing all events'
)
return
}
//Figure out if events should be suppressed
const suppressEvents = this.occupancySensor.isClearingOccupancy && on == false;
//Handle specific events
if(!suppressEvents) {
this._handleNewState(on, previousOn);
}
//Cache our previous state for restoration
if(on != previousOn && this.isStateful) {
this.occupancySensor.saveCachedState('PMS-' + this.name, on);
}
}
_handleOffDelayTimer(on) {
//Cancel if the timer exists first, always
if (this._offDelayTimer) {
clearTimeout(this._offDelayTimer);
this._offDelayTimer = null;
}
//Turn on the off delay timer if the switch is on
if(on && !this.isStateful) {
this._offDelayTimer = setTimeout(
function () {
this._service.setCharacteristic(Characteristic.On, false)
}.bind(this),
this.occupancySensor.triggerSwitchToggleTimeout
);
}
}
_handleNewState (on, previousOn) {
//Overwritten in child classes
}
}
class StatefulSwitch extends BaseHelperSwitch {
constructor (occupancySensor, config) {
super(occupancySensor, config, true);
this.stayOnOnly = config.stayOnOnly || false;
}
_handleNewState (on, previousOn) {
const isValidOn =
on &&
(!this.stayOnOnly || this.occupancySensor.modeState != 'Unoccupied');
if (isValidOn) {
this._setOccupancyOn();
}
if (!on && this.occupancySensor.modeState != 'Unoccupied') {
this.occupancySensor.checkOccupancy(10);
}
}
_getIsKeepingOccupancyTriggered () {
return (
this._is_on &&
(!this.stayOnOnly || this.occupancySensor.modeState != 'Unoccupied')
);
}
}
class TriggerSwitch extends BaseHelperSwitch {
constructor (occupancySensor, config) {
super(occupancySensor, config, false);
this.stayOnOnly = config.stayOnOnly || false;
}
_handleNewState (on, previousOn) {
if (
on &&
(!this.stayOnOnly || this.occupancySensor.modeState != 'Unoccupied')
) {
this._setOccupancyOn();
}
}
_getIsKeepingOccupancyTriggered () {
return false;
}
}
class LightSwitchMirrorSwitch extends BaseHelperSwitch {
constructor (occupancySensor, config) {
super(occupancySensor, config, true);
this.wasTheInitialTriggerSwitch = this.occupancySensor.getCachedState('PMS-wasInit-' + this.name, false);
//Make this switch match the big boi
this.occupancySensor.occupancyService
.getCharacteristic(Characteristic.OccupancyDetected)
.on(
'set',
function (occVal, callback) {
//execute callback
try {
callback()
} catch (error) {
this.log.debug(`Callback error: LightSwitchMirrorSwitch.constructor - ${error}`)
}
const properSwitchState = this.occupancySensor.modeState != 'Unoccupied';
if (this._is_on != properSwitchState) {
this._service.setCharacteristic(
Characteristic.On,
properSwitchState
)
}
}.bind(this)
);
}
_handleNewState (on, previousOn) {
//Figure out if this switch is the reason we're occupied and save that
if(this.occupancySensor.initializationCompleted && (!on || !previousOn)) {
this.wasTheInitialTriggerSwitch = on && this.occupancySensor.modeState == 'Unoccupied';
}
//Normal on behavior
if (on && this.occupancySensor.modeState != 'Occupied') {
this._setOccupancyOn();
}
//Handle turning off the whole system with this switch
if (!on) {
this._killOccupancy();
}
//Save cached state
this.occupancySensor.saveCachedState('PMS-wasInit-' + this.name, this.wasTheInitialTriggerSwitch);
}
_getIsKeepingOccupancyTriggered () {
return this._is_on && this.wasTheInitialTriggerSwitch;
}
}
class MasterShutoffSwitch extends BaseHelperSwitch {
constructor (occupancySensor, config) {
super(occupancySensor, config, false)
}
_handleNewState (on, previousOn) {
if (on) {
this._killOccupancy();
}
}
_getIsKeepingOccupancyTriggered () {
return false;
}
}