-
-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathautomoli.py
More file actions
1241 lines (1023 loc) · 42.8 KB
/
automoli.py
File metadata and controls
1241 lines (1023 loc) · 42.8 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
"""AutoMoLi.
Automatic Motion Lights
@benleb / https://github.com/benleb/ad-automoli
"""
from __future__ import annotations
import asyncio
from collections.abc import Coroutine, Iterable
from copy import deepcopy
from datetime import time
from packaging.version import Version
from enum import Enum, IntEnum
from inspect import stack
import logging
from pprint import pformat
import random
from typing import Any
# pylint: disable=import-error
import hassapi as hass
__version__ = "0.11.4"
APP_NAME = "AutoMoLi"
APP_ICON = "💡"
ON_ICON = APP_ICON
OFF_ICON = "🌑"
DIM_ICON = "🔜"
DAYTIME_SWITCH_ICON = "⏰"
# default values
DEFAULT_NAME = "daytime"
DEFAULT_LIGHT_SETTING = 100
DEFAULT_DELAY = 150
DEFAULT_DIM_METHOD = "step"
DEFAULT_DAYTIMES: list[dict[str, str | int]] = [
dict(starttime="05:30", name="morning", light=25),
dict(starttime="07:30", name="day", light=100),
dict(starttime="20:30", name="evening", light=90),
dict(starttime="22:30", name="night", light=0),
]
DEFAULT_LOGLEVEL = "INFO"
EVENT_MOTION_XIAOMI = "xiaomi_aqara.motion"
RANDOMIZE_SEC = 5
SECONDS_PER_MIN: int = 60
class EntityType(Enum):
LIGHT = "light."
MOTION = "binary_sensor.motion_sensor_"
HUMIDITY = "sensor.humidity_"
ILLUMINANCE = "sensor.illumination_"
DOOR_WINDOW = "binary_sensor.door_window_sensor_"
@property
def idx(self) -> str:
return self.name.casefold()
@property
def prefix(self) -> str:
return str(self.value).casefold()
SENSORS_REQUIRED = [EntityType.MOTION.idx]
SENSORS_OPTIONAL = [EntityType.HUMIDITY.idx, EntityType.ILLUMINANCE.idx]
KEYWORDS = {
EntityType.LIGHT.idx: "light.",
EntityType.MOTION.idx: "binary_sensor.motion_sensor_",
EntityType.HUMIDITY.idx: "sensor.humidity_",
EntityType.ILLUMINANCE.idx: "sensor.illumination_",
EntityType.DOOR_WINDOW.idx: "binary_sensor.door_window_sensor_",
}
def install_pip_package(
pkg: str,
version: str = "",
install_name: str | None = None,
pre_release: bool = False,
) -> None:
import importlib
import site
from subprocess import check_call # nosec
import sys
try:
importlib.import_module(pkg)
except ImportError:
install_name = install_name if install_name else pkg
if pre_release:
check_call(
[
sys.executable,
"-m",
"pip",
"install",
"--upgrade",
"--pre",
f"{install_name}{version}",
]
)
else:
check_call(
[
sys.executable,
"-m",
"pip",
"install",
"--upgrade",
f"{install_name}{version}",
]
)
importlib.reload(site)
finally:
importlib.import_module(pkg)
# install adutils library
install_pip_package("adutils", version=">=0.6.2")
from adutils import Room, hl, natural_time, py38_or_higher, py39_or_higher # noqa
from adutils import py37_or_higher # noqa
class DimMethod(IntEnum):
"""IntEnum representing the transition-to-off method used."""
NONE = 0
TRANSITION = 1
STEP = 2
class AutoMoLi(hass.Hass): # type: ignore
"""Automatic Motion Lights."""
def lg(
self,
msg: str,
*args: Any,
level: int | None = None,
icon: str | None = None,
repeat: int = 1,
log_to_ha: bool = False,
**kwargs: Any,
) -> None:
kwargs.setdefault("ascii_encode", False)
level = level if level else self.loglevel
if level >= self.loglevel:
message = f"{f'{icon} ' if icon else ' '}{msg}"
_ = [self.log(message, *args, **kwargs) for _ in range(repeat)]
if log_to_ha or self.log_to_ha:
message = message.replace("\033[1m", "").replace("\033[0m", "")
# Python community recommend a strategy of
# "easier to ask for forgiveness than permission"
# https://stackoverflow.com/a/610923/13180763
try:
ha_name = self.room.name.capitalize()
except AttributeError:
ha_name = APP_NAME
self.lg(
"No room set yet, using 'AutoMoLi' forlogging to HA",
level=logging.DEBUG,
)
self.call_service(
"logbook/log",
name=ha_name, # type:ignore
message=message, # type:ignore
entity_id="light.esszimmer_decke", # type:ignore
)
def listr(
self,
list_or_string: list[str] | set[str] | str | Any,
entities_exist: bool = True,
) -> set[str]:
entity_list: list[str] = []
if isinstance(list_or_string, str):
entity_list.append(list_or_string)
elif isinstance(list_or_string, (list, set)):
entity_list += list_or_string
elif list_or_string:
self.lg(
f"{list_or_string} is of type {type(list_or_string)} and "
f"not 'Union[List[str], Set[str], str]'"
)
return set(
filter(self.entity_exists, entity_list) if entities_exist else entity_list
)
async def initialize(self) -> None:
"""Initialize a room with AutoMoLi."""
# pylint: disable=attribute-defined-outside-init
self.icon = APP_ICON
# get a real dict for the configuration
self.args: dict[str, Any] = dict(self.args)
self.loglevel = (
logging.DEBUG if self.args.get("debug_log", False) else logging.INFO
)
self.log_to_ha = self.args.get("log_to_ha", False)
# notification thread (prevents doubled messages)
self.notify_thread = random.randint(0, 9) # nosec
self.lg(
f"setting log level to {logging.getLevelName(self.loglevel)}",
level=logging.DEBUG,
)
# python version check
if not py39_or_higher:
self.lg("")
self.lg(f" hey, what about trying {hl('Python >= 3.9')}‽ 🤪")
self.lg("")
if not py38_or_higher:
icon_alert = "⚠️"
self.lg("", icon=icon_alert)
self.lg("")
self.lg(
f" please update to {hl('Python >= 3.8')} at least! 🤪", icon=icon_alert
)
self.lg("")
self.lg("", icon=icon_alert)
if not py37_or_higher:
raise ValueError
# set room
self.room_name = str(self.args.pop("room"))
# general delay
self.delay = int(self.args.pop("delay", DEFAULT_DELAY))
# directly switch to new daytime light settings
self.transition_on_daytime_switch: bool = bool(
self.args.pop("transition_on_daytime_switch", False)
)
# state values
self.states = {
"motion_on": self.args.pop("motion_state_on", None),
"motion_off": self.args.pop("motion_state_off", None),
}
# threshold values
self.thresholds = {
"humidity": self.args.pop("humidity_threshold", None),
EntityType.ILLUMINANCE.idx: self.args.pop("illuminance_threshold", None),
}
# experimental dimming features
self.dimming: bool = False
self.dim: dict[str, int | DimMethod] = {}
if (dim := self.args.pop("dim", {})) and (
seconds_before := dim.pop("seconds_before", None)
):
brightness_step_pct = dim.pop("brightness_step_pct", None)
dim_method: DimMethod | None = None
if method := dim.pop("method", None):
dim_method = (
DimMethod.TRANSITION
if method.lower() == "transition"
else DimMethod.STEP
)
elif brightness_step_pct:
dim_method = DimMethod.TRANSITION
else:
dim_method = DimMethod.NONE
self.dim = { # type: ignore
"brightness_step_pct": brightness_step_pct,
"seconds_before": int(seconds_before),
"method": dim_method.value,
}
# night mode settings
self.night_mode: dict[str, int | str] = {}
if night_mode := self.args.pop("night_mode", {}):
self.night_mode = await self.configure_night_mode(night_mode)
# on/off switch via input.boolean
self.disable_switch_entities: set[str] = self.listr(
self.args.pop("disable_switch_entities", set())
)
self.disable_switch_states: set[str] = self.listr(
self.args.pop("disable_switch_states", set(["off"]))
)
# store if an entity has been switched on by automoli
self.only_own_events: bool = bool(self.args.pop("only_own_events", False))
self._switched_on_by_automoli: set[str] = set()
self.disable_hue_groups: bool = self.args.pop("disable_hue_groups", False)
# eol of the old option name
if "disable_switch_entity" in self.args:
icon_alert = "⚠️"
self.lg("", icon=icon_alert)
self.lg(
f" please migrate {hl('disable_switch_entity')} to {hl('disable_switch_entities')}",
icon=icon_alert,
)
self.lg("", icon=icon_alert)
self.args.pop("disable_switch_entity")
return
# currently active daytime settings
self.active: dict[str, int | str] = {}
# entity lists for initial discovery
states = await self.get_state()
self.handle_turned_off: str | None = None
# define light entities switched by automoli
self.lights: set[str] = self.args.pop("lights", set())
if not self.lights:
room_light_group = f"light.{self.room_name}"
if await self.entity_exists(room_light_group):
self.lights.add(room_light_group)
else:
self.lights.update(
await self.find_sensors(
EntityType.LIGHT.prefix, self.room_name, states
)
)
# sensors
self.sensors: dict[str, Any] = {}
# enumerate sensors for motion detection
self.sensors[EntityType.MOTION.idx] = self.listr(
self.args.pop(
"motion",
await self.find_sensors(
EntityType.MOTION.prefix, self.room_name, states
),
)
)
self.room = Room(
name=self.room_name,
room_lights=self.lights,
motion=self.sensors[EntityType.MOTION.idx],
door_window=set(),
temperature=set(),
push_data=dict(),
appdaemon=self.get_ad_api(),
)
# requirements check
if not self.lights or not self.sensors[EntityType.MOTION.idx]:
self.lg("")
self.lg(
f"{hl('No lights/sensors')} given and none found with name: "
f"'{hl(EntityType.LIGHT.prefix)}*{hl(self.room.name)}*' or "
f"'{hl(EntityType.MOTION.prefix)}*{hl(self.room.name)}*'",
icon="⚠️ ",
)
self.lg("")
self.lg(" docs: https://github.com/benleb/ad-automoli")
self.lg("")
return
# enumerate optional sensors & disable optional features if sensors are not available
for sensor_type in SENSORS_OPTIONAL:
if sensor_type in self.thresholds and self.thresholds[sensor_type]:
self.sensors[sensor_type] = self.listr(
self.args.pop(sensor_type, None)
) or await self.find_sensors(
KEYWORDS[sensor_type], self.room_name, states
)
self.lg(f"{self.sensors[sensor_type] = }", level=logging.DEBUG)
else:
self.lg(
f"No {sensor_type} sensors → disabling features based on {sensor_type}"
f" - {self.thresholds[sensor_type]}.",
level=logging.DEBUG,
)
del self.thresholds[sensor_type]
# use user-defined daytimes if available
daytimes = await self.build_daytimes(
self.args.pop("daytimes", DEFAULT_DAYTIMES)
)
# set up event listener for each sensor
listener: set[Coroutine[Any, Any, Any]] = set()
for sensor in self.sensors[EntityType.MOTION.idx]:
# listen to xiaomi sensors by default
if not any([self.states["motion_on"], self.states["motion_off"]]):
self.lg(
"no motion states configured - using event listener",
level=logging.DEBUG,
)
listener.add(
self.listen_event(
self.motion_event, event=EVENT_MOTION_XIAOMI, entity_id=sensor
)
)
# on/off-only sensors without events on every motion
elif all([self.states["motion_on"], self.states["motion_off"]]):
self.lg(
"both motion states configured - using state listener",
level=logging.DEBUG,
)
listener.add(
self.listen_state(
self.motion_detected,
entity_id=sensor,
new=self.states["motion_on"],
)
)
listener.add(
self.listen_state(
self.motion_cleared,
entity_id=sensor,
new=self.states["motion_off"],
)
)
self.args.update(
{
"room": self.room_name.capitalize(),
"delay": self.delay,
"active_daytime": self.active_daytime,
"daytimes": daytimes,
"lights": self.lights,
"dim": self.dim,
"sensors": self.sensors,
"disable_hue_groups": self.disable_hue_groups,
"only_own_events": self.only_own_events,
"loglevel": self.loglevel,
}
)
if self.thresholds:
self.args.update({"thresholds": self.thresholds})
# add night mode to config if enabled
if self.night_mode:
self.args.update({"night_mode": self.night_mode})
# add disable entity to config if given
if self.disable_switch_entities:
self.args.update({"disable_switch_entities": self.disable_switch_entities})
self.args.update({"disable_switch_states": self.disable_switch_states})
# show parsed config
self.show_info(self.args)
await asyncio.gather(*listener)
await self.refresh_timer()
async def switch_daytime(self, kwargs: dict[str, Any]) -> None:
"""Set new light settings according to daytime."""
daytime = kwargs.get("daytime")
if daytime is not None:
self.active = daytime
if not kwargs.get("initial"):
delay = daytime["delay"]
light_setting = daytime["light_setting"]
if isinstance(light_setting, str):
is_scene = True
# if its a ha scene, remove the "scene." part
if "." in light_setting:
light_setting = (light_setting.split("."))[1]
else:
is_scene = False
self.lg(
f"{stack()[0][3]}: {self.transition_on_daytime_switch = }",
level=logging.DEBUG,
)
action_done = "set"
if self.transition_on_daytime_switch and any(
[await self.get_state(light) == "on" for light in self.lights]
):
await self.lights_on(force=True)
action_done = "activated"
self.lg(
f"{action_done} daytime {hl(daytime['daytime'])} → "
f"{'scene' if is_scene else 'brightness'}: {hl(light_setting)}"
f"{'' if is_scene else '%'}, delay: {hl(natural_time(delay))}",
icon=DAYTIME_SWITCH_ICON,
)
async def motion_cleared(
self, entity: str, attribute: str, old: str, new: str, _: dict[str, Any]
) -> None:
"""wrapper for motion sensors that do not push a certain event but.
instead the default HA `state_changed` event is used for presence detection
schedules the callback to switch the lights off after a `state_changed` callback
of a motion sensors changing to "cleared" is received
"""
# starte the timer if motion is cleared
self.lg(
f"{stack()[0][3]}: {entity} changed {attribute} from {old} to {new}",
level=logging.DEBUG,
)
if all(
[
await self.get_state(sensor) == self.states["motion_off"]
for sensor in self.sensors[EntityType.MOTION.idx]
]
):
# all motion sensors off, starting timer
await self.refresh_timer()
else:
# cancel scheduled callbacks
await self.clear_handles()
async def motion_detected(
self, entity: str, attribute: str, old: str, new: str, kwargs: dict[str, Any]
) -> None:
"""wrapper for motion sensors that do not push a certain event but.
instead the default HA `state_changed` event is used for presence detection
maps the `state_changed` callback of a motion sensors changing to "detected"
to the `event` callback`
"""
self.lg(
f"{stack()[0][3]}: {entity} changed {attribute} from {old} to {new}",
level=logging.DEBUG,
)
# cancel scheduled callbacks
await self.clear_handles()
self.lg(
f"{stack()[0][3]}: handles cleared and cancelled all scheduled timers"
f" | {self.dimming = }",
level=logging.DEBUG,
)
# calling motion event handler
data: dict[str, Any] = {"entity_id": entity, "new": new, "old": old}
await self.motion_event("state_changed_detection", data, kwargs)
async def motion_event(
self, event: str, data: dict[str, str], _: dict[str, Any]
) -> None:
"""Main handler for motion events."""
self.lg(
f"{stack()[0][3]}: received '{hl(event)}' event from "
f"'{data['entity_id'].replace(EntityType.MOTION.prefix, '')}' | {self.dimming = }",
level=logging.DEBUG,
)
# check if automoli is disabled via home assistant entity
self.lg(
f"{stack()[0][3]}: {await self.is_disabled() = } | {self.dimming = }",
level=logging.DEBUG,
)
if await self.is_disabled():
return
# turn on the lights if not already
if self.dimming or not any(
[await self.get_state(light) == "on" for light in self.lights]
):
self.lg(
f"{stack()[0][3]}: switching on | {self.dimming = }",
level=logging.DEBUG,
)
await self.lights_on()
else:
self.lg(
f"{stack()[0][3]}: light in {self.room.name.capitalize()} already on → refreshing "
f"timer | {self.dimming = }",
level=logging.DEBUG,
)
if event != "state_changed_detection":
await self.refresh_timer()
def has_min_ad_version(self, required_version: str) -> bool:
required_version = required_version if required_version else "4.0.7"
return bool(
Version(self.get_ad_version()) >= Version(required_version)
)
async def clear_handles(self, handles: set[str] = None) -> None:
"""clear scheduled timers/callbacks."""
if not handles:
handles = deepcopy(self.room.handles_automoli)
self.room.handles_automoli.clear()
if self.has_min_ad_version("4.0.7"):
await asyncio.gather(
*[
self.cancel_timer(handle)
for handle in handles
if await self.timer_running(handle)
]
)
else:
await asyncio.gather(*[self.cancel_timer(handle) for handle in handles])
self.lg(f"{stack()[0][3]}: cancelled scheduled callbacks", level=logging.DEBUG)
async def refresh_timer(self) -> None:
"""refresh delay timer."""
fnn = f"{stack()[0][3]}:"
# leave dimming state
self.dimming = False
dim_in_sec = 0
# cancel scheduled callbacks
await self.clear_handles()
# if no delay is set or delay = 0, lights will not switched off by AutoMoLi
if delay := self.active.get("delay"):
self.lg(
f"{fnn} {self.active = } | {delay = } | {self.dim = }",
level=logging.DEBUG,
)
if self.dim:
dim_in_sec = int(delay) - self.dim["seconds_before"]
self.lg(f"{fnn} {dim_in_sec = }", level=logging.DEBUG)
handle = await self.run_in(self.dim_lights, (dim_in_sec))
else:
handle = await self.run_in(self.lights_off, delay)
self.room.handles_automoli.add(handle)
if timer_info := await self.info_timer(handle):
self.lg(
f"{fnn} scheduled callback to switch off the lights in {dim_in_sec}s "
f"({timer_info[0].isoformat()}) | "
f"handles: {self.room.handles_automoli = }",
level=logging.DEBUG,
)
async def night_mode_active(self) -> bool:
return bool(
self.night_mode and await self.get_state(self.night_mode["entity"]) == "on"
)
async def is_disabled(self) -> bool:
"""check if automoli is disabled via home assistant entity"""
for entity in self.disable_switch_entities:
if (
state := await self.get_state(entity, copy=False)
) and state in self.disable_switch_states:
self.lg(f"{APP_NAME} is disabled by {entity} with {state = }")
return True
return False
async def is_blocked(self) -> bool:
# the "shower case"
if humidity_threshold := self.thresholds.get("humidity"):
for sensor in self.sensors[EntityType.HUMIDITY.idx]:
try:
current_humidity = float(
await self.get_state(sensor) # type:ignore
)
except ValueError as error:
self.lg(
f"self.get_state(sensor) raised a ValueError for {sensor}: {error}",
level=logging.ERROR,
)
continue
self.lg(
f"{stack()[0][3]}: {current_humidity = } >= {humidity_threshold = } "
f"= {current_humidity >= humidity_threshold}",
level=logging.DEBUG,
)
if current_humidity >= humidity_threshold:
await self.refresh_timer()
self.lg(
f"🛁 no motion in {hl(self.room.name.capitalize())} since "
f"{hl(natural_time(int(self.active['delay'])))} → "
f"but {hl(current_humidity)}%RH > "
f"{hl(humidity_threshold)}%RH"
)
return True
return False
async def dim_lights(self, _: Any) -> None:
message: str = ""
self.lg(
f"{stack()[0][3]}: {await self.is_disabled() = } | {await self.is_blocked() = }",
level=logging.DEBUG,
)
# check if automoli is disabled via home assistant entity or blockers like the "shower case"
if (await self.is_disabled()) or (await self.is_blocked()):
return
if not any([await self.get_state(light) == "on" for light in self.lights]):
return
dim_method: DimMethod
seconds_before: int = 10
if (
self.dim
and (dim_method := DimMethod(self.dim["method"]))
and dim_method != DimMethod.NONE
):
seconds_before = int(self.dim["seconds_before"])
dim_attributes: dict[str, int] = {}
self.lg(
f"{stack()[0][3]}: {dim_method = } | {seconds_before = }",
level=logging.DEBUG,
)
if dim_method == DimMethod.STEP:
dim_attributes = {
"brightness_step_pct": int(self.dim["brightness_step_pct"])
}
message = (
f"{hl(self.room.name.capitalize())} → "
f"dim to {hl(self.dim['brightness_step_pct'])} | "
f"{hl('off')} in {natural_time(seconds_before)}"
)
elif dim_method == DimMethod.TRANSITION:
dim_attributes = {"transition": int(seconds_before)}
message = (
f"{hl(self.room.name.capitalize())} → transition to "
f"{hl('off')} ({natural_time(seconds_before)})"
)
self.dimming = True
self.lg(
f"{stack()[0][3]}: {dim_attributes = } | {self.dimming = }",
level=logging.DEBUG,
)
self.lg(f"{stack()[0][3]}: {self.room.room_lights = }", level=logging.DEBUG)
self.lg(
f"{stack()[0][3]}: {self.room.lights_dimmable = }", level=logging.DEBUG
)
self.lg(
f"{stack()[0][3]}: {self.room.lights_undimmable = }",
level=logging.DEBUG,
)
if self.room.lights_undimmable:
for light in self.room.lights_dimmable:
await self.call_service(
"light/turn_off",
entity_id=light, # type:ignore
**dim_attributes, # type:ignore
)
await self.set_state(entity_id=light, state="off")
# workaround to switch off lights that do not support dimming
if self.room.room_lights:
self.room.handles_automoli.add(
await self.run_in(
self.turn_off_lights,
seconds_before,
lights=self.room.room_lights,
)
)
self.lg(message, icon=OFF_ICON, level=logging.DEBUG)
async def turn_off_lights(self, kwargs: dict[str, Any]) -> None:
if lights := kwargs.get("lights"):
self.lg(f"{stack()[0][3]}: {lights = }", level=logging.DEBUG)
for light in lights:
await self.call_service("homeassistant/turn_off", entity_id=light)
self.run_in_thread(self.turned_off, thread=self.notify_thread)
async def lights_on(self, force: bool = False) -> None:
"""Turn on the lights."""
self.lg(
f"{stack()[0][3]}: {self.thresholds.get(EntityType.ILLUMINANCE.idx) = }"
f" | {self.dimming = } | {force = } | {bool(force or self.dimming) = }",
level=logging.DEBUG,
)
force = bool(force or self.dimming)
if illuminance_threshold := self.thresholds.get(EntityType.ILLUMINANCE.idx):
# the "eco mode" check
for sensor in self.sensors[EntityType.ILLUMINANCE.idx]:
self.lg(
f"{stack()[0][3]}: {self.thresholds.get(EntityType.ILLUMINANCE.idx) = } | "
f"{float(await self.get_state(sensor)) = }", # type:ignore
level=logging.DEBUG,
)
try:
if (
illuminance := float(
await self.get_state(sensor) # type:ignore
) # type:ignore
) >= illuminance_threshold:
self.lg(
f"According to {hl(sensor)} its already bright enough ¯\\_(ツ)_/¯"
f" | {illuminance} >= {illuminance_threshold}"
)
return
except ValueError as error:
self.lg(
f"could not parse illuminance '{await self.get_state(sensor)}' "
f"from '{sensor}': {error}"
)
return
light_setting = (
self.active.get("light_setting")
if not await self.night_mode_active()
else self.night_mode.get("light")
)
if isinstance(light_setting, str):
# last check until we switch the lights on... really!
if not force and any(
[await self.get_state(light) == "on" for light in self.lights]
):
self.lg("¯\\_(ツ)_/¯")
return
for entity in self.lights:
if self.active["is_hue_group"] and await self.get_state(
entity_id=entity, attribute="is_hue_group"
):
await self.call_service(
"hue/hue_activate_scene",
group_name=await self.friendly_name(entity), # type:ignore
scene_name=light_setting, # type:ignore
)
if self.only_own_events:
self._switched_on_by_automoli.add(entity)
continue
item = light_setting if light_setting.startswith("scene.") else entity
await self.call_service(
"homeassistant/turn_on", entity_id=item # type:ignore
) # type:ignore
if self.only_own_events:
self._switched_on_by_automoli.add(item)
self.lg(
f"{hl(self.room.name.capitalize())} turned {hl('on')} → "
f"{'hue' if self.active['is_hue_group'] else 'ha'} scene: "
f"{hl(light_setting.replace('scene.', ''))}"
f" | delay: {hl(natural_time(int(self.active['delay'])))}",
icon=ON_ICON,
)
elif isinstance(light_setting, int):
if light_setting == 0:
await self.lights_off({})
else:
# last check until we switch the lights on... really!
if not force and any(
[await self.get_state(light) == "on" for light in self.lights]
):
self.lg("¯\\_(ツ)_/¯")
return
for entity in self.lights:
if entity.startswith("switch."):
await self.call_service(
"homeassistant/turn_on", entity_id=entity # type:ignore
)
else:
await self.call_service(
"homeassistant/turn_on",
entity_id=entity, # type:ignore
brightness_pct=light_setting, # type:ignore
)
self.lg(
f"{hl(self.room.name.capitalize())} turned {hl('on')} → "
f"brightness: {hl(light_setting)}%"
f" | delay: {hl(natural_time(int(self.active['delay'])))}",
icon=ON_ICON,
)
if self.only_own_events:
self._switched_on_by_automoli.add(entity)
else:
raise ValueError(
f"invalid brightness/scene: {light_setting!s} " f"in {self.room}"
)
async def lights_off(self, _: dict[str, Any]) -> None:
"""Turn off the lights."""
self.lg(
f"{stack()[0][3]} {await self.is_disabled()} | {await self.is_blocked() = }",
level=logging.DEBUG,
)
# check if automoli is disabled via home assistant entity or blockers like the "shower case"
if (await self.is_disabled()) or (await self.is_blocked()):
return
# cancel scheduled callbacks
await self.clear_handles()
self.lg(
f"{stack()[0][3]}: "
f"{any([await self.get_state(entity) == 'on' for entity in self.lights]) = }"
f" | {self.lights = }",
level=logging.DEBUG,
)
# if any([await self.get_state(entity) == "on" for entity in self.lights]):
if all([await self.get_state(entity) == "off" for entity in self.lights]):
return
at_least_one_turned_off = False
for entity in self.lights:
if self.only_own_events:
if entity in self._switched_on_by_automoli:
await self.call_service(
"homeassistant/turn_off", entity_id=entity # type:ignore
) # type:ignore
self._switched_on_by_automoli.remove(entity)
at_least_one_turned_off = True
else:
await self.call_service(
"homeassistant/turn_off", entity_id=entity # type:ignore
) # type:ignore
at_least_one_turned_off = True
if at_least_one_turned_off:
self.run_in_thread(self.turned_off, thread=self.notify_thread)
# experimental | reset for xiaomi "super motion" sensors | idea from @wernerhp
# app: https://github.com/wernerhp/appdaemon_aqara_motion_sensors
# mod:
# https://community.smartthings.com/t/making-xiaomi-motion-sensor-a-super-motion-sensor/139806
for sensor in self.sensors[EntityType.MOTION.idx]:
await self.set_state(
sensor,
state="off",
attributes=(await self.get_state(sensor, attribute="all")).get(
"attributes", {}
),
)
async def turned_off(self, _: dict[str, Any] | None = None) -> None:
# cancel scheduled callbacks