-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
__init__.py
1751 lines (1528 loc) · 69.3 KB
/
__init__.py
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
"""
This file is part of Entity Controller.
Entity Controller is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Entity Controller is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Entity Controller. If not, see <https://www.gnu.org/licenses/>.
"""
"""
Entity controller component for Home Assistant.
Maintainer: Daniel Mason
Version: v9.6.0
Project Page: https://danielbkr.net/projects/entity-controller/
Documentation: https://github.com/danobot/entity-controller
"""
import hashlib
import logging
import re
from datetime import date, datetime, time, timedelta
from threading import Timer
import pprint
from typing import Optional
import homeassistant.helpers.config_validation as cv
import voluptuous as vol
from homeassistant.const import CONF_NAME, SUN_EVENT_SUNRISE, SUN_EVENT_SUNSET
from homeassistant.core import callback, Context
from homeassistant.helpers import entity, event, service
from homeassistant.helpers.template import Template
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.helpers.sun import get_astral_event_date
from homeassistant.util import dt
import homeassistant.util.uuid as uuid_util
from transitions import Machine
from transitions.extensions import HierarchicalMachine as Machine
from homeassistant.helpers.service import async_call_from_config
DEPENDENCIES = ["light", "sensor", "binary_sensor", "cover", "fan", "media_player"]
from .const import (
DOMAIN,
DOMAIN_SHORT,
STATES,
CONF_START_TIME,
CONF_END_TIME,
CONF_TRANSITION_BEHAVIOUR_ON,
CONF_TRANSITION_BEHAVIOUR_OFF,
CONF_TRANSITION_BEHAVIOUR_IGNORE,
# Behaviours
CONF_BEHAVIOURS,
CONF_ON_ENTER_IDLE,
CONF_ON_EXIT_IDLE,
CONF_ON_ENTER_ACTIVE,
CONF_ON_EXIT_ACTIVE,
CONF_ON_ENTER_OVERRIDDEN,
CONF_ON_EXIT_OVERRIDDEN,
CONF_ON_ENTER_CONSTRAINED,
CONF_ON_EXIT_CONSTRAINED,
CONF_ON_ENTER_BLOCKED,
CONF_ON_EXIT_BLOCKED,
SENSOR_TYPE_DURATION,
SENSOR_TYPE_EVENT,
MODE_DAY,
MODE_NIGHT,
DEFAULT_DELAY,
DEFAULT_BRIGHTNESS,
DEFAULT_NAME,
CONF_CONTROL_ENTITIES,
CONF_CONTROL_ENTITY,
CONF_TRIGGER_ON_ACTIVATE,
CONF_TRIGGER_ON_DEACTIVATE,
CONF_SENSOR,
CONF_SENSORS,
CONF_SERVICE_DATA,
CONF_SERVICE_DATA_OFF,
CONF_STATE_ENTITIES,
CONF_DELAY,
CONF_BLOCK_TIMEOUT,
CONF_DISABLE_BLOCK,
CONF_SENSOR_TYPE_DURATION,
CONF_SENSOR_TYPE,
CONF_SENSOR_RESETS_TIMER,
CONF_NIGHT_MODE,
CONF_STATE_ATTRIBUTES_IGNORE,
CONF_IGNORED_EVENT_SOURCES,
CONSTRAIN_START,
CONSTRAIN_END,
CONTEXT_ID_CHARACTER_LIMIT
)
from .entity_services import (
async_setup_entity_services,
)
VERSION = '9.6.0'
_LOGGER = logging.getLogger(__name__)
devices = []
MODE_SCHEMA = vol.Schema(
{
vol.Optional(CONF_SERVICE_DATA, default=None): vol.Coerce(
dict
), # Default must be none because we differentiate between set and unset
vol.Optional(CONF_SERVICE_DATA_OFF, default=None): vol.Coerce(dict),
vol.Required(CONF_START_TIME): cv.string,
vol.Required(CONF_END_TIME): cv.string,
vol.Optional(CONF_DELAY, default=DEFAULT_DELAY): cv.positive_int,
}
)
ENTITY_SCHEMA = vol.Schema(
cv.has_at_least_one_key(
CONF_CONTROL_ENTITIES, CONF_CONTROL_ENTITY, CONF_TRIGGER_ON_ACTIVATE
),
{
# vol.Required(CONF_NAME): cv.string,
vol.Optional(CONF_DELAY, default=DEFAULT_DELAY): cv.positive_int,
vol.Optional(CONF_START_TIME): cv.string,
vol.Optional(CONF_END_TIME): cv.string,
vol.Optional(CONF_SENSOR_TYPE_DURATION, default=False): cv.boolean,
vol.Optional(CONF_SENSOR_TYPE, default=SENSOR_TYPE_EVENT): vol.All(
vol.Lower, vol.Any(SENSOR_TYPE_EVENT, SENSOR_TYPE_DURATION)
),
vol.Optional(CONF_SENSOR_RESETS_TIMER, default=False): cv.boolean,
vol.Optional(CONF_SENSOR, default=[]): cv.entity_ids,
vol.Optional(CONF_SENSORS, default=[]): cv.entity_ids,
vol.Optional(CONF_CONTROL_ENTITIES, default=[]): cv.entity_ids,
vol.Optional(CONF_CONTROL_ENTITY, default=[]): cv.entity_ids,
vol.Optional(CONF_TRIGGER_ON_ACTIVATE, default=None): cv.entity_ids,
vol.Optional(CONF_TRIGGER_ON_DEACTIVATE, default=None): cv.entity_ids,
vol.Optional(CONF_STATE_ENTITIES, default=[]): cv.entity_ids,
vol.Optional(CONF_BLOCK_TIMEOUT, default=None): cv.positive_int,
vol.Optional(CONF_DISABLE_BLOCK, default=False): cv.boolean,
# vol.Optional(CONF_IGNORE_STATE_CHANGES_UNTIL, default=None): cv.positive_int,
vol.Optional(CONF_NIGHT_MODE, default=None): MODE_SCHEMA,
vol.Optional(CONF_STATE_ATTRIBUTES_IGNORE, default=[]): cv.ensure_list,
vol.Optional(CONF_IGNORED_EVENT_SOURCES, default=[]): cv.ensure_list,
vol.Optional(CONF_SERVICE_DATA, default=None): vol.Coerce(
dict
),
vol.Optional(CONF_BEHAVIOURS, default=None): vol.Coerce(
dict
),
# Default must be none because we differentiate between set and unset
vol.Optional(CONF_SERVICE_DATA_OFF, default=None): vol.Coerce(dict),
},
# extra=vol.ALLOW_EXTRA,
)
PLATFORM_SCHEMA = cv.schema_with_slug_keys(ENTITY_SCHEMA)
async def async_setup(hass, config):
"""Load graph configurations."""
component = EntityComponent(_LOGGER, DOMAIN, hass)
_LOGGER.info(
"If you have ANY issues with EntityController (v"
+ VERSION
+ "), please enable DEBUG logging under the logger component and kindly report the issue on Github. https://github.com/danobot/entity-controller/issues"
)
async_setup_entity_services(component)
machine = Machine(
states=STATES,
initial="idle",
# title=self.name+" State Diagram",
# show_conditions=True
# show_auto_transitions = True,
finalize_event="finalize",
)
machine.add_transition(trigger="constrain", source="*", dest="constrained")
machine.add_transition(
trigger="override",
source=["idle", "active_timer", "blocked"],
dest="overridden",
)
machine.add_transition(
trigger="activate",
source=["idle", "blocked"],
dest="active",
)
machine.add_transition(
trigger="activate", source="active_timer", dest=None, after="_reset_timer"
)
# Idle
# machine.add_transition(trigger='sensor_off', source='idle', dest=None)
machine.add_transition(
trigger="sensor_on",
source="idle",
dest="active",
conditions=["is_state_entities_off"],
)
machine.add_transition(
trigger="sensor_on",
source="idle",
dest="active",
conditions=["is_state_entities_on"],
unless="is_block_enabled"
)
machine.add_transition(
trigger="sensor_on",
source="idle",
dest="blocked",
conditions=["is_state_entities_on", "is_block_enabled"],
)
machine.add_transition(trigger="enable", source="idle", dest=None, conditions=["is_state_entities_off"])
# Blocked
machine.add_transition(trigger="enable", source="blocked", dest="idle", conditions=["is_state_entities_off"])
machine.add_transition(
trigger="sensor_on", source="blocked", dest="blocked", conditions=["is_block_enabled"]
) # re-entering self-transition (on_enter callback executed.)
# Overridden
# machine.add_transition(trigger='enable', source='overridden', dest='idle')
machine.add_transition(
trigger="enable",
source="overridden",
dest="idle",
conditions=["is_state_entities_off"],
)
# If a device leaving overridden is on, we do not necessarily want to shut it off immediately. We simply want EC to stop controlling it. To do that, we'll move it to active, to simulate an EC trigger, and we'll see if it exits on its own. This works for event sensors, of course, and it will also work for duration sensors if the current state is on. A duration sensor that is off now will never expire on its own, though, so in that case, we'll assume the target is 'idle'.
machine.add_transition(
trigger="enable",
source="overridden",
dest="active",
conditions=["is_state_entities_on", "is_event_sensor"],
)
machine.add_transition(
trigger="enable",
source="overridden",
dest="active",
conditions=["is_state_entities_on", "is_sensor_on"],
) # This could be duration && on, but it will also work for any event sensor, so it's simpler to just write 'on'
machine.add_transition(
trigger="enable",
source="overridden",
dest="idle",
conditions=["is_state_entities_on", "is_duration_sensor", "is_sensor_off"],
)
machine.add_transition(
trigger="enter", source="active", dest="active_timer", unless="will_stay_on"
)
machine.add_transition(
trigger="enter",
source="active",
dest="active_stay_on",
conditions="will_stay_on",
)
# Active Timer
machine.add_transition(
trigger="sensor_on", source="active_timer", dest=None, after="_reset_timer"
)
# machine.add_transition(trigger='sensor_off', source='active_timer', dest=None, conditions=['is_event_sensor'])
machine.add_transition(
trigger="sensor_off_duration",
source="active_timer",
dest="idle",
conditions=["is_timer_expired"],
)
# The following two transitions must be kept seperate because they have
# special conditional logic that cannot be combined.
machine.add_transition(
trigger="timer_expires",
source="active_timer",
dest="idle",
conditions=["is_event_sensor"],
)
machine.add_transition(
trigger="timer_expires",
source="active_timer",
dest="idle",
conditions=["is_duration_sensor", "is_sensor_off"],
)
# machine.add_transition(trigger='block_timer_expires', source='blocked', dest='idle')
machine.add_transition(
trigger="block_timer_expires",
source="blocked",
dest="active",
conditions=["is_state_entities_on", "is_event_sensor"],
)
machine.add_transition(
trigger="block_timer_expires",
source="blocked",
dest="active",
conditions=["is_state_entities_on", "is_sensor_on"],
) # This could be duration && on, but it will also work for any event sensor, so it's simpler to just write 'on'
machine.add_transition(
trigger="block_timer_expires",
source="blocked",
dest="idle",
conditions=["is_state_entities_on", "is_duration_sensor", "is_sensor_off"],
)
# Active Timer
machine.add_transition(
trigger="control",
source="active_timer",
dest="idle",
conditions=["is_state_entities_off"]
)
machine.add_transition(trigger="control", source="active_timer",
dest="blocked", conditions=["is_state_entities_on", "is_block_enabled"])
# When block is disabled, "control" will reset the active timer
machine.add_transition(trigger="control", source="active_timer",
dest=None, after="_reset_timer", conditions=["is_state_entities_on"], unless="is_block_enabled")
# Manually enable blocked state
machine.add_transition(trigger="block_enable", source="active_timer",
dest="blocked", conditions=["is_state_entities_on", "is_block_enabled"])
# machine.add_transition(trigger='sensor_off', source='active_stay_on', dest=None)
# machine.add_transition(trigger="timer_expires", source="active_stay_on", dest=None)
machine.add_transition(
trigger="enable",
source="active_stay_on",
dest="idle",
conditions=["is_state_entities_off"]
)
# Constrained
machine.add_transition(
trigger="enable",
source="constrained",
dest="idle",
conditions=["is_override_state_off"],
)
machine.add_transition(
trigger="enable",
source="constrained",
dest="overridden",
conditions=["is_override_state_on"],
)
# Enter blocked state when component is enabled and entity is on
machine.add_transition(trigger="blocked", source="constrained", dest="blocked", conditions=["is_block_enabled"])
for myconfig in config[DOMAIN]:
_LOGGER.info("Domain Configuration: " + str(myconfig))
for key, config in myconfig.items():
if not config:
config = {}
# _LOGGER.info("Config Item %s: %s", str(key), str(config))
config["name"] = key
m = None
m = EntityController(hass, config, machine)
# machine.add_model(m.model)
# m.model.after_model(config)
devices.append(m)
await component.async_add_entities(devices)
_LOGGER.info("The %s component is ready!", DOMAIN)
return True
class EntityController(entity.Entity):
from .entity_services import (
async_entity_service_activate as async_activate,
async_entity_service_clear_block as async_clear_block,
async_entity_service_enable_block as async_enable_block,
async_entity_service_enable_stay_mode as async_enable_stay_mode,
async_entity_service_disable_stay_mode as async_disable_stay_mode,
async_entity_service_set_night_mode as async_set_night_mode,
)
def __init__(self, hass, config, machine):
self.attributes = {}
self.may_update = False
self.model = None
self.friendly_name = config.get(CONF_NAME, "Motion Light")
if "friendly_name" in config:
self.friendly_name = config.get("friendly_name")
try:
self.model = Model(hass, config, machine, self)
except AttributeError as e:
_LOGGER.error(
"Configuration error! Please ensure you use plural keys for lists. e.g. sensors, entities." + e
)
event.async_call_later(hass, 1, self.do_update)
@property
def state(self):
"""Return the state of the entity."""
return self.model.state
@property
def name(self):
"""Return the state of the entity."""
return self.friendly_name
@property
def icon(self):
"""Return the entity icon."""
if self.model.state == "idle":
return "mdi:circle-outline"
if self.model.state == "active":
return "mdi:check-circle"
if self.model.state == "active_timer":
return "mdi:timer-outline"
if self.model.state == "constrained":
return "mdi:cancel"
if self.model.state == "overridden":
return "mdi:timer-off-outline"
if self.model.state == "blocked":
return "mdi:close-circle"
return "mdi:eye"
@property
def state_attributes(self):
"""Return the state of the entity."""
return self.attributes.copy()
def reset_state(self):
""" Reset state attributes by removing any state specific attributes when returning to idle state """
_LOGGER.debug("Resetting state")
att = {}
PERSISTED_STATE_ATTRIBUTES = [
"last_triggered_by",
"last_triggered_at",
CONF_STATE_ENTITIES,
"control_entities",
"sensor_entities",
"override_entities",
CONF_DELAY,
"sensor_type",
"mode",
"start_time",
"end_time",
]
for k, v in self.attributes.items():
if k in PERSISTED_STATE_ATTRIBUTES:
att[k] = v
self.attributes = att
self.do_update()
@callback
def do_update(self, wait=False, **kwargs):
""" Schedules an entity state update with HASS """
# _LOGGER.debug("Scheduled update with HASS")
if self.may_update:
self.async_schedule_update_ha_state(True)
def set_attr(self, k, v):
if k == CONF_DELAY:
v = str(v) + "s"
self.attributes[k] = v
# HA Callbacks
async def async_added_to_hass(self):
"""Register update dispatcher."""
self.may_update = True
@property
def should_poll(self) -> bool:
"""EntityController will push its state to HA"""
return False
class Model:
""" Represents the transitions state machine model """
def __init__(self, hass, config, machine, entity):
self.hass = hass # backwards reference to hass object
self.entity = entity # backwards reference to entity containing this model
self.config = (
{}
) # new way of storing configuration (avoids having an attribue for each)
self.config = config
self.debug_day_length = config.get("day_length", None)
self.stateEntities = []
self.controlEntities = []
self.sensorEntities = []
self.triggerOnDeactivate = []
self.triggerOnActivate = []
self.timer_handle = None
self.block_timer_handle = None
self.sensor_type = None
self.night_mode = None
self.state_attributes_ignore = []
self.backoff = False
self.backoff_count = 0
self.light_params_day = {}
self.light_params_night = {}
self.lightParams = {}
self.name = None
self.stay = False
self.start = None
self.end = None
self.reset_count = None
self.transition_behaviours = {}
# logging.setFormatter(logging.Formatter(FORMAT))
self.log = logging.getLogger(__name__ + "." + config.get(CONF_NAME))
self.ignored_event_sources = []
self.context = None
self.log.debug(
"Initialising EntityController entity with this configuration: "
)
self.log.debug(
pprint.pformat(config)
)
self.name = config.get(CONF_NAME, "Unnamed Entity Controller")
self.ignored_event_sources = []
machine.add_model(
self
) # add here because machine generated methods are being used in methods below.
self.config_static_strings(config)
self.config_control_entities(config)
self.config_state_entities(
config
) # must come after config_control_entities (uses control entities if not set)
self.config_sensor_entities(config)
self.config_override_entities(config)
self.config_transition_behaviours(config)
self.config_off_entities(config)
self.config_on_entities(config)
self.config_normal_mode(config)
self.config_night_mode(
config
) # must come after normal_mode (uses normal mode parameters if not set)
self.config_state_attributes_ignore(config)
self.config_times(config)
self.config_other(config)
self.prepare_service_data()
def update(self, wait=False, **kwargs):
""" Called from different methods to report a state attribute change """
# self.log.debug("Update called with {}".format(str(kwargs)))
for k, v in kwargs.items():
if v is not None:
self.entity.set_attr(k, v)
if wait == False:
self.entity.do_update()
def finalize(self):
self.entity.do_update()
# =====================================================
# S T A T E C H A N G E C A L L B A C K S
# =====================================================
@callback
def sensor_state_change(self, entity, old, new):
""" State change callback for sensor entities """
self.log.debug("sensor_state_change :: %10s Sensor state change to: %s" % ( pprint.pformat(entity), new.state))
self.log.debug("sensor_state_change :: state: " + pprint.pformat(self.state))
try:
if new.state == old.state:
self.log.debug("sensor_state_change :: Ignore attribute only change")
return
except AttributeError:
self.log.debug("sensor_state_change :: old NoneType")
pass
if self.matches(new.state, self.SENSOR_ON_STATE) and (
self.is_idle() or self.is_active_timer() or self.is_blocked()
):
self.set_context(new.context)
self.update(last_triggered_by=entity)
self.sensor_on()
if (
self.matches(new.state, self.SENSOR_OFF_STATE)
and self.is_duration_sensor()
and self.is_active_timer()
):
self.set_context(new.context)
self.update(last_triggered_by=entity, sensor_turned_off_at=datetime.now())
# If configured, reset timer when duration sensor goes off
if self.config[CONF_SENSOR_RESETS_TIMER]:
self.log.debug("sensor_state_change :: CONF_SENSOR_RESETS_TIMER")
self.update(
notes="The sensor turned off and reset the timeout. Timer started."
)
self._reset_timer()
else:
# We only care about sensor off state changes when the sensor is a duration sensor and we are in active_timer state.
self.sensor_off_duration()
self.log.debug("sensor_state_change :: CONF_SENSOR_RESETS_TIMER - normal")
@callback
def override_state_change(self, entity, old, new):
""" State change callback for override entities """
self.log.debug("override_state_change :: Override state change entity=%s, old=%s, new=%s" % ( entity, old, new))
if self.matches(new.state, self.OVERRIDE_ON_STATE) and (
self.is_active()
or self.is_active_timer()
or self.is_idle()
or self.is_blocked()
):
self.set_context(new.context)
self.update(overridden_by=entity)
self.override()
self.update(overridden_at=str(datetime.now()))
if (
self.matches(new.state, self.OVERRIDE_OFF_STATE)
and self.is_override_state_off()
and self.is_overridden()
):
self.set_context(new.context)
self.enable()
@callback
def state_entity_state_change(self, entity, old, new):
""" State change callback for state entities. This can be called with either a state change or an attribute change. """
self.log.debug(
"state_entity_state_change :: [ Entity: %s, Context: %s ]\n\tOld state: %s\n\tNew State: %s",
str(entity),
str(new.context),
str(old),
str(new)
)
if self.is_ignored_context(new.context):
self.log.debug("state_entity_state_change :: Ignoring this state change because it came from %s" % (new.context.id))
return
# If the state changed, we definitely want to handle the transition. If only attributes changed, we'll check if the new attributes are significant (i.e., not being ignored).
try:
if not old or not new or old == 'off' or new == 'off':
pass
else:
if old.state == new.state: # Only attributes changed
# Build two dictionaries of attributes, excluding the ones we don't want to monitor
old_temp = {
key: old.attributes[key]
for key in old.attributes
if key not in self.state_attributes_ignore
}
new_temp = {
key: new.attributes[key]
for key in new.attributes
if key not in self.state_attributes_ignore
}
if old_temp == new_temp:
self.log.debug("state_entity_state_change :: insignificant attribute change - Ignore the state change altogether")
return
self.log.debug("state_entity_state_change :: A significant attribute changed and will be handled")
except AttributeError as a:
# Most likely one of the states, either new or old, is 'off', so there's no attributes dict attached to the state object.
self.log.debug(
"state_entity_state_change :: Most likely one of the states, either new or old, is 'off', so there's no attributes dict attached to the state object: "
+ str(a)
)
self.set_context(new.context)
if self.is_active_timer():
self.log.debug("state_entity_state_change :: We are in active timer and the state of observed state entities changed.")
self.control()
if self.is_blocked() or self.is_active_stay_on(): # if statement required to avoid MachineErrors, cleaner than adding transitions to all possible states.
self.enable()
def _start_timer(self):
self.log.info("_start_timer :: Light params: " + str(self.lightParams))
if self.backoff_count == 0:
self.previous_delay = self.lightParams.get(CONF_DELAY, DEFAULT_DELAY)
else:
self.log.debug(
"_start_timer :: Backoff: %s, count: %s, delay%s, factor: %s",
self.backoff,
self.backoff_count,
self.lightParams.get(CONF_DELAY, DEFAULT_DELAY),
self.backoff_factor,
)
self.previous_delay = round(self.previous_delay * self.backoff_factor, 2)
if self.previous_delay > self.backoff_max:
self.log.debug("Max backoff reached. Will not increase further.")
self.previous_delay = self.backoff_max
self.update(delay=self.previous_delay)
expiry_time = datetime.now() + timedelta(seconds=self.previous_delay)
# not able to use async_call_later because no known way to check whether timer is active.
# self.timer_handle = event.async_call_later(self.hass, self.previous_delay, self.timer_expire)
self.timer_handle = Timer(self.previous_delay, self.timer_expire)
self.timer_handle.start()
self.update(expires_at=expiry_time)
def _cancel_timer(self):
if self.timer_handle.is_alive():
self.timer_handle.cancel()
def _reset_timer(self):
self.log.debug("_reset_timer :: Resetting timer: " + str(self.backoff))
self._cancel_timer()
self.update(reset_at=datetime.now())
if self.backoff:
self.backoff_count += 1
self.update(backoff_count=self.backoff_count)
self._start_timer()
return True
def timer_expire(self):
self.log.debug("timer_expire :: Timer expired")
if self.is_duration_sensor() and self.is_sensor_on(): # Ignore timer expiry because duration sensor overwrites timer
self.update(expires_at="pending sensor")
else:
self.log.debug("timer_expire :: Trigger timer_expires event")
self.timer_expires()
def block_timer_expire(self):
self.log.debug("block_timer_expire :: Blocked Timer expired")
self.block_timer_expires()
# =====================================================
# S T A T E M A C H I N E C O N D I T I O N S
# =====================================================
def _override_entity_state(self):
for e in self.overrideEntities:
s = self.hass.states.get(e)
try:
state = s.state
except AttributeError as ex:
self.log.error(
"Potential configuration error: Override Entity ({}) does not exist (yet). Please check for spelling and typos. {}".format(
e, ex
)
)
return None
if self.matches(state, self.OVERRIDE_ON_STATE):
self.log.debug("Override entities are ON. [%s]", e)
return e
self.log.debug("Override entities are OFF.")
return None
def is_override_state_off(self):
return self._override_entity_state() is None
# def is_within_grace_period(self):
# """ Dtermines if the last service call EC made was within the last 2 seconds.
# This is important or else EC will react to state changes caused by EC itself which results in going into blocked state."""
# return datetime.now() < self.ignore_state_changes_until
def is_override_state_on(self):
return self._override_entity_state() is not None
def _sensor_entity_state(self):
for e in self.sensorEntities:
s = self.hass.states.get(e)
try:
state = s.state
except AttributeError as ex:
self.log.error(
"Potential configuration error: Sensor Entity ({}) does not exist (yet). Please check for spelling and typos. {}".format(
e, ex
)
)
return None
if self.matches(state, self.SENSOR_ON_STATE):
self.log.debug("Sensor entities are ON. [%s]", e)
return e
self.log.debug("Sensor entities are OFF.")
return None
def is_sensor_off(self):
return self._sensor_entity_state() is None
def is_sensor_on(self):
return self._sensor_entity_state() is not None
def _state_entity_state(self):
for e in self.stateEntities:
s = self.hass.states.get(e)
self.log.info(s)
try:
state = s.state
except AttributeError as ex:
self.log.error(
"Potential configuration error: State Entity ({}) does not exist (yet). Please check for spelling and typos. {}".format(
e, ex
)
)
state = 'off'
return None
if self.matches(state, self.STATE_ON_STATE):
self.log.debug("State entities are ON. [%s]", e)
return e
self.log.debug("State entities are OFF.")
return None
def is_state_entities_off(self):
return self._state_entity_state() is None
def is_state_entities_on(self):
return self._state_entity_state() is not None
def is_block_enabled(self):
return self.disable_block is False
def will_stay_on(self):
return self.stay
def is_night(self):
if self.night_mode is None:
return False # if night mode is undefined, it's never night :)
else:
self.log.debug("NIGHT MODE ENABLED: " + str(self.night_mode))
return self.now_is_between(
self.night_mode[CONF_START_TIME], self.night_mode[CONF_END_TIME]
)
def is_event_sensor(self):
return self.sensor_type == SENSOR_TYPE_EVENT
def is_duration_sensor(self):
return self.sensor_type == SENSOR_TYPE_DURATION
def is_timer_expired(self):
expired = self.timer_handle.is_alive() == False
return expired
def does_sensor_reset_timer(self):
return self.config[CONF_SENSOR_RESETS_TIMER]
# =====================================================
# S T A T E M A C H I N E C A L L B A C K S
# =====================================================
def on_enter_idle(self):
self.log.debug("Entering idle")
# Entering idle due to no events, set a new context with no parent
self.set_context(None)
self.do_transition_behaviour(CONF_ON_ENTER_IDLE)
self.entity.reset_state()
def on_exit_idle(self):
self.log.debug("Exiting idle")
self.do_transition_behaviour(CONF_ON_EXIT_IDLE)
def on_enter_overridden(self):
self.log.debug("Entering overridden")
self.do_transition_behaviour(CONF_ON_ENTER_OVERRIDDEN)
def on_exit_overridden(self):
self.log.debug("Exiting overridden")
self.do_transition_behaviour(CONF_ON_EXIT_OVERRIDDEN)
def on_enter_active(self):
self.log.debug("Entering active")
self.update(last_triggered_at=str(datetime.now()))
self.backoff_count = 0
self.prepare_service_data()
self._start_timer()
self.log.debug("on_enter_active :: light params before turning on: " + str(self.lightParams))
self.do_transition_behaviour(CONF_ON_ENTER_ACTIVE)
self.enter()
def on_exit_active(self):
self.log.debug("Exiting active")
self.log.debug("on_exit_active :: Turning off entities, cancelling timer")
self._cancel_timer() # cancel previous timer
self.update(
delay=self.lightParams.get(CONF_DELAY)
) # no need to update immediately
self.do_transition_behaviour(CONF_ON_EXIT_ACTIVE)
def on_enter_blocked(self):
self.log.debug("Entering blocked")
self.update(blocked_at=datetime.now())
self.update(blocked_by=self._state_entity_state())
self.do_transition_behaviour(CONF_ON_ENTER_BLOCKED)
if self.block_timeout:
self.block_timer_handle = Timer(self.block_timeout, self.block_timer_expire)
self.block_timer_handle.start()
self.update(block_timeout=self.block_timeout)
def on_exit_blocked(self):
self.log.debug("Exiting blocked")
self.do_transition_behaviour(CONF_ON_EXIT_BLOCKED)
if self.block_timer_handle and self.block_timer_handle.is_alive():
self.block_timer_handle.cancel()
def on_enter_constrained(self):
self.log.debug("Entering constrained")
self.do_transition_behaviour(CONF_ON_ENTER_CONSTRAINED)
def on_exit_constrained(self):
self.log.debug("Exiting constrained")
self.do_transition_behaviour(CONF_ON_EXIT_CONSTRAINED)
# =====================================================
# C O N F I G U R A T I O N & V A L I D A T I O N
# =====================================================
def config_transition_behaviours(self, config):
self.transition_behaviours = {
CONF_ON_ENTER_IDLE: CONF_TRANSITION_BEHAVIOUR_OFF, # By default turn off
CONF_ON_EXIT_IDLE: CONF_TRANSITION_BEHAVIOUR_IGNORE,
CONF_ON_ENTER_ACTIVE: CONF_TRANSITION_BEHAVIOUR_ON, # By default turn on
CONF_ON_EXIT_ACTIVE: CONF_TRANSITION_BEHAVIOUR_IGNORE,
CONF_ON_ENTER_OVERRIDDEN: CONF_TRANSITION_BEHAVIOUR_IGNORE,
CONF_ON_EXIT_OVERRIDDEN: CONF_TRANSITION_BEHAVIOUR_IGNORE,
CONF_ON_ENTER_CONSTRAINED: CONF_TRANSITION_BEHAVIOUR_IGNORE,
CONF_ON_EXIT_CONSTRAINED: CONF_TRANSITION_BEHAVIOUR_IGNORE,
CONF_ON_ENTER_BLOCKED: CONF_TRANSITION_BEHAVIOUR_IGNORE,
CONF_ON_EXIT_BLOCKED: CONF_TRANSITION_BEHAVIOUR_IGNORE,
}
if CONF_BEHAVIOURS in config:
self.transition_behaviours = {**self.transition_behaviours, **config[CONF_BEHAVIOURS]}
self.log.debug("config_transition_behaviours :: Transition Behaviours: " + pprint.pformat(self.transition_behaviours))
def config_control_entities(self, config):
self.controlEntities = []
self.add(self.controlEntities, config, CONF_CONTROL_ENTITY)
self.add(self.controlEntities, config, CONF_CONTROL_ENTITIES)
self.log.debug("Control Entities: " + pprint.pformat(self.controlEntities))
def config_state_entities(self, config):
self.stateEntities = []
self.add(
self.stateEntities, config, CONF_STATE_ENTITIES
) # adding optimistically
if len(self.stateEntities) > 0: # now checking whether they actually exist
self.log.info(
"State Entities (explicitly defined - I hope you know what you are doing): " + str(self.stateEntities)
)
event.async_track_state_change(
self.hass, self.stateEntities, self.state_entity_state_change
)
if len(self.stateEntities) == 0:
# If no state entities are defined, use control entites as state
self.stateEntities = self.controlEntities.copy()
self.log.debug(
"Added Control Entities as state entities (default): " + str(self.stateEntities)
)
event.async_track_state_change(
self.hass, self.stateEntities, self.state_entity_state_change
)
def config_off_entities(self, config):
self.triggerOnDeactivate = []
self.add(self.triggerOnDeactivate, config, CONF_TRIGGER_ON_DEACTIVATE)
if len(self.triggerOnDeactivate) > 0:
self.log.info("Off Entities: " + pprint.pformat(self.triggerOnDeactivate))
def config_on_entities(self, config):
self.triggerOnActivate = []
self.add(self.triggerOnActivate, config, CONF_TRIGGER_ON_ACTIVATE)
if len(self.triggerOnActivate) > 0:
self.log.info("On Entities: " + pprint.pformat(self.triggerOnActivate))
def config_sensor_entities(self, config):
self.sensorEntities = []
self.add(self.sensorEntities, config, CONF_SENSOR)
self.add(self.sensorEntities, config, CONF_SENSORS)
if len(self.sensorEntities) == 0:
self.log.error(
"No sensor entities defined. You must define at least one sensor entity."
)
self.log.debug("Sensor Entities: " + pprint.pformat(self.sensorEntities))
event.async_track_state_change(
self.hass, self.sensorEntities, self.sensor_state_change
)
def config_static_strings(self, config):
DEFAULT_ON = ["on", "playing", "home", "True"]
DEFAULT_OFF = ["off", "idle", "paused", "away", "False"]