-
Notifications
You must be signed in to change notification settings - Fork 139
/
test_switch.py
2132 lines (1834 loc) · 77.5 KB
/
test_switch.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
"""Tests for Adaptive Lighting switches."""
# pylint: disable=protected-access
import asyncio
import itertools
from copy import deepcopy
import datetime
import logging
from random import randint
from typing import Any
from unittest.mock import Mock, patch
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_BRIGHTNESS_PCT,
ATTR_COLOR_TEMP_KELVIN,
ATTR_RGB_COLOR,
ATTR_TRANSITION,
ATTR_XY_COLOR,
)
from homeassistant.components.light import DOMAIN as LIGHT_DOMAIN
from homeassistant.components.light import SERVICE_TURN_OFF
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
import homeassistant.config as config_util
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import (
ATTR_AREA_ID,
ATTR_ENTITY_ID,
ATTR_SUPPORTED_FEATURES,
CONF_LIGHTS,
CONF_NAME,
EVENT_CALL_SERVICE,
EVENT_STATE_CHANGED,
SERVICE_TOGGLE,
SERVICE_TURN_ON,
STATE_OFF,
STATE_ON,
)
from homeassistant.core import Context, Event, HomeAssistant, State
from homeassistant.helpers import entity_registry
from homeassistant.helpers.entity_platform import async_get_platforms
from homeassistant.setup import async_setup_component
from homeassistant.util.color import color_temperature_mired_to_kelvin
import homeassistant.util.dt as dt_util
import pytest
from pytest_homeassistant_custom_component.common import (
MockConfigEntry,
mock_area_registry,
)
import ulid_transform
import voluptuous.error
from custom_components.adaptive_lighting.adaptation_utils import (
AdaptationData,
_create_service_call_data_iterator,
)
from custom_components.adaptive_lighting.const import (
ADAPT_BRIGHTNESS_SWITCH,
ADAPT_COLOR_SWITCH,
CONF_TAKE_OVER_CONTROL,
ATTR_ADAPTIVE_LIGHTING_MANAGER,
CONF_ADAPT_UNTIL_SLEEP,
CONF_AUTORESET_CONTROL,
CONF_BRIGHTNESS_MODE,
CONF_BRIGHTNESS_MODE_TIME_DARK,
CONF_BRIGHTNESS_MODE_TIME_LIGHT,
CONF_DETECT_NON_HA_CHANGES,
CONF_INITIAL_TRANSITION,
CONF_MANUAL_CONTROL,
CONF_MAX_BRIGHTNESS,
CONF_MIN_COLOR_TEMP,
CONF_PREFER_RGB_COLOR,
CONF_MULTI_LIGHT_INTERCEPT,
CONF_SEPARATE_TURN_ON_COMMANDS,
CONF_SLEEP_RGB_OR_COLOR_TEMP,
CONF_SUNRISE_OFFSET,
CONF_SUNRISE_TIME,
CONF_SUNSET_TIME,
CONF_TRANSITION,
CONF_TURN_ON_LIGHTS,
CONF_USE_DEFAULTS,
DEFAULT_MAX_BRIGHTNESS,
DEFAULT_NAME,
DEFAULT_SLEEP_BRIGHTNESS,
DEFAULT_SLEEP_COLOR_TEMP,
DEFAULT_SLEEP_RGB_COLOR,
DOMAIN,
SERVICE_APPLY,
SERVICE_CHANGE_SWITCH_SETTINGS,
SERVICE_SET_MANUAL_CONTROL,
SLEEP_MODE_SWITCH,
CONF_ADAPT_ONLY_ON_BARE_TURN_ON,
UNDO_UPDATE_LISTENER,
)
from custom_components.adaptive_lighting.switch import (
INTERNAL_CONF_PROACTIVE_SERVICE_CALL_ADAPTATION,
AdaptiveSwitch,
_attributes_have_changed,
color_difference_redmean,
create_context,
AdaptiveLightingManager,
is_our_context,
is_our_context_id,
)
from custom_components.adaptive_lighting.color_and_brightness import lerp_color_hsv
_LOGGER = logging.getLogger(__name__)
SUNRISE = datetime.datetime(
year=2020,
month=10,
day=17,
hour=6,
)
SUNSET = datetime.datetime(
year=2020,
month=10,
day=17,
hour=22,
)
LAT_LONG_TZS = [
(39, -1, "Europe/Madrid"),
(60, 50, "GMT"),
(55, 13, "Europe/Copenhagen"),
(52.379189, 4.899431, "Europe/Amsterdam"),
(32.87336, -117.22743, "US/Pacific"),
]
ENTITY_LIGHT_1 = "light.light_1"
ENTITY_LIGHT_2 = "light.light_2"
ENTITY_LIGHT_3 = "light.light_3"
_SWITCH_FMT = f"{SWITCH_DOMAIN}.{DOMAIN}"
ENTITY_SWITCH = f"{_SWITCH_FMT}_{DEFAULT_NAME}"
ENTITY_SLEEP_MODE_SWITCH = f"{_SWITCH_FMT}_sleep_mode_{DEFAULT_NAME}"
ENTITY_ADAPT_BRIGHTNESS_SWITCH = f"{_SWITCH_FMT}_adapt_brightness_{DEFAULT_NAME}"
ENTITY_ADAPT_COLOR_SWITCH = f"{_SWITCH_FMT}_adapt_color_{DEFAULT_NAME}"
ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE
def create_random_context() -> str:
return Context(id=ulid_transform.ulid_now(), parent_id=None)
@pytest.fixture
def reset_time_zone():
"""Reset time zone."""
yield
dt_util.DEFAULT_TIME_ZONE = ORIG_TIMEZONE
@pytest.fixture
async def cleanup(hass):
yield
manager: AdaptiveLightingManager = hass.data[DOMAIN][ATTR_ADAPTIVE_LIGHTING_MANAGER]
for timer in manager.auto_reset_manual_control_timers.values():
timer.cancel()
for timer in manager.transition_timers.values():
timer.cancel()
for task in manager.adaptation_tasks:
task.cancel()
async def setup_switch(hass, extra_data) -> tuple[MockConfigEntry, AdaptiveSwitch]:
"""Create the switch entry."""
entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_NAME: DEFAULT_NAME,
INTERNAL_CONF_PROACTIVE_SERVICE_CALL_ADAPTATION: False,
**extra_data,
},
)
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert entry.state is ConfigEntryState.LOADED
switch = hass.data[DOMAIN][entry.entry_id][SWITCH_DOMAIN]
return entry, switch
async def setup_lights(hass: HomeAssistant, with_group: bool = False):
"""Set up 3 light entities using the 'template' platform."""
n = 3 if not with_group else 5 # last 2 will be put in a group
template_lights = {
f"light_{i}": {
"unique_id": f"light_{i}",
"friendly_name": f"light_{i}",
"turn_on": None,
"turn_off": None,
"set_level": None,
"set_temperature": None,
"set_color": None,
}
for i in range(1, n + 1)
}
template_lights["light_3"]["supports_transition_template"] = True
platforms = [{"platform": "template", "lights": template_lights}]
if with_group:
platforms.append(
{
"platform": "group",
"entities": ["light.light_4", "light.light_5"],
"name": "Light Group",
"unique_id": "light_group",
"all": "false",
}
)
await async_setup_component(
hass,
LIGHT_DOMAIN,
{LIGHT_DOMAIN: platforms},
)
await hass.async_block_till_done()
if with_group:
state = hass.states.get("light.light_group")
assert state.attributes["entity_id"] == ["light.light_4", "light.light_5"]
platform = async_get_platforms(hass, "template")
lights = list(platform[0].entities.values())
await lights[0].async_turn_on()
await lights[1].async_turn_on()
for light in lights:
light._attr_brightness = 255
light._attr_color_temp = 250
assert all(hass.states.get(light.entity_id) is not None for light in lights)
return lights
async def setup_lights_and_switch(hass, extra_conf=None, all_lights: bool = False):
"""Create switch and demo lights."""
# Setup demo lights and turn on
lights_instances = await setup_lights(hass)
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: ENTITY_LIGHT_1},
blocking=True,
)
# Setup switch
lights = [
ENTITY_LIGHT_1,
ENTITY_LIGHT_2,
]
if all_lights:
lights.append(ENTITY_LIGHT_3)
assert all(hass.states.get(light) is not None for light in lights)
_, switch = await setup_switch(
hass,
{
CONF_LIGHTS: lights,
CONF_SUNRISE_TIME: datetime.time(SUNRISE.hour),
CONF_SUNSET_TIME: datetime.time(SUNSET.hour),
CONF_INITIAL_TRANSITION: 0,
CONF_TRANSITION: 0,
CONF_DETECT_NON_HA_CHANGES: True,
CONF_PREFER_RGB_COLOR: False,
CONF_MIN_COLOR_TEMP: 2500, # to not coincide with sleep_color_temp
**(extra_conf or {}),
},
)
await hass.async_block_till_done()
return switch, lights_instances
# see https://github.com/home-assistant/core/blob/dev/homeassistant/scripts/benchmark/__init__.py
# basically just search the repo for EVENT_STATE_CHANGED look for how it's fired.
def create_transition_events(
light: str,
state: State,
last: dict | None = None,
current: dict | None = None,
total_events: int = 4,
) -> list[dict]:
assert light is not None
all_events = []
for i in range(1, total_events):
# Build basic event data.
attributes = {}
# The first state change always has the context from our integration.
# That one will not be in all_events.
# It's very possible it stores the parent_id though.
# If it stores the parent_id in all situations, there's a great improvement
# that could added in future updates.
# Simulate the events the bulb would send to HASS.
last_brightness = last.get(ATTR_BRIGHTNESS) or state[ATTR_BRIGHTNESS]
current_brightness = current.get(ATTR_BRIGHTNESS)
if (
last_brightness
and current_brightness
and last_brightness != current_brightness
):
diff = (current_brightness - last_brightness) * (i / total_events)
attributes[ATTR_BRIGHTNESS] = last_brightness + diff
elif current_brightness:
attributes[ATTR_BRIGHTNESS] = current_brightness
current_kelvin = current.get(ATTR_COLOR_TEMP_KELVIN)
last_kelvin = last.get(ATTR_COLOR_TEMP_KELVIN) or state[ATTR_COLOR_TEMP_KELVIN]
if last_kelvin and current_kelvin and last_kelvin != current_kelvin:
diff = (current_kelvin - last_kelvin) * (i / total_events)
attributes[ATTR_COLOR_TEMP_KELVIN] = last_kelvin + diff
elif current_kelvin:
attributes[ATTR_COLOR_TEMP_KELVIN] = current_kelvin
# Pack event
event_data = {
ATTR_ENTITY_ID: light,
"old_state": State(light, "on", attributes=last),
"new_state": State(
light, "on", attributes=attributes, context=create_random_context()
),
}
all_events.append(event_data)
return all_events
async def test_adaptive_lighting_switches(hass):
"""Test switches created for adaptive_lighting integration."""
entry, _ = await setup_switch(hass, {})
assert len(hass.states.async_entity_ids(SWITCH_DOMAIN)) == 4
assert set(hass.states.async_entity_ids(SWITCH_DOMAIN)) == {
ENTITY_SWITCH,
ENTITY_SLEEP_MODE_SWITCH,
ENTITY_ADAPT_COLOR_SWITCH,
ENTITY_ADAPT_BRIGHTNESS_SWITCH,
}
assert ATTR_ADAPTIVE_LIGHTING_MANAGER in hass.data[DOMAIN]
assert entry.entry_id in hass.data[DOMAIN]
assert len(hass.data[DOMAIN].keys()) == 2
data = hass.data[DOMAIN][entry.entry_id]
assert SLEEP_MODE_SWITCH in data
assert SWITCH_DOMAIN in data
assert ADAPT_COLOR_SWITCH in data
assert ADAPT_BRIGHTNESS_SWITCH in data
assert UNDO_UPDATE_LISTENER in data
assert len(data.keys()) == 5
@pytest.mark.parametrize("lat,long,timezone", LAT_LONG_TZS)
async def test_adaptive_lighting_time_zones_with_default_settings(
hass, lat, long, timezone, reset_time_zone # pylint: disable=redefined-outer-name
):
"""Test setting up the Adaptive Lighting switches with different timezones."""
await config_util.async_process_ha_core_config(
hass,
{"latitude": lat, "longitude": long, "time_zone": timezone},
)
_, switch = await setup_switch(hass, {})
# Shouldn't raise an exception ever
await switch._update_attrs_and_maybe_adapt_lights(
context=switch.create_context("test")
)
@pytest.mark.parametrize("lat,long,timezone", LAT_LONG_TZS)
async def test_adaptive_lighting_time_zones_and_sun_settings(
hass,
lat,
long,
timezone,
reset_time_zone, # pylint: disable=redefined-outer-name
):
"""Test setting up the Adaptive Lighting switches with different timezones.
Also test the (sleep) brightness and color temperature settings.
"""
await config_util.async_process_ha_core_config(
hass,
{"latitude": lat, "longitude": long, "time_zone": timezone},
)
_, switch = await setup_switch(
hass,
{
CONF_SUNRISE_TIME: datetime.time(SUNRISE.hour),
CONF_SUNSET_TIME: datetime.time(SUNSET.hour),
},
)
context = switch.create_context("test") # needs to be passed to update method
min_color_temp = switch._sun_light_settings.min_color_temp
sunset = SUNSET.replace(tzinfo=dt_util.DEFAULT_TIME_ZONE).astimezone(dt_util.UTC)
before_sunset = sunset - datetime.timedelta(hours=1)
after_sunset = sunset + datetime.timedelta(hours=1)
sunrise = SUNRISE.replace(tzinfo=dt_util.DEFAULT_TIME_ZONE).astimezone(dt_util.UTC)
before_sunrise = sunrise - datetime.timedelta(hours=1)
after_sunrise = sunrise + datetime.timedelta(hours=1)
async def patch_time_and_update(time):
with patch(
"custom_components.adaptive_lighting.color_and_brightness.utcnow",
return_value=time,
):
await switch._update_attrs_and_maybe_adapt_lights(context=context)
await hass.async_block_till_done()
# At sunset the brightness should be max and color_temp at the smallest value
await patch_time_and_update(sunset)
assert switch._settings[ATTR_BRIGHTNESS_PCT] == DEFAULT_MAX_BRIGHTNESS
assert switch._settings["color_temp_kelvin"] == min_color_temp
# One hour before sunset the brightness should be max and color_temp
# not at the smallest value yet.
await patch_time_and_update(before_sunset)
assert switch._settings[ATTR_BRIGHTNESS_PCT] == DEFAULT_MAX_BRIGHTNESS
assert switch._settings["color_temp_kelvin"] > min_color_temp
# One hour after sunset the brightness should be down
await patch_time_and_update(after_sunset)
assert switch._settings[ATTR_BRIGHTNESS_PCT] < DEFAULT_MAX_BRIGHTNESS
assert switch._settings["color_temp_kelvin"] == min_color_temp
# At sunrise the brightness should be max and color_temp at the smallest value
await patch_time_and_update(sunrise)
assert switch._settings[ATTR_BRIGHTNESS_PCT] == DEFAULT_MAX_BRIGHTNESS
assert switch._settings["color_temp_kelvin"] == min_color_temp
# One hour before sunrise the brightness should smaller than max
# and color_temp at the min value.
await patch_time_and_update(before_sunrise)
assert switch._settings[ATTR_BRIGHTNESS_PCT] < DEFAULT_MAX_BRIGHTNESS
assert switch._settings["color_temp_kelvin"] == min_color_temp
# One hour after sunrise the brightness should be up
await patch_time_and_update(after_sunrise)
assert switch._settings[ATTR_BRIGHTNESS_PCT] == DEFAULT_MAX_BRIGHTNESS
assert switch._settings["color_temp_kelvin"] > min_color_temp
# Turn on sleep mode which make the brightness and color_temp
# deterministic regardless of the time
await switch.sleep_mode_switch.async_turn_on()
await switch._update_attrs_and_maybe_adapt_lights(context=context)
assert switch._settings[ATTR_BRIGHTNESS_PCT] == DEFAULT_SLEEP_BRIGHTNESS
assert switch._settings["color_temp_kelvin"] == DEFAULT_SLEEP_COLOR_TEMP
async def test_light_settings(hass):
"""Test that light settings are correctly applied."""
switch, _ = await setup_lights_and_switch(hass)
lights = switch.lights
# Turn on "sleep mode"
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: ENTITY_SLEEP_MODE_SWITCH},
blocking=True,
)
await hass.async_block_till_done()
light_states = [hass.states.get(light) for light in lights]
for state in light_states:
assert state.attributes[ATTR_BRIGHTNESS] == round(
255 * switch._settings[ATTR_BRIGHTNESS_PCT] / 100
)
last_service_data = switch.manager.last_service_data[state.entity_id]
assert state.attributes[ATTR_BRIGHTNESS] == last_service_data[ATTR_BRIGHTNESS]
assert (
state.attributes[ATTR_COLOR_TEMP_KELVIN]
== last_service_data[ATTR_COLOR_TEMP_KELVIN]
)
# Turn off "sleep mode"
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: ENTITY_SLEEP_MODE_SWITCH},
blocking=True,
)
await hass.async_block_till_done()
# Test with different times
sunset = SUNSET.replace(tzinfo=dt_util.DEFAULT_TIME_ZONE).astimezone(dt_util.UTC)
before_sunset = sunset - datetime.timedelta(hours=1)
after_sunset = sunset + datetime.timedelta(hours=1)
sunrise = SUNRISE.replace(tzinfo=dt_util.DEFAULT_TIME_ZONE).astimezone(dt_util.UTC)
before_sunrise = sunrise - datetime.timedelta(hours=1)
after_sunrise = sunrise + datetime.timedelta(hours=1)
context = switch.create_context("test") # needs to be passed to update method
async def patch_time_and_get_updated_states(time):
with patch(
"custom_components.adaptive_lighting.color_and_brightness.utcnow",
return_value=time,
):
await switch._update_attrs_and_maybe_adapt_lights(
context=context, transition=0, force=True
)
await hass.async_block_till_done()
return [hass.states.get(light) for light in lights]
def assert_expected_color_temp(state):
last_service_data = switch.manager.last_service_data[state.entity_id]
assert (
state.attributes[ATTR_COLOR_TEMP_KELVIN]
== last_service_data[ATTR_COLOR_TEMP_KELVIN]
)
# At sunset the brightness should be max and color_temp at the smallest value
light_states = await patch_time_and_get_updated_states(sunset)
for state in light_states:
assert state.attributes[ATTR_BRIGHTNESS] == 255
assert_expected_color_temp(state)
# One hour before sunset the brightness should be max and color_temp
# not at the smallest value yet.
light_states = await patch_time_and_get_updated_states(before_sunset)
for state in light_states:
assert state.attributes[ATTR_BRIGHTNESS] == 255
assert_expected_color_temp(state)
# One hour after sunset the brightness should be down
light_states = await patch_time_and_get_updated_states(after_sunset)
for state in light_states:
assert state.attributes[ATTR_BRIGHTNESS] < 255
assert_expected_color_temp(state)
# At sunrise the brightness should be max and color_temp at the smallest value
light_states = await patch_time_and_get_updated_states(sunrise)
for state in light_states:
assert state.attributes[ATTR_BRIGHTNESS] == 255
assert_expected_color_temp(state)
# One hour before sunrise the brightness should smaller than max
# and color_temp at the min value.
light_states = await patch_time_and_get_updated_states(before_sunrise)
for state in light_states:
assert state.attributes[ATTR_BRIGHTNESS] < 255
assert_expected_color_temp(state)
# One hour after sunrise the brightness should be up
light_states = await patch_time_and_get_updated_states(after_sunrise)
for state in light_states:
assert state.attributes[ATTR_BRIGHTNESS] == 255
assert_expected_color_temp(state)
async def test_manager_not_tracking_untracked_lights(hass):
"""Test that lights that are not in a Adaptive Lighting switch aren't tracked."""
switch, _ = await setup_lights_and_switch(hass)
light = ENTITY_LIGHT_3
assert light not in switch.lights
for state in [True, False]:
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON if state else SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: light},
blocking=True,
)
await switch._update_attrs_and_maybe_adapt_lights(
context=switch.create_context("test")
)
await hass.async_block_till_done()
assert light not in switch.manager.lights
@pytest.mark.parametrize("adapt_only_on_bare_turn_on", [True, False])
@pytest.mark.parametrize("proactive_service_call_adaptation", [True, False])
async def test_manual_control(
hass, adapt_only_on_bare_turn_on, proactive_service_call_adaptation
):
"""Test the 'manual control' tracking."""
switch, (light, *_) = await setup_lights_and_switch(
hass,
{
CONF_ADAPT_ONLY_ON_BARE_TURN_ON: adapt_only_on_bare_turn_on,
INTERNAL_CONF_PROACTIVE_SERVICE_CALL_ADAPTATION: proactive_service_call_adaptation,
},
)
assert switch._take_over_control
assert hass.states.get(ENTITY_LIGHT_1).state == STATE_ON
context = switch.create_context("test") # needs to be passed to update method
manual_control = switch.manager.manual_control
async def update():
await switch._update_attrs_and_maybe_adapt_lights(context=context, transition=0)
await hass.async_block_till_done()
async def turn_light(state, **kwargs):
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON if state else SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: ENTITY_LIGHT_1, **kwargs},
blocking=True,
)
_LOGGER.debug("Turn light %s, to %s", "on" if state else "off", kwargs)
await hass.async_block_till_done()
await update()
async def turn_switch(state, entity_id):
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON if state else SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
await hass.async_block_till_done()
async def change_manual_control(set_to, extra_service_data=None):
if extra_service_data is None:
extra_service_data = {CONF_LIGHTS: [ENTITY_LIGHT_1]}
_LOGGER.debug(f"{switch.manager.manual_control=}")
await hass.services.async_call(
DOMAIN,
SERVICE_SET_MANUAL_CONTROL,
{
ATTR_ENTITY_ID: switch.entity_id,
CONF_MANUAL_CONTROL: set_to,
**extra_service_data,
},
blocking=True,
)
_LOGGER.debug(f"{switch.manager.manual_control=}")
_LOGGER.debug("Called set_manual_control with %s", set_to)
await hass.async_block_till_done()
await update()
_LOGGER.debug("End of change_manual_control")
def increased_brightness():
return (light._attr_brightness + 100) % 255
def increased_color_temp():
return max(
(light._attr_color_temp + 100) % light.max_color_temp_kelvin,
light.min_color_temp_kelvin,
)
# Nothing is manually controlled
await update()
assert not manual_control[ENTITY_LIGHT_1]
# Call light.turn_on for ENTITY_LIGHT_1
await turn_light(True, brightness=increased_brightness())
# Check that ENTITY_LIGHT_1 is manually controlled
assert manual_control[ENTITY_LIGHT_1]
# Test adaptive_lighting.set_manual_control
await change_manual_control(False)
# Check that ENTITY_LIGHT_1 is not manually controlled
assert not manual_control[ENTITY_LIGHT_1]
# Check that toggling light off to on resets manual control
await change_manual_control(True)
assert manual_control[ENTITY_LIGHT_1]
await turn_light(False)
assert not manual_control[ENTITY_LIGHT_1], manual_control
await turn_light(True, brightness=increased_brightness())
assert hass.states.get(ENTITY_LIGHT_1).state == STATE_ON
if adapt_only_on_bare_turn_on:
# Marks as manually controlled beacuse we turned it on with brightness
assert manual_control[ENTITY_LIGHT_1], manual_control
else:
assert not manual_control[ENTITY_LIGHT_1], manual_control
# Check that toggling (sleep mode) switch resets manual control
for entity_id in [ENTITY_SWITCH, ENTITY_SLEEP_MODE_SWITCH]:
await change_manual_control(True)
assert manual_control[ENTITY_LIGHT_1]
await turn_switch(False, entity_id)
await turn_switch(True, entity_id)
assert not manual_control[ENTITY_LIGHT_1]
# Check that manual control is still enabled if set while bulb is off.
# Test issue #37
await turn_light(False)
await change_manual_control(True)
await turn_light(True)
assert manual_control[ENTITY_LIGHT_1]
# Check that when 'adapt_brightness' is off, changing the brightness
# doesn't mark it as manually controlled but changing color_temp
# does
await turn_light(False)
await turn_light(True) # reset manually controlled status
assert not manual_control[ENTITY_LIGHT_1]
await switch.adapt_brightness_switch.async_turn_off()
await turn_light(True, brightness=increased_brightness())
assert not manual_control[ENTITY_LIGHT_1]
mired_range = (light.min_color_temp_kelvin, light.max_color_temp_kelvin)
kelvin_range = (
color_temperature_mired_to_kelvin(mired_range[1]),
color_temperature_mired_to_kelvin(mired_range[0]),
)
ptp_kelvin = kelvin_range[1] - kelvin_range[0]
await turn_light(
True, color_temp_kelvin=(light._attr_color_temp + 100) % ptp_kelvin
)
assert manual_control[ENTITY_LIGHT_1]
await switch.adapt_brightness_switch.async_turn_on() # turn on again
# Check that when 'adapt_color' is off, changing the color
# doesn't mark it as manually controlled but changing brightness
# does
await turn_light(False) # reset manually controlled status
await turn_light(True)
assert not manual_control[ENTITY_LIGHT_1]
await switch.adapt_color_switch.async_turn_off()
await turn_light(True, color_temp=increased_color_temp())
assert not manual_control[ENTITY_LIGHT_1]
await turn_light(True, brightness=increased_brightness())
assert manual_control[ENTITY_LIGHT_1]
# Check that when 'adapt_color' adapt_brightness are both off
# nothing marks it as manually controlled
await turn_light(False) # reset manually controlled status
await turn_light(True)
await switch.adapt_color_switch.async_turn_off()
await switch.adapt_brightness_switch.async_turn_off()
assert not manual_control[ENTITY_LIGHT_1]
await turn_light(True, color_temp=increased_color_temp())
await turn_light(True, brightness=increased_brightness())
await turn_light(
True,
color_temp=increased_color_temp(),
brightness=increased_brightness(),
)
assert not manual_control[ENTITY_LIGHT_1]
# Turn switches on again
await switch.adapt_color_switch.async_turn_on()
await switch.adapt_brightness_switch.async_turn_on()
# Check that when no lights are specified, all are reset
await change_manual_control(True, {CONF_LIGHTS: switch.lights})
assert all([manual_control[eid] for eid in switch.lights])
# do not pass "lights" so reset all
await change_manual_control(False, {})
assert all([not manual_control[eid] for eid in switch.lights])
# Turn off light and turn on using adaptive_lighting.apply
await turn_light(False)
await hass.services.async_call(
DOMAIN,
SERVICE_APPLY,
{
ATTR_ENTITY_ID: ENTITY_SWITCH,
CONF_LIGHTS: [ENTITY_LIGHT_1],
CONF_TURN_ON_LIGHTS: True,
},
blocking=True,
)
await hass.async_block_till_done()
assert hass.states.get(ENTITY_LIGHT_1).state == STATE_ON
assert not manual_control[ENTITY_LIGHT_1]
async def test_auto_reset_manual_control(hass):
switch, (light, *_) = await setup_lights_and_switch(
hass, {CONF_AUTORESET_CONTROL: 0.1}
)
context = switch.create_context("test") # needs to be passed to update method
manual_control = switch.manager.manual_control
async def update():
await switch._update_attrs_and_maybe_adapt_lights(context=context, transition=0)
await hass.async_block_till_done()
async def turn_light(state, **kwargs):
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON if state else SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: light.entity_id, **kwargs},
blocking=True,
)
await hass.async_block_till_done()
await update()
_LOGGER.debug(
"Turn light %s to state %s, to %s", light.entity_id, state, kwargs
)
_LOGGER.debug("Start test auto reset manual control")
await turn_light(True, brightness=1)
await turn_light(True, brightness=10)
assert manual_control[light.entity_id]
assert (
switch.extra_state_attributes["autoreset_time_remaining"][light.entity_id] > 0
)
await update()
await asyncio.sleep(0.3) # Should be enough time for auto reset
assert not manual_control[light.entity_id], (light, manual_control)
assert (
light.entity_id not in switch.extra_state_attributes["autoreset_time_remaining"]
)
# Do a couple of quick changes and check that light is not reset
for i in range(3):
_LOGGER.debug("Quick change %s", i)
await turn_light(True, brightness=(i + 1) * 20)
await asyncio.sleep(0.05) # Less than 0.1
assert manual_control[light.entity_id]
await update()
await asyncio.sleep(0.3) # Wait the auto reset time
assert not manual_control[light.entity_id]
async def test_apply_service(hass):
"""Test adaptive_lighting.apply service."""
switch, (_, _, light) = await setup_lights_and_switch(hass)
entity_id = light.entity_id
assert entity_id not in switch.lights
def increased_brightness():
return (light._attr_brightness + 100) % 255
def increased_color_temp():
return max(
(light._attr_color_temp + 100) % light.max_color_temp_kelvin,
light.min_color_temp_kelvin,
)
async def change_light():
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{
ATTR_ENTITY_ID: entity_id,
ATTR_BRIGHTNESS: increased_brightness(),
ATTR_COLOR_TEMP_KELVIN: increased_color_temp(),
},
blocking=True,
)
await hass.async_block_till_done()
async def apply(**kwargs):
await hass.services.async_call(
DOMAIN,
SERVICE_APPLY,
{
ATTR_ENTITY_ID: ENTITY_SWITCH,
CONF_LIGHTS: [entity_id],
CONF_TURN_ON_LIGHTS: True,
**kwargs,
},
blocking=True,
)
await hass.async_block_till_done()
# Test turn on with defaults
assert hass.states.get(entity_id).state == STATE_OFF
await apply()
assert hass.states.get(entity_id).state == STATE_ON
await change_light()
# Test only changing color
old_state = hass.states.get(entity_id).attributes
await apply(adapt_color=True, adapt_brightness=False)
new_state = hass.states.get(entity_id).attributes
assert old_state[ATTR_BRIGHTNESS] == new_state[ATTR_BRIGHTNESS]
assert old_state[ATTR_COLOR_TEMP_KELVIN] != new_state[ATTR_COLOR_TEMP_KELVIN]
# Test only changing brightness
await change_light()
old_state = hass.states.get(entity_id).attributes
await apply(adapt_color=False, adapt_brightness=True)
new_state = hass.states.get(entity_id).attributes
assert old_state[ATTR_BRIGHTNESS] != new_state[ATTR_BRIGHTNESS]
assert old_state[ATTR_COLOR_TEMP_KELVIN] == new_state[ATTR_COLOR_TEMP_KELVIN]
async def test_switch_off_on_off(hass):
"""Test switch rapid off_on_off."""
async def turn_light(state, **kwargs):
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON if state else SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: ENTITY_LIGHT_1, **kwargs},
blocking=True,
)
await hass.async_block_till_done()
async def update():
await switch._update_attrs_and_maybe_adapt_lights(
context=switch.create_context("test"), transition=0
)
await hass.async_block_till_done()
switch, _ = await setup_lights_and_switch(hass)
for turn_light_state_at_end in [True, False]:
# Turn light on
await turn_light(True)
# Turn light off with transition
await turn_light(False, transition=1)
assert not switch.manager.manual_control[ENTITY_LIGHT_1]
# Set state to on after a second (like happens IRL)
await asyncio.sleep(1e-3)
hass.states.async_set(ENTITY_LIGHT_1, STATE_ON)
# Set state to off after a second (like happens IRL)
await asyncio.sleep(1e-3)
hass.states.async_set(ENTITY_LIGHT_1, STATE_OFF)
# Now we test whether the sleep task is there
assert ENTITY_LIGHT_1 in switch.manager.sleep_tasks
sleep_task = switch.manager.sleep_tasks[ENTITY_LIGHT_1]
assert not sleep_task.cancelled()
# A 'light.turn_on' event should cancel that task
await turn_light(turn_light_state_at_end)
await update()
state = hass.states.get(ENTITY_LIGHT_1).state
if turn_light_state_at_end:
assert sleep_task.cancelled()
assert state == STATE_ON
else:
assert state == STATE_OFF
def test_color_difference_redmean():
"""Test color_difference_redmean function."""
for _ in range(10):
rgb_1 = (randint(0, 255), randint(0, 255), randint(0, 255))
rgb_2 = (randint(0, 255), randint(0, 255), randint(0, 255))
color_difference_redmean(rgb_1, rgb_2)
color_difference_redmean((0, 0, 0), (255, 255, 255))
def test_attributes_have_changed():
"""Test _attributes_have_changed function."""
attributes_1 = {
ATTR_BRIGHTNESS: 1,
ATTR_RGB_COLOR: (0, 0, 0),
ATTR_COLOR_TEMP_KELVIN: 100,
}
attributes_2 = {
ATTR_BRIGHTNESS: 100,
ATTR_RGB_COLOR: (255, 0, 0),
ATTR_COLOR_TEMP_KELVIN: 300,
}
kwargs = dict(
light="light.test",
adapt_brightness=True,
adapt_color=True,
context=Context(),
)
assert not _attributes_have_changed(
old_attributes=attributes_1, new_attributes=attributes_1, **kwargs
)
for key, value in attributes_2.items():
attrs = dict(attributes_1)
attrs[key] = value
assert _attributes_have_changed(
old_attributes=attributes_1, new_attributes=attrs, **kwargs
)
_LOGGER.debug("Test switch from color_temp to rgb_color")
assert not _attributes_have_changed(
old_attributes={ATTR_BRIGHTNESS: 1, ATTR_COLOR_TEMP_KELVIN: 2702},
new_attributes={ATTR_BRIGHTNESS: 1, ATTR_RGB_COLOR: (255, 166, 87)},
**kwargs,
)
_LOGGER.debug("Test switch from rgb_color to color_temp")
assert not _attributes_have_changed(
old_attributes={ATTR_BRIGHTNESS: 1, ATTR_RGB_COLOR: (255, 166, 87)},
new_attributes={ATTR_BRIGHTNESS: 1, ATTR_COLOR_TEMP_KELVIN: 2702},
**kwargs,
)
_LOGGER.debug("Test switch from color_temp to color_xy")
assert not _attributes_have_changed(
old_attributes={ATTR_BRIGHTNESS: 1, ATTR_COLOR_TEMP_KELVIN: 2702},
new_attributes={ATTR_BRIGHTNESS: 1, ATTR_XY_COLOR: (0.526, 0.387)},
**kwargs,
)
_LOGGER.debug("Test switch from color_xy to color_temp")
assert not _attributes_have_changed(
old_attributes={ATTR_BRIGHTNESS: 1, ATTR_XY_COLOR: (0.526, 0.387)},
new_attributes={ATTR_BRIGHTNESS: 1, ATTR_COLOR_TEMP_KELVIN: 2702},
**kwargs,
)
async def test_state_change_handlers(hass):
"""
Test AdaptiveLightingManager's EVENT_STATE_CHANGED listener.
======================
Sequence of events:
1. Transition from sleep mode to normal.
2. Create simulated transition events for that adapt.
3. Fire all simulated transition events.
4. Assert all possible problems that would result.
Also tests significant changes.
"""
switch, (light, *_) = await setup_lights_and_switch(hass)
context = switch.create_context("test") # needs to be passed to update method
# [Config options]: