From 0fd8c38df2ef9311055a451b83d559f1c6b196f1 Mon Sep 17 00:00:00 2001 From: "allcontributors[bot]" <46447321+allcontributors[bot]@users.noreply.github.com> Date: Sun, 6 Sep 2026 16:14:34 +0000 Subject: [PATCH 01/26] docs: update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 3afc9a0d..e4cf37b8 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ [![hacs_badge](https://img.shields.io/badge/HACS-Default-orange.svg?style=for-the-badge)](https://github.com/hacs/integration) ![Version](https://img.shields.io/github/v/release/basnijholt/adaptive-lighting?style=for-the-badge) -[![All Contributors](https://img.shields.io/badge/all_contributors-167-orange.svg?style=flat-square)](#contributors-) +[![All Contributors](https://img.shields.io/badge/all_contributors-168-orange.svg?style=flat-square)](#contributors-) # 🌞 Adaptive Lighting: Enhance Your Home's Atmosphere with Smart, Sun-Synchronized Lighting 🌙 @@ -926,6 +926,7 @@ Notice the values of `brightness_mode_time_light` and `brightness_mode_time_dark Wosten
Wosten

🐛 Zachary Priddy
Zachary Priddy

🤔 Andrew Blakeslee Moore
Andrew Blakeslee Moore

🐛 + tests
tests

⚠️ From cbee5c260a2cfd5332a83750cf9dc482bcf3a721 Mon Sep 17 00:00:00 2001 From: "allcontributors[bot]" <46447321+allcontributors[bot]@users.noreply.github.com> Date: Sun, 6 Sep 2026 16:14:34 +0000 Subject: [PATCH 02/26] docs: update .all-contributorsrc --- .all-contributorsrc | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/.all-contributorsrc b/.all-contributorsrc index 161b5633..0b7a28e2 100644 --- a/.all-contributorsrc +++ b/.all-contributorsrc @@ -1523,6 +1523,15 @@ "contributions": [ "bug" ] + }, + { + "login": "tests", + "name": "tests", + "avatar_url": "https://avatars.githubusercontent.com/u/37722?v=4", + "profile": "https://github.com/tests", + "contributions": [ + "test" + ] } ], "contributorsPerLine": 7, From cda1c2db3392f353befa219588a8eaa4c42bf748 Mon Sep 17 00:00:00 2001 From: Bas Nijholt Date: Sun, 6 Sep 2026 19:09:26 +0200 Subject: [PATCH 03/26] Track manual changes across shared light profiles (#1569) --- custom_components/adaptive_lighting/switch.py | 30 ++- tests/test_switch.py | 220 ++++++++++++++++++ 2 files changed, 234 insertions(+), 16 deletions(-) diff --git a/custom_components/adaptive_lighting/switch.py b/custom_components/adaptive_lighting/switch.py index f240a334..0a340c6c 100644 --- a/custom_components/adaptive_lighting/switch.py +++ b/custom_components/adaptive_lighting/switch.py @@ -2612,22 +2612,20 @@ class AdaptiveLightingManager: # Fix for https://github.com/basnijholt/adaptive-lighting/issues/1378 state = self.hass.states.get(eid) if state is not None and state.state == STATE_ON: - try: - switch = _switch_with_lights( - self.hass, - [eid], - expand_light_groups=False, - ) - await self.update_manually_controlled_from_event( - switch, - eid, - force=False, - ) - except NoSwitchFoundError: - _LOGGER.debug( - "No switch found for entity_id='%s' in 'on' event listener", - eid, - ) + switches = _switches_with_lights( + self.hass, + [eid], + expand_light_groups=False, + ) + for switch in switches: + # Preserve tracking for a lone profile, including when off. + # Shared lights notify each enabled owner using its takeover policy. + if switch.is_on or len(switches) == 1: + await self.update_manually_controlled_from_event( + switch, + eid, + force=False, + ) timer = self.auto_reset_manual_control_timers.get(eid) if ( diff --git a/tests/test_switch.py b/tests/test_switch.py index 03f0066c..733b1ef3 100644 --- a/tests/test_switch.py +++ b/tests/test_switch.py @@ -40,6 +40,7 @@ from homeassistant.components.adaptive_lighting.const import ( CONF_INITIAL_TRANSITION, CONF_MANUAL_CONTROL, CONF_MAX_BRIGHTNESS, + CONF_MAX_COLOR_TEMP, CONF_MIN_BRIGHTNESS, CONF_MIN_COLOR_TEMP, CONF_MULTI_LIGHT_INTERCEPT, @@ -1760,6 +1761,154 @@ async def test_manual_control_state_updates_shared_switches(hass): assert attrs["manual_control_color"] == [] +@pytest.mark.parametrize("intercept", [False, True]) +@pytest.mark.parametrize( + ( + "brightness_takeover", + "color_takeover", + "color_enabled", + "color_mode", + "expected_brightness", + "expected_color_calls", + "event_profiles", + ), + [ + ( + True, + True, + True, + TakeOverControlMode.PAUSE_CHANGED, + 77, + 1, + ["brightness", "color"], + ), + ( + True, + True, + True, + TakeOverControlMode.PAUSE_ALL, + 77, + 0, + ["brightness", "color"], + ), + (False, True, True, TakeOverControlMode.PAUSE_CHANGED, 77, 1, ["color"]), + (True, False, True, TakeOverControlMode.PAUSE_CHANGED, 77, 1, ["brightness"]), + (False, False, True, TakeOverControlMode.PAUSE_CHANGED, 128, 1, []), + (False, True, False, TakeOverControlMode.PAUSE_CHANGED, 128, 0, []), + (True, True, False, TakeOverControlMode.PAUSE_CHANGED, 77, 0, ["brightness"]), + ], +) +async def test_shared_profiles_track_manual_brightness( + hass, + intercept, + brightness_takeover, + color_takeover, + color_enabled, + color_mode, + expected_brightness, + expected_color_calls, + event_profiles, +): + """Shared owners track manual service calls and apply each profile's pause mode.""" + await setup_lights(hass) + profiles = {} + for name, takeover, mode in ( + ("brightness", brightness_takeover, TakeOverControlMode.PAUSE_CHANGED), + ("color", color_takeover, color_mode), + ): + _, switch = await setup_switch( + hass, + { + CONF_NAME: name, + CONF_LIGHTS: [ENTITY_LIGHT_1], + CONF_INTERCEPT: intercept, + CONF_TAKE_OVER_CONTROL: takeover, + CONF_TAKE_OVER_CONTROL_MODE: mode, + CONF_DETECT_NON_HA_CHANGES: False, + CONF_INITIAL_TRANSITION: 0, + CONF_TRANSITION: 0, + CONF_MIN_BRIGHTNESS: 50, + CONF_MAX_BRIGHTNESS: 50, + CONF_MIN_COLOR_TEMP: 4000, + CONF_MAX_COLOR_TEMP: 4000, + }, + ) + other_axis = ( + switch.adapt_color_switch + if name == "brightness" + else switch.adapt_brightness_switch + ) + await hass.services.async_call( + SWITCH_DOMAIN, + SERVICE_TURN_OFF, + {ATTR_ENTITY_ID: other_axis.entity_id}, + blocking=True, + ) + profiles[name] = switch + if not color_enabled: + await hass.services.async_call( + SWITCH_DOMAIN, + SERVICE_TURN_OFF, + {ATTR_ENTITY_ID: profiles["color"].entity_id}, + blocking=True, + ) + await hass.async_block_till_done() + + events = [] + remove_events = hass.bus.async_listen(f"{DOMAIN}.manual_control", events.append) + context = Context() + await hass.services.async_call( + LIGHT_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: ENTITY_LIGHT_1, ATTR_BRIGHTNESS: 77}, + context=context, + blocking=True, + ) + await hass.async_block_till_done() + calls = [] + remove_calls = hass.bus.async_listen(EVENT_CALL_SERVICE, calls.append) + for switch in profiles.values(): + if switch.is_on: + await switch._async_update_at_interval_action() + await hass.async_block_till_done() + remove_calls() + remove_events() + + light_calls = [ + event.data["service_data"] + for event in calls + if event.data["domain"] == LIGHT_DOMAIN + and event.data["service"] == SERVICE_TURN_ON + ] + assert ( + sum(ATTR_COLOR_TEMP_KELVIN in call for call in light_calls) + == expected_color_calls + ) + assert sum(ATTR_BRIGHTNESS in call for call in light_calls) == ( + expected_brightness == 128 + ) + assert ( + hass.states.get(ENTITY_LIGHT_1).attributes[ATTR_BRIGHTNESS] + == expected_brightness + ) + assert [event.data[SWITCH_DOMAIN] for event in events] == [ + profiles[name].entity_id for name in event_profiles + ] + assert all(event.context == context for event in events) + assert all( + event.data[CONF_MANUAL_CONTROL] == LightControlAttributes.BRIGHTNESS + for event in events + ) + for switch in profiles.values(): + if not switch.is_on: + continue + attrs = hass.states.get(switch.entity_id).attributes + assert attrs["manual_control_brightness"] == ( + [ENTITY_LIGHT_1] if event_profiles else [] + ) + assert attrs["manual_control_color"] == [] + + async def test_manual_control_state_ignores_incomplete_entries(hass): """An entry awaiting platform setup must not break another profile's updates.""" switch, (light, *_) = await setup_lights_and_switch(hass) @@ -4969,3 +5118,74 @@ async def test_forced_split_apply_stays_off(hass, off_action, cleanup): assert ATTR_BRIGHTNESS in turn_on_events[0].data["service_data"] assert ATTR_COLOR_TEMP_KELVIN not in turn_on_events[0].data["service_data"] assert hass.states.get(ENTITY_LIGHT_3).state == STATE_OFF + + +@pytest.mark.parametrize("intercept", [False, True]) +async def test_shared_profiles_keep_independent_sun_schedules( + hass, + intercept, + reset_time_zone, +): + """A later color sunrise keeps running after manual brightness takeover.""" + await hass.config.async_set_time_zone("UTC") + await setup_lights(hass) + profiles = [] + for name, sunrise, sunset in (("brightness", 6, 18), ("color", 10, 22)): + _, switch = await setup_switch( + hass, + { + CONF_NAME: name, + CONF_LIGHTS: [ENTITY_LIGHT_1], + CONF_INTERCEPT: intercept, + CONF_TAKE_OVER_CONTROL_MODE: TakeOverControlMode.PAUSE_CHANGED, + CONF_DETECT_NON_HA_CHANGES: False, + CONF_INITIAL_TRANSITION: 0, + CONF_TRANSITION: 0, + CONF_SUNRISE_TIME: datetime.time(sunrise), + CONF_SUNSET_TIME: datetime.time(sunset), + CONF_MIN_BRIGHTNESS: 10, + CONF_MAX_BRIGHTNESS: 90, + CONF_MIN_COLOR_TEMP: 2000, + CONF_MAX_COLOR_TEMP: 6000, + }, + ) + other_axis = ( + switch.adapt_color_switch + if name == "brightness" + else switch.adapt_brightness_switch + ) + await hass.services.async_call( + SWITCH_DOMAIN, + SERVICE_TURN_OFF, + {ATTR_ENTITY_ID: other_axis.entity_id}, + blocking=True, + ) + profiles.append(switch) + with patch( + "homeassistant.components.adaptive_lighting.color_and_brightness.utcnow", + return_value=datetime.datetime.fromisoformat("2026-09-05T08:00:00+00:00"), + ): + for switch in profiles: + await switch._async_update_at_interval_action() + await hass.async_block_till_done() + morning = hass.states.get(ENTITY_LIGHT_1) + assert morning.attributes[ATTR_BRIGHTNESS] > 26 + assert morning.attributes[ATTR_COLOR_TEMP_KELVIN] == 2000 + + await hass.services.async_call( + LIGHT_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: ENTITY_LIGHT_1, ATTR_BRIGHTNESS: 77}, + blocking=True, + ) + await hass.async_block_till_done() + with patch( + "homeassistant.components.adaptive_lighting.color_and_brightness.utcnow", + return_value=datetime.datetime.fromisoformat("2026-09-05T12:00:00+00:00"), + ): + for switch in profiles: + await switch._async_update_at_interval_action() + await hass.async_block_till_done() + noon = hass.states.get(ENTITY_LIGHT_1) + assert noon.attributes[ATTR_BRIGHTNESS] == 77 + assert noon.attributes[ATTR_COLOR_TEMP_KELVIN] > 2000 From ba2b7a3e442ac457dfa7844dc888ec14bee2b32d Mon Sep 17 00:00:00 2001 From: "allcontributors[bot]" <46447321+allcontributors[bot]@users.noreply.github.com> Date: Sun, 6 Sep 2026 19:09:30 +0200 Subject: [PATCH 04/26] docs: add jaynis as a contributor for code (#1571) * docs: update README.md * docs: update .all-contributorsrc --------- Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com> --- .all-contributorsrc | 9 +++++++++ README.md | 3 ++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/.all-contributorsrc b/.all-contributorsrc index 161b5633..6a23f772 100644 --- a/.all-contributorsrc +++ b/.all-contributorsrc @@ -1523,6 +1523,15 @@ "contributions": [ "bug" ] + }, + { + "login": "jaynis", + "name": "jaynis", + "avatar_url": "https://avatars.githubusercontent.com/u/1553675?v=4", + "profile": "https://github.com/jaynis", + "contributions": [ + "code" + ] } ], "contributorsPerLine": 7, diff --git a/README.md b/README.md index 3afc9a0d..281fbe1c 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ [![hacs_badge](https://img.shields.io/badge/HACS-Default-orange.svg?style=for-the-badge)](https://github.com/hacs/integration) ![Version](https://img.shields.io/github/v/release/basnijholt/adaptive-lighting?style=for-the-badge) -[![All Contributors](https://img.shields.io/badge/all_contributors-167-orange.svg?style=flat-square)](#contributors-) +[![All Contributors](https://img.shields.io/badge/all_contributors-168-orange.svg?style=flat-square)](#contributors-) # 🌞 Adaptive Lighting: Enhance Your Home's Atmosphere with Smart, Sun-Synchronized Lighting 🌙 @@ -926,6 +926,7 @@ Notice the values of `brightness_mode_time_light` and `brightness_mode_time_dark Wosten
Wosten

🐛 Zachary Priddy
Zachary Priddy

🤔 Andrew Blakeslee Moore
Andrew Blakeslee Moore

🐛 + jaynis
jaynis

💻 From 3231a1ac279d4800925ef734689e599459026dae Mon Sep 17 00:00:00 2001 From: Bas Nijholt Date: Sun, 6 Sep 2026 19:11:55 +0200 Subject: [PATCH 05/26] Add on-demand Home Assistant diagnostics (#1575) * Add privacy-safe config entry diagnostics * Clarify accumulated diagnostics values --- README.md | 10 + .../adaptive_lighting/diagnostics.py | 131 ++++++ docs/troubleshooting.md | 10 + tests/test_diagnostics.py | 372 ++++++++++++++++++ 4 files changed, 523 insertions(+) create mode 100644 custom_components/adaptive_lighting/diagnostics.py create mode 100644 tests/test_diagnostics.py diff --git a/README.md b/README.md index 281fbe1c..606341a6 100644 --- a/README.md +++ b/README.md @@ -583,6 +583,16 @@ logger: ``` After the issue occurs, create a new issue report with the log (`/config/home-assistant.log`). + +For support, use Home Assistant's **Download diagnostics** action on the +Adaptive Lighting config entry. The download is an on-demand snapshot of the +profile's current switches and currently tracked light targets. It does not +refresh group membership or predict targets a disabled profile would use after +being enabled. It does not create live sensors; existing switch attributes +remain the interface for automations. +The reported last adaptation values are the shared manager's latest retained +value for each attribute. They can come from different commands and do not +represent one sent command or the current desired state. diff --git a/custom_components/adaptive_lighting/diagnostics.py b/custom_components/adaptive_lighting/diagnostics.py new file mode 100644 index 00000000..80ae56d0 --- /dev/null +++ b/custom_components/adaptive_lighting/diagnostics.py @@ -0,0 +1,131 @@ +"""Diagnostics support for Adaptive Lighting.""" + +from typing import Any + +from homeassistant.components.light import ( + ATTR_BRIGHTNESS, + ATTR_COLOR_TEMP_KELVIN, + ATTR_RGB_COLOR, + ATTR_TRANSITION, +) +from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN +from homeassistant.config_entries import ConfigEntry +from homeassistant.const import STATE_OFF, STATE_ON, STATE_UNAVAILABLE, STATE_UNKNOWN +from homeassistant.core import HomeAssistant + +from .adaptation_utils import LightControlAttributes +from .const import ( + ADAPT_BRIGHTNESS_SWITCH, + ADAPT_COLOR_SWITCH, + ATTR_ADAPTIVE_LIGHTING_MANAGER, + DOMAIN, + SLEEP_MODE_SWITCH, +) +from .switch import AdaptiveLightingManager, AdaptiveSwitch + +_REPORTABLE_LIGHT_STATES = { + STATE_OFF, + STATE_ON, + STATE_UNAVAILABLE, + STATE_UNKNOWN, +} +_TARGET_ATTRIBUTES = ( + ATTR_BRIGHTNESS, + ATTR_COLOR_TEMP_KELVIN, + ATTR_RGB_COLOR, + ATTR_TRANSITION, +) + + +def _last_adaptation_values( + manager: AdaptiveLightingManager, + light: str, +) -> dict[str, Any] | None: + """Return latest retained value for each allowlisted adaptation attribute. + + Values may come from different commands because the manager merges partial + service data per attribute. + """ + service_data = manager.last_service_data.get(light) + if service_data is None: + return None + target = { + attribute: ( + list(service_data[attribute]) + if attribute == ATTR_RGB_COLOR + else service_data[attribute] + ) + for attribute in _TARGET_ATTRIBUTES + if attribute in service_data + } + return target or None + + +def _autoreset_seconds( + manager: AdaptiveLightingManager, + light: str, +) -> float | None: + """Return remaining time for a running global manual-control reset.""" + timer = manager.auto_reset_manual_control_timers.get(light) + if timer is None or not timer.is_running(): + return None + remaining = timer.remaining_time() + return round(remaining, 3) if remaining > 0 else None + + +async def async_get_config_entry_diagnostics( + hass: HomeAssistant, + config_entry: ConfigEntry, +) -> dict[str, Any]: + """Return an allowlisted, on-demand snapshot for one config entry.""" + domain_data = hass.data.get(DOMAIN) + if not isinstance(domain_data, dict): + return {"loaded": False} + entry_data = domain_data.get(config_entry.entry_id) + manager = domain_data.get(ATTR_ADAPTIVE_LIGHTING_MANAGER) + if not isinstance(entry_data, dict) or not isinstance( + manager, + AdaptiveLightingManager, + ): + return {"loaded": False} + switch = entry_data.get(SWITCH_DOMAIN) + if not isinstance(switch, AdaptiveSwitch): + return {"loaded": False} + + lights: dict[str, Any] = {} + for index, light in enumerate(sorted(switch.lights), start=1): + state = hass.states.get(light) + state_value = "missing" + if state is not None: + state_value = ( + state.state + if state.state in _REPORTABLE_LIGHT_STATES + else STATE_UNKNOWN + ) + manual_control = manager.get_manual_control_attributes(light) + lights[f"light_{index}"] = { + "state": state_value, + "global_manager_manual_control": { + "brightness": bool( + manual_control & LightControlAttributes.BRIGHTNESS, + ), + "color": bool(manual_control & LightControlAttributes.COLOR), + }, + "global_manager_autoreset_seconds": _autoreset_seconds(manager, light), + "global_manager_last_adaptation_values": _last_adaptation_values( + manager, + light, + ), + } + + return { + "loaded": True, + "profile_switches": { + "profile": switch.is_on, + "adapt_brightness": entry_data[ADAPT_BRIGHTNESS_SWITCH].is_on, + "adapt_color": entry_data[ADAPT_COLOR_SWITCH].is_on, + "sleep_mode": entry_data[SLEEP_MODE_SWITCH].is_on, + }, + "manager_fact_scope": "global_shared_across_profiles", + "lights": lights, + } diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 170f5ddf..c5f59353 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -25,6 +25,16 @@ logger: After the issue occurs, create a new issue report with the log (`/config/home-assistant.log`). +For support, use Home Assistant's **Download diagnostics** action on the +Adaptive Lighting config entry. The download is an on-demand snapshot of the +profile's current switches and currently tracked light targets. It does not +refresh group membership or predict targets a disabled profile would use after +being enabled. It does not create live sensors; existing switch attributes +remain the interface for automations. +The reported last adaptation values are the shared manager's latest retained +value for each attribute. They can come from different commands and do not +represent one sent command or the current desired state. + ## Common Problems & Solutions diff --git a/tests/test_diagnostics.py b/tests/test_diagnostics.py new file mode 100644 index 00000000..9c96b295 --- /dev/null +++ b/tests/test_diagnostics.py @@ -0,0 +1,372 @@ +"""Tests for Adaptive Lighting diagnostics.""" + +import json +from copy import deepcopy +from unittest.mock import patch + +import pytest +from homeassistant.components.adaptive_lighting.adaptation_utils import ( + AdaptationData, + LightControlAttributes, + _create_service_call_data_iterator, +) +from homeassistant.components.adaptive_lighting.const import ( + ATTR_ADAPTIVE_LIGHTING_MANAGER, + CONF_AUTORESET_CONTROL, + CONF_INTERCEPT, + CONF_MANUAL_CONTROL, + DOMAIN, + SERVICE_SET_MANUAL_CONTROL, +) +from homeassistant.components.adaptive_lighting.diagnostics import ( + async_get_config_entry_diagnostics, +) +from homeassistant.components.light import ( + ATTR_BRIGHTNESS, + ATTR_COLOR_TEMP_KELVIN, + ATTR_RGB_COLOR, + ATTR_TRANSITION, + SERVICE_TURN_ON, +) +from homeassistant.components.light import DOMAIN as LIGHT_DOMAIN +from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN +from homeassistant.config_entries import ConfigEntryState +from homeassistant.const import ( + ATTR_ENTITY_ID, + ATTR_SERVICE_DATA, + CONF_LIGHTS, + CONF_NAME, + EVENT_CALL_SERVICE, + EVENT_STATE_CHANGED, + STATE_OFF, + STATE_UNAVAILABLE, +) +from homeassistant.core import State + +from tests.common import MockConfigEntry +from tests.components.diagnostics import get_diagnostics_for_config_entry + +from .test_switch import ( + ENTITY_LIGHT_1, + ENTITY_LIGHT_2, + ENTITY_LIGHT_3, + setup_lights, +) + + +@pytest.fixture +async def cleanup_diagnostics(hass): + """Cancel integration tasks created by diagnostics fixtures.""" + yield + manager = hass.data.get(DOMAIN, {}).get(ATTR_ADAPTIVE_LIGHTING_MANAGER) + if manager is None: + return + 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_entry(hass, name, lights, **data): + """Set up a real Adaptive Lighting config entry.""" + entry = MockConfigEntry( + domain=DOMAIN, + data={ + CONF_NAME: name, + CONF_LIGHTS: lights, + CONF_INTERCEPT: False, + **data, + }, + ) + entry.add_to_hass(hass) + assert await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + assert entry.state is ConfigEntryState.LOADED + return entry, hass.data[DOMAIN][entry.entry_id][SWITCH_DOMAIN] + + +async def test_config_entry_diagnostics_reports_allowlisted_current_facts( + hass, + hass_client, + cleanup_diagnostics, +): + """Diagnostics report current selected-profile facts without identifiers.""" + await setup_lights(hass) + entry, switch = await _setup_entry( + hass, + "Private Upstairs Profile", + [ENTITY_LIGHT_1, ENTITY_LIGHT_2], + **{CONF_AUTORESET_CONTROL: 60}, + ) + other_entry, _ = await _setup_entry( + hass, + "Private Basement Profile", + [ENTITY_LIGHT_3], + ) + + await switch.adapt_color_switch.async_turn_off() + await switch.sleep_mode_switch.async_turn_on() + await hass.services.async_call( + DOMAIN, + SERVICE_SET_MANUAL_CONTROL, + { + ATTR_ENTITY_ID: switch.entity_id, + CONF_LIGHTS: [ENTITY_LIGHT_1], + CONF_MANUAL_CONTROL: "brightness", + }, + blocking=True, + ) + await hass.services.async_call( + DOMAIN, + SERVICE_SET_MANUAL_CONTROL, + { + ATTR_ENTITY_ID: switch.entity_id, + CONF_LIGHTS: [ENTITY_LIGHT_2], + CONF_MANUAL_CONTROL: "color", + }, + blocking=True, + ) + hass.states.async_set( + ENTITY_LIGHT_2, + STATE_UNAVAILABLE, + {"friendly_name": "Private Bedside Lamp", "room": "Private Bedroom"}, + ) + await hass.async_block_till_done() + + manager = hass.data[DOMAIN][ATTR_ADAPTIVE_LIGHTING_MANAGER] + assert manager.get_manual_control_attributes(ENTITY_LIGHT_1) == ( + LightControlAttributes.BRIGHTNESS + ) + manager.last_service_data[ENTITY_LIGHT_1] = { + ATTR_ENTITY_ID: ENTITY_LIGHT_1, + ATTR_BRIGHTNESS: 123, + ATTR_COLOR_TEMP_KELVIN: 3456, + ATTR_RGB_COLOR: (12, 34, 56), + ATTR_TRANSITION: 4.5, + "context_id": "private-context-id", + "friendly_name": "Private Bedside Lamp", + } + manager.last_service_data.pop(ENTITY_LIGHT_2, None) + + result = await get_diagnostics_for_config_entry(hass, hass_client, entry) + + assert result["loaded"] is True + assert result["profile_switches"] == { + "profile": True, + "adapt_brightness": True, + "adapt_color": False, + "sleep_mode": True, + } + assert result["manager_fact_scope"] == "global_shared_across_profiles" + assert list(result["lights"]) == ["light_1", "light_2"] + assert result["lights"]["light_1"]["state"] == "on" + assert result["lights"]["light_1"]["global_manager_manual_control"] == { + "brightness": True, + "color": False, + } + assert result["lights"]["light_1"][ + "global_manager_autoreset_seconds" + ] == pytest.approx(60, abs=2) + assert result["lights"]["light_1"]["global_manager_last_adaptation_values"] == { + ATTR_BRIGHTNESS: 123, + ATTR_COLOR_TEMP_KELVIN: 3456, + ATTR_RGB_COLOR: [12, 34, 56], + ATTR_TRANSITION: 4.5, + } + assert result["lights"]["light_2"] == { + "state": STATE_UNAVAILABLE, + "global_manager_manual_control": { + "brightness": False, + "color": True, + }, + "global_manager_autoreset_seconds": pytest.approx(60, abs=2), + "global_manager_last_adaptation_values": None, + } + + serialized = json.dumps(result, sort_keys=True) + for sensitive_value in ( + entry.entry_id, + other_entry.entry_id, + ENTITY_LIGHT_1, + ENTITY_LIGHT_2, + ENTITY_LIGHT_3, + "Private Upstairs Profile", + "Private Basement Profile", + "Private Bedside Lamp", + "Private Bedroom", + "private-context-id", + ): + assert sensitive_value not in serialized + + +async def test_diagnostics_labels_accumulated_partial_adaptation_values( + hass, + cleanup_diagnostics, +): + """Diagnostics do not describe merged per-attribute history as one command.""" + await setup_lights(hass) + entry, switch = await _setup_entry( + hass, + "Private Profile", + [ENTITY_LIGHT_1], + ) + commands = [ + { + ATTR_ENTITY_ID: ENTITY_LIGHT_1, + ATTR_BRIGHTNESS: 100, + ATTR_RGB_COLOR: (12, 34, 56), + ATTR_TRANSITION: 2, + }, + {ATTR_ENTITY_ID: ENTITY_LIGHT_1, ATTR_BRIGHTNESS: 180}, + {ATTR_ENTITY_ID: ENTITY_LIGHT_1, ATTR_COLOR_TEMP_KELVIN: 3500}, + ] + call_events = [] + remove_listener = hass.bus.async_listen(EVENT_CALL_SERVICE, call_events.append) + + await switch._execute_adaptation_calls( + AdaptationData( + entity_id=ENTITY_LIGHT_1, + context=switch.create_context("diagnostics_test"), + sleep_time=0, + service_call_datas=_create_service_call_data_iterator( + hass, + commands, + filter_by_state=False, + ), + force=True, + max_length=len(commands), + attributes=LightControlAttributes.ALL, + ), + ) + await hass.async_block_till_done() + remove_listener() + + actual_commands = [ + event.data[ATTR_SERVICE_DATA] + for event in call_events + if event.data["domain"] == LIGHT_DOMAIN + and event.data["service"] == SERVICE_TURN_ON + ] + assert actual_commands == commands + + result = await async_get_config_entry_diagnostics(hass, entry) + light = result["lights"]["light_1"] + assert "global_manager_last_sent_target" not in light + assert light["global_manager_last_adaptation_values"] == { + ATTR_BRIGHTNESS: 180, + ATTR_COLOR_TEMP_KELVIN: 3500, + ATTR_RGB_COLOR: [12, 34, 56], + ATTR_TRANSITION: 2, + } + + +async def test_diagnostics_preserves_restored_off_profile_tracked_group(hass): + """Diagnostics report tracked targets without refreshing late groups.""" + await setup_lights(hass) + group = "light.private_late_group" + members = [ENTITY_LIGHT_1, ENTITY_LIGHT_2] + with patch( + "homeassistant.helpers.restore_state.RestoreEntity.async_get_last_state", + return_value=State("switch.restored", STATE_OFF), + ): + entry, switch = await _setup_entry( + hass, + "Private Restored Profile", + [group], + ) + assert not switch.is_on + assert switch.lights == [group] + + hass.states.async_set( + group, + STATE_UNAVAILABLE, + {ATTR_ENTITY_ID: members, "friendly_name": "Private Late Group"}, + ) + await hass.async_block_till_done() + manager = hass.data[DOMAIN][ATTR_ADAPTIVE_LIGHTING_MANAGER] + manager_lights_before = set(manager.lights) + reset_times_before = dict(manager.auto_reset_manual_control_times) + + result = await async_get_config_entry_diagnostics(hass, entry) + + assert result["lights"] == { + "light_1": { + "state": STATE_UNAVAILABLE, + "global_manager_manual_control": { + "brightness": False, + "color": False, + }, + "global_manager_autoreset_seconds": None, + "global_manager_last_adaptation_values": None, + }, + } + assert switch.lights == [group] + assert manager.lights == manager_lights_before + assert manager.auto_reset_manual_control_times == reset_times_before + assert group not in json.dumps(result) + + +async def test_diagnostics_handles_missing_states_and_unload_without_side_effects( + hass, +): + """Diagnostics normalize states and never change live integration state.""" + await setup_lights(hass) + entry, switch = await _setup_entry( + hass, + "Private Profile", + [ENTITY_LIGHT_1, ENTITY_LIGHT_2, ENTITY_LIGHT_3, "light.private_missing"], + ) + hass.states.async_set(ENTITY_LIGHT_2, STATE_OFF) + hass.states.async_set(ENTITY_LIGHT_3, STATE_UNAVAILABLE) + await hass.async_block_till_done() + + manager = hass.data[DOMAIN][ATTR_ADAPTIVE_LIGHTING_MANAGER] + manual_control_before = dict(manager.manual_control) + last_service_data_before = deepcopy(manager.last_service_data) + timers_before = dict(manager.auto_reset_manual_control_timers) + switch_states_before = ( + switch.is_on, + switch.adapt_brightness_switch.is_on, + switch.adapt_color_switch.is_on, + switch.sleep_mode_switch.is_on, + ) + service_events = [] + state_events = [] + remove_service_listener = hass.bus.async_listen( + EVENT_CALL_SERVICE, + service_events.append, + ) + remove_state_listener = hass.bus.async_listen( + EVENT_STATE_CHANGED, + state_events.append, + ) + + result = await async_get_config_entry_diagnostics(hass, entry) + await hass.async_block_till_done() + remove_service_listener() + remove_state_listener() + + assert [light["state"] for light in result["lights"].values()] == [ + "on", + STATE_OFF, + STATE_UNAVAILABLE, + "missing", + ] + assert json.dumps(result) + assert not service_events + assert not state_events + assert manager.manual_control == manual_control_before + assert manager.last_service_data == last_service_data_before + assert manager.auto_reset_manual_control_timers == timers_before + assert ( + switch.is_on, + switch.adapt_brightness_switch.is_on, + switch.adapt_color_switch.is_on, + switch.sleep_mode_switch.is_on, + ) == switch_states_before + + assert await hass.config_entries.async_unload(entry.entry_id) + await hass.async_block_till_done() + assert await async_get_config_entry_diagnostics(hass, entry) == {"loaded": False} From 46d07388ba977e28b16a0201ed953aba43bad4d7 Mon Sep 17 00:00:00 2001 From: "allcontributors[bot]" <46447321+allcontributors[bot]@users.noreply.github.com> Date: Sun, 6 Sep 2026 19:12:41 +0200 Subject: [PATCH 06/26] docs: add alistairg as a contributor for code (#1572) * docs: update README.md * docs: update .all-contributorsrc --------- Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com> Co-authored-by: Bas Nijholt --- .all-contributorsrc | 9 +++++++++ README.md | 5 ++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/.all-contributorsrc b/.all-contributorsrc index 6a23f772..b346d2fd 100644 --- a/.all-contributorsrc +++ b/.all-contributorsrc @@ -1532,6 +1532,15 @@ "contributions": [ "code" ] + }, + { + "login": "alistairg", + "name": "Alistair Galbraith", + "avatar_url": "https://avatars.githubusercontent.com/u/272786?v=4", + "profile": "https://github.com/alistairg", + "contributions": [ + "code" + ] } ], "contributorsPerLine": 7, diff --git a/README.md b/README.md index 606341a6..12cc151a 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ [![hacs_badge](https://img.shields.io/badge/HACS-Default-orange.svg?style=for-the-badge)](https://github.com/hacs/integration) ![Version](https://img.shields.io/github/v/release/basnijholt/adaptive-lighting?style=for-the-badge) -[![All Contributors](https://img.shields.io/badge/all_contributors-168-orange.svg?style=flat-square)](#contributors-) +[![All Contributors](https://img.shields.io/badge/all_contributors-169-orange.svg?style=flat-square)](#contributors-) # 🌞 Adaptive Lighting: Enhance Your Home's Atmosphere with Smart, Sun-Synchronized Lighting 🌙 @@ -938,6 +938,9 @@ Notice the values of `brightness_mode_time_light` and `brightness_mode_time_dark Andrew Blakeslee Moore
Andrew Blakeslee Moore

🐛 jaynis
jaynis

💻 + + Alistair Galbraith
Alistair Galbraith

💻 + From d09b15a138abb024e4ea198d401e70e1860cef25 Mon Sep 17 00:00:00 2001 From: "allcontributors[bot]" <46447321+allcontributors[bot]@users.noreply.github.com> Date: Sun, 6 Sep 2026 19:13:13 +0200 Subject: [PATCH 07/26] docs: add hesseleo as a contributor for code (#1573) * docs: update README.md * docs: update .all-contributorsrc --------- Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com> Co-authored-by: Bas Nijholt --- .all-contributorsrc | 9 +++++++++ README.md | 3 ++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/.all-contributorsrc b/.all-contributorsrc index b346d2fd..260b8410 100644 --- a/.all-contributorsrc +++ b/.all-contributorsrc @@ -1541,6 +1541,15 @@ "contributions": [ "code" ] + }, + { + "login": "hesseleo", + "name": "Leonhard Hesse", + "avatar_url": "https://avatars.githubusercontent.com/u/44778508?v=4", + "profile": "https://github.com/hesseleo", + "contributions": [ + "code" + ] } ], "contributorsPerLine": 7, diff --git a/README.md b/README.md index 12cc151a..e56098eb 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ [![hacs_badge](https://img.shields.io/badge/HACS-Default-orange.svg?style=for-the-badge)](https://github.com/hacs/integration) ![Version](https://img.shields.io/github/v/release/basnijholt/adaptive-lighting?style=for-the-badge) -[![All Contributors](https://img.shields.io/badge/all_contributors-169-orange.svg?style=flat-square)](#contributors-) +[![All Contributors](https://img.shields.io/badge/all_contributors-170-orange.svg?style=flat-square)](#contributors-) # 🌞 Adaptive Lighting: Enhance Your Home's Atmosphere with Smart, Sun-Synchronized Lighting 🌙 @@ -940,6 +940,7 @@ Notice the values of `brightness_mode_time_light` and `brightness_mode_time_dark Alistair Galbraith
Alistair Galbraith

💻 + Leonhard Hesse
Leonhard Hesse

💻 From 51f2878b1668b5adf9a35d13acfdc317dbcfce01 Mon Sep 17 00:00:00 2001 From: "allcontributors[bot]" <46447321+allcontributors[bot]@users.noreply.github.com> Date: Sun, 6 Sep 2026 19:13:44 +0200 Subject: [PATCH 08/26] docs: add timstallmann as a contributor for code (#1574) * docs: update README.md * docs: update .all-contributorsrc --------- Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com> Co-authored-by: Bas Nijholt --- .all-contributorsrc | 9 +++++++++ README.md | 3 ++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/.all-contributorsrc b/.all-contributorsrc index 260b8410..4099e0bc 100644 --- a/.all-contributorsrc +++ b/.all-contributorsrc @@ -1550,6 +1550,15 @@ "contributions": [ "code" ] + }, + { + "login": "timstallmann", + "name": "Tim Stallmann", + "avatar_url": "https://avatars.githubusercontent.com/u/6741938?v=4", + "profile": "http://www.tim-maps.com", + "contributions": [ + "code" + ] } ], "contributorsPerLine": 7, diff --git a/README.md b/README.md index e56098eb..13785a60 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ [![hacs_badge](https://img.shields.io/badge/HACS-Default-orange.svg?style=for-the-badge)](https://github.com/hacs/integration) ![Version](https://img.shields.io/github/v/release/basnijholt/adaptive-lighting?style=for-the-badge) -[![All Contributors](https://img.shields.io/badge/all_contributors-170-orange.svg?style=flat-square)](#contributors-) +[![All Contributors](https://img.shields.io/badge/all_contributors-171-orange.svg?style=flat-square)](#contributors-) # 🌞 Adaptive Lighting: Enhance Your Home's Atmosphere with Smart, Sun-Synchronized Lighting 🌙 @@ -941,6 +941,7 @@ Notice the values of `brightness_mode_time_light` and `brightness_mode_time_dark Alistair Galbraith
Alistair Galbraith

💻 Leonhard Hesse
Leonhard Hesse

💻 + Tim Stallmann
Tim Stallmann

💻 From e2a3aae41666e52f6024386bde51e0df288a2124 Mon Sep 17 00:00:00 2001 From: "allcontributors[bot]" <46447321+allcontributors[bot]@users.noreply.github.com> Date: Sun, 6 Sep 2026 19:14:21 +0200 Subject: [PATCH 09/26] docs: add lehneres as a contributor for ideas (#1576) * docs: update README.md * docs: update .all-contributorsrc --------- Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com> Co-authored-by: Bas Nijholt --- .all-contributorsrc | 9 +++++++++ README.md | 3 ++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/.all-contributorsrc b/.all-contributorsrc index 4099e0bc..6004155e 100644 --- a/.all-contributorsrc +++ b/.all-contributorsrc @@ -1559,6 +1559,15 @@ "contributions": [ "code" ] + }, + { + "login": "lehneres", + "name": "lehneres", + "avatar_url": "https://avatars.githubusercontent.com/u/7437288?v=4", + "profile": "https://github.com/lehneres", + "contributions": [ + "ideas" + ] } ], "contributorsPerLine": 7, diff --git a/README.md b/README.md index 13785a60..4b90347a 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ [![hacs_badge](https://img.shields.io/badge/HACS-Default-orange.svg?style=for-the-badge)](https://github.com/hacs/integration) ![Version](https://img.shields.io/github/v/release/basnijholt/adaptive-lighting?style=for-the-badge) -[![All Contributors](https://img.shields.io/badge/all_contributors-171-orange.svg?style=flat-square)](#contributors-) +[![All Contributors](https://img.shields.io/badge/all_contributors-172-orange.svg?style=flat-square)](#contributors-) # 🌞 Adaptive Lighting: Enhance Your Home's Atmosphere with Smart, Sun-Synchronized Lighting 🌙 @@ -942,6 +942,7 @@ Notice the values of `brightness_mode_time_light` and `brightness_mode_time_dark Alistair Galbraith
Alistair Galbraith

💻 Leonhard Hesse
Leonhard Hesse

💻 Tim Stallmann
Tim Stallmann

💻 + lehneres
lehneres

🤔 From f7b50b12d94be7c921e42f40fe03a67b7a264ecf Mon Sep 17 00:00:00 2001 From: Bas Nijholt Date: Sun, 6 Sep 2026 19:59:56 +0200 Subject: [PATCH 10/26] Add validated blueprints for common automation examples (#1577) * Add minimum brightness automation and blueprint * Ignore independent profile event order in test * Add tested blueprints for sleep, schedules, and daylight --- README.md | 67 ++++ blueprints/automation/daylight_limit.yaml | 112 ++++++ blueprints/automation/schedule_profile.yaml | 57 +++ blueprints/automation/sleep_mode.yaml | 41 +++ .../automation/turn_off_at_minimum.yaml | 87 +++++ docs/automation-examples.md | 67 ++++ tests/test_automation_examples.py | 346 +++++++++++++++++- tests/test_switch.py | 5 +- 8 files changed, 772 insertions(+), 10 deletions(-) create mode 100644 blueprints/automation/daylight_limit.yaml create mode 100644 blueprints/automation/schedule_profile.yaml create mode 100644 blueprints/automation/sleep_mode.yaml create mode 100644 blueprints/automation/turn_off_at_minimum.yaml diff --git a/README.md b/README.md index 4b90347a..af016c54 100644 --- a/README.md +++ b/README.md @@ -272,6 +272,17 @@ Replace every entity ID below with the IDs from your Home Assistant instance. Fr Blocks that begin with `- alias` are entries for `automations.yaml`. Blocks with a top-level `script:` or `adaptive_lighting:` key are complete `configuration.yaml` examples. If your configuration uses `script: !include scripts.yaml`, omit that outer key and place its contents in `scripts.yaml`. +Four examples also have blueprints with selectors, so you can configure them without editing YAML: + +| Blueprint | Purpose | +| --- | --- | +| [Sleep mode](https://github.com/basnijholt/adaptive-lighting/blob/main/blueprints/automation/sleep_mode.yaml) | Synchronize several profiles with one sleep-mode helper. | +| [Minimum brightness](https://github.com/basnijholt/adaptive-lighting/blob/main/blueprints/automation/turn_off_at_minimum.yaml) | Turn one light off when its target crosses down to the minimum. | +| [Schedule profile](https://github.com/basnijholt/adaptive-lighting/blob/main/blueprints/automation/schedule_profile.yaml) | Apply brightness and color temperature from Schedule helper blocks. | +| [Daylight limit](https://github.com/basnijholt/adaptive-lighting/blob/main/blueprints/automation/daylight_limit.yaml) | Lower maximum brightness in strong daylight. | + +Copy a blueprint's link into **Settings → Automations & scenes → Blueprints → Import Blueprint**, then create an automation from it. Read the matching example below for setup and behavior. Each blueprint is tested through Home Assistant alongside its YAML example. The built-in manual-control timeout needs no automation; the scripts below remain useful as actions in your own automations. + `change_switch_settings` updates a profile while its main switch is off, but lights are adapted only while that switch is on. It preserves manual-control flags, so manually controlled lights remain paused.
@@ -294,6 +305,8 @@ This is a top-level `configuration.yaml` example. The timer clears manual contro
Toggle multiple Adaptive Lighting switches to "sleep mode" using an input_boolean.sleep_mode. +Also available as a [blueprint](https://github.com/basnijholt/adaptive-lighting/blob/main/blueprints/automation/sleep_mode.yaml). Select an input boolean and the sleep-mode switches it should control. + ```yaml - alias: "Adaptive lighting: toggle 'sleep mode'" trigger: @@ -316,6 +329,56 @@ This is a top-level `configuration.yaml` example. The timer clears manual contro
+
+Turn a light off when its adaptive brightness target reaches the minimum. + +Prefer a form over editing YAML? Import the [blueprint](https://github.com/basnijholt/adaptive-lighting/blob/main/blueprints/automation/turn_off_at_minimum.yaml) in Home Assistant under **Settings → Automations & scenes → Blueprints → Import Blueprint**. Select your profile, its matching adapt brightness switch, one light managed by that profile, and its minimum brightness percentage. Create one automation per light. If you change the profile's minimum later, update the automation too. The blueprint and YAML example below have the same behavior. + +The Adaptive Lighting switch already exposes its calculated `brightness_pct` target. Use its state changes to choose a power policy in an automation; no custom event is needed. This example assumes `min_brightness: 1`. Change `minimum_pct` to match your profile, and replace the switch and light entity IDs with your own. + +The comparison uses the same rounded 0–255 brightness as an adaptation command. Comparing floating-point percentages for exact equality can miss the minimum between updates. This detects the calculated target reaching its minimum command, not the bulb finishing a transition or reaching its physical dimming limit. + +```yaml +- alias: "Adaptive lighting: turn off at minimum brightness" + mode: single + triggers: + - trigger: state + entity_id: switch.adaptive_lighting_living_room + attribute: brightness_pct + conditions: + - condition: state + entity_id: + - switch.adaptive_lighting_living_room + - switch.adaptive_lighting_living_room_adapt_brightness + state: "on" + - condition: template + value_template: >- + {% set minimum_pct = 1 %} + {% set minimum = (minimum_pct * 255 / 100) | round(0) %} + {% set before = trigger.from_state.attributes.get('brightness_pct') + if trigger.from_state else none %} + {% set after = trigger.to_state.attributes.get('brightness_pct') + if trigger.to_state else none %} + {{ is_number(before) and is_number(after) + and (before | float * 255 / 100) | round(0) > minimum + and (after | float * 255 / 100) | round(0) <= minimum }} + - condition: state + entity_id: light.living_room + state: "on" + - condition: template + value_template: >- + {{ 'light.living_room' not in + (state_attr('switch.adaptive_lighting_living_room', 'manual_control') or []) }} + actions: + - action: light.turn_off + target: + entity_id: light.living_room +``` + +This runs once when a valid target crosses down into the minimum range. It skips lights currently marked as manually controlled, does not repeatedly turn them off while the target remains low, and does not turn them back on later. Startup or re-enabling the profile while already at the minimum is not a new crossing. Sleep mode can also cause a crossing if its brightness is at or below the chosen minimum. Changing sleep mode clears manual control by default; set `reset_manual_control_on_sleep_mode_change: false` if you want to preserve it. For a bedtime-only policy, trigger directly on the sleep-mode switch changing to `on` instead. + +
+
Set sunrise and sunset from an alarm. @@ -342,6 +405,8 @@ script:
Use a Schedule helper as a step-based custom lighting profile. +Also available as a [blueprint](https://github.com/basnijholt/adaptive-lighting/blob/main/blueprints/automation/schedule_profile.yaml). Select the main profile switch and your Schedule helper. + Create a [Schedule helper](https://www.home-assistant.io/integrations/schedule/) named `Adaptive Lighting Profile`. Add time blocks with Additional data like this: ```yaml @@ -391,6 +456,8 @@ This creates step changes at block boundaries. It does not interpolate between s
Reduce daytime brightness when an illuminance sensor detects strong daylight. +Also available as a [blueprint](https://github.com/basnijholt/adaptive-lighting/blob/main/blueprints/automation/daylight_limit.yaml). Select the profile and sensor, then set the lux thresholds and brightness limits. The high lux threshold must exceed the low threshold; the blueprint does nothing if they are reversed or equal. + Keep a low configured `min_brightness` for late night and let an automation lower `max_brightness` while the room has ample daylight. Use a sensor that is not significantly affected by the controlled lights to avoid a feedback loop. ```yaml diff --git a/blueprints/automation/daylight_limit.yaml b/blueprints/automation/daylight_limit.yaml new file mode 100644 index 00000000..bc57d434 --- /dev/null +++ b/blueprints/automation/daylight_limit.yaml @@ -0,0 +1,112 @@ +blueprint: + name: "Adaptive Lighting: limit brightness in daylight" + description: >- + Lower a profile's maximum brightness in strong daylight and restore the + chosen normal maximum when daylight falls. Separate lux thresholds prevent + repeated changes near a single threshold. Use a sensor not significantly + affected by the controlled lights. Keep the daylight maximum at or above + the profile's minimum unless you want an inverted brightness curve. + Startup waits up to five minutes for a numeric sensor reading; a reading + between the thresholds leaves the configured maximum unchanged. + domain: automation + homeassistant: + min_version: "2025.9.0" + input: + adaptive_switch: + name: Adaptive Lighting profile + description: Select the main profile switch, not a sleep or adaptation switch. + selector: + entity: + filter: + domain: switch + integration: adaptive_lighting + illuminance_sensor: + name: Illuminance sensor + selector: + entity: + filter: + domain: sensor + device_class: illuminance + high_lux: + name: Strong daylight threshold + description: Must be greater than the low daylight threshold. + default: 300 + selector: + number: + min: 0 + max: 200000 + mode: box + unit_of_measurement: lx + low_lux: + name: Low daylight threshold + default: 200 + selector: + number: + min: 0 + max: 200000 + mode: box + unit_of_measurement: lx + daylight_maximum: + name: Maximum brightness in strong daylight + default: 30 + selector: + number: + min: 1 + max: 100 + mode: box + unit_of_measurement: "%" + normal_maximum: + name: Normal maximum brightness + default: 100 + selector: + number: + min: 1 + max: 100 + mode: box + unit_of_measurement: "%" + +mode: restart +variables: + illuminance_sensor: !input illuminance_sensor + high_lux: !input high_lux + low_lux: !input low_lux +triggers: + - trigger: numeric_state + entity_id: !input illuminance_sensor + above: !input high_lux + - trigger: numeric_state + entity_id: !input illuminance_sensor + below: !input low_lux + - trigger: homeassistant + event: start + id: startup +conditions: + - condition: template + value_template: "{{ high_lux > low_lux }}" +actions: + - if: + - condition: trigger + id: startup + then: + - wait_template: "{{ is_number(states(illuminance_sensor)) }}" + timeout: "00:05:00" + continue_on_timeout: false + - choose: + - conditions: + - condition: numeric_state + entity_id: !input illuminance_sensor + above: !input high_lux + sequence: + - action: adaptive_lighting.change_switch_settings + data: + entity_id: !input adaptive_switch + max_brightness: !input daylight_maximum + - conditions: + - condition: numeric_state + entity_id: !input illuminance_sensor + below: !input low_lux + sequence: + - action: adaptive_lighting.change_switch_settings + data: + entity_id: !input adaptive_switch + max_brightness: !input normal_maximum diff --git a/blueprints/automation/schedule_profile.yaml b/blueprints/automation/schedule_profile.yaml new file mode 100644 index 00000000..64ccf17a --- /dev/null +++ b/blueprints/automation/schedule_profile.yaml @@ -0,0 +1,57 @@ +blueprint: + name: "Adaptive Lighting: scheduled profile" + description: >- + Apply fixed brightness and color temperature from a Schedule helper's + brightness_pct and color_temp_kelvin attributes. Uses step changes, not + interpolation. Missing attributes fall back to 1% and 2000 K. Outside an + active block, restores ALL configured profile settings. Use this only if + other automations do not also change runtime settings on this profile. + Reapplies the active block on Home Assistant startup. Updates settings + while the profile is off without enabling it; preserves manual control. + domain: automation + homeassistant: + min_version: "2025.9.0" + input: + adaptive_switch: + name: Adaptive Lighting profile + description: Select the main profile switch, not a sleep or adaptation switch. + selector: + entity: + filter: + domain: switch + integration: adaptive_lighting + schedule_entity: + name: Schedule helper + description: Add brightness_pct (1–100) and color_temp_kelvin to each block's Additional data. + selector: + entity: + filter: + domain: schedule + +mode: restart +variables: + schedule_entity: !input schedule_entity +triggers: + - trigger: state + entity_id: !input schedule_entity + - trigger: homeassistant + event: start +actions: + - choose: + - conditions: + - condition: state + entity_id: !input schedule_entity + state: "on" + sequence: + - action: adaptive_lighting.change_switch_settings + data: + entity_id: !input adaptive_switch + min_brightness: "{{ state_attr(schedule_entity, 'brightness_pct') | int(1) }}" + max_brightness: "{{ state_attr(schedule_entity, 'brightness_pct') | int(1) }}" + min_color_temp: "{{ state_attr(schedule_entity, 'color_temp_kelvin') | int(2000) }}" + max_color_temp: "{{ state_attr(schedule_entity, 'color_temp_kelvin') | int(2000) }}" + default: + - action: adaptive_lighting.change_switch_settings + data: + entity_id: !input adaptive_switch + use_defaults: configuration diff --git a/blueprints/automation/sleep_mode.yaml b/blueprints/automation/sleep_mode.yaml new file mode 100644 index 00000000..fe57079b --- /dev/null +++ b/blueprints/automation/sleep_mode.yaml @@ -0,0 +1,41 @@ +blueprint: + name: "Adaptive Lighting: synchronize sleep mode" + description: >- + Keep the selected Adaptive Lighting sleep-mode switches in sync with an + input boolean, including its restored state at Home Assistant startup. + Unknown or unavailable helper states are ignored. Select only sleep-mode + switches, not the main profile or adaptation switches. + domain: automation + homeassistant: + min_version: "2025.9.0" + input: + sleep_helper: + name: Sleep-mode helper + selector: + entity: + filter: + domain: input_boolean + sleep_switches: + name: Adaptive Lighting sleep-mode switches + selector: + entity: + multiple: true + filter: + domain: switch + integration: adaptive_lighting + +triggers: + - trigger: state + entity_id: !input sleep_helper + - trigger: homeassistant + event: start +variables: + sleep_helper: !input sleep_helper + sleep_mode: "{{ states(sleep_helper) }}" +conditions: + - condition: template + value_template: "{{ sleep_mode in ['on', 'off'] }}" +actions: + - action: "switch.turn_{{ sleep_mode }}" + target: + entity_id: !input sleep_switches diff --git a/blueprints/automation/turn_off_at_minimum.yaml b/blueprints/automation/turn_off_at_minimum.yaml new file mode 100644 index 00000000..6593e398 --- /dev/null +++ b/blueprints/automation/turn_off_at_minimum.yaml @@ -0,0 +1,87 @@ +blueprint: + name: "Adaptive Lighting: turn off at minimum brightness" + description: >- + Turn one light off when its Adaptive Lighting target crosses down into the + chosen minimum brightness range. Compares rounded 0–255 commands, not the + bulb's physical dimming limit or transition completion. Skips lights currently + marked as manually controlled. Changing sleep mode clears manual control by + default; set reset_manual_control_on_sleep_mode_change to false in your + profile to preserve it. Does not turn lights back on or repeatedly turn them off + while the target stays low. Startup at the minimum does not trigger it. + Sleep mode can trigger it if its target crosses the chosen minimum. + Select a light managed by the chosen profile and its matching brightness switch. + domain: automation + homeassistant: + min_version: "2025.9.0" + input: + adaptive_switch: + name: Adaptive Lighting profile + description: Select the main Adaptive Lighting switch, not a sleep or adaptation switch. + selector: + entity: + filter: + domain: switch + integration: adaptive_lighting + brightness_switch: + name: Adapt brightness switch + description: Select the adapt brightness switch belonging to the same profile. + selector: + entity: + filter: + domain: switch + integration: adaptive_lighting + light_entity: + name: Light + description: Select one light managed by this profile. Create an automation for each light. + selector: + entity: + filter: + domain: light + minimum_pct: + name: Minimum brightness + description: Match the profile's min_brightness setting. Update this if that setting changes. + default: 1 + selector: + number: + min: 1 + max: 100 + step: 1 + unit_of_measurement: "%" + mode: box + +mode: single +variables: + adaptive_switch: !input adaptive_switch + light_entity: !input light_entity + minimum_pct: !input minimum_pct +triggers: + - trigger: state + entity_id: !input adaptive_switch + attribute: brightness_pct +conditions: + - condition: state + entity_id: !input adaptive_switch + state: "on" + - condition: state + entity_id: !input brightness_switch + state: "on" + - condition: template + value_template: >- + {% set minimum = (minimum_pct * 255 / 100) | round(0) %} + {% set before = trigger.from_state.attributes.get('brightness_pct') + if trigger.from_state else none %} + {% set after = trigger.to_state.attributes.get('brightness_pct') + if trigger.to_state else none %} + {{ is_number(before) and is_number(after) + and (before | float * 255 / 100) | round(0) > minimum + and (after | float * 255 / 100) | round(0) <= minimum }} + - condition: state + entity_id: !input light_entity + state: "on" + - condition: template + value_template: >- + {{ light_entity not in (state_attr(adaptive_switch, 'manual_control') or []) }} +actions: + - action: light.turn_off + target: + entity_id: !input light_entity diff --git a/docs/automation-examples.md b/docs/automation-examples.md index 9a8c21f3..5686c5d7 100644 --- a/docs/automation-examples.md +++ b/docs/automation-examples.md @@ -16,6 +16,17 @@ Replace every entity ID below with the IDs from your Home Assistant instance. Fr Blocks that begin with `- alias` are entries for `automations.yaml`. Blocks with a top-level `script:` or `adaptive_lighting:` key are complete `configuration.yaml` examples. If your configuration uses `script: !include scripts.yaml`, omit that outer key and place its contents in `scripts.yaml`. +Four examples also have blueprints with selectors, so you can configure them without editing YAML: + +| Blueprint | Purpose | +| --- | --- | +| [Sleep mode](https://github.com/basnijholt/adaptive-lighting/blob/main/blueprints/automation/sleep_mode.yaml) | Synchronize several profiles with one sleep-mode helper. | +| [Minimum brightness](https://github.com/basnijholt/adaptive-lighting/blob/main/blueprints/automation/turn_off_at_minimum.yaml) | Turn one light off when its target crosses down to the minimum. | +| [Schedule profile](https://github.com/basnijholt/adaptive-lighting/blob/main/blueprints/automation/schedule_profile.yaml) | Apply brightness and color temperature from Schedule helper blocks. | +| [Daylight limit](https://github.com/basnijholt/adaptive-lighting/blob/main/blueprints/automation/daylight_limit.yaml) | Lower maximum brightness in strong daylight. | + +Copy a blueprint's link into **Settings → Automations & scenes → Blueprints → Import Blueprint**, then create an automation from it. Read the matching example below for setup and behavior. Each blueprint is tested through Home Assistant alongside its YAML example. The built-in manual-control timeout needs no automation; the scripts below remain useful as actions in your own automations. + `change_switch_settings` updates a profile while its main switch is off, but lights are adapted only while that switch is on. It preserves manual-control flags, so manually controlled lights remain paused.
@@ -38,6 +49,8 @@ This is a top-level `configuration.yaml` example. The timer clears manual contro
Toggle multiple Adaptive Lighting switches to "sleep mode" using an input_boolean.sleep_mode. +Also available as a [blueprint](https://github.com/basnijholt/adaptive-lighting/blob/main/blueprints/automation/sleep_mode.yaml). Select an input boolean and the sleep-mode switches it should control. + ```yaml - alias: "Adaptive lighting: toggle 'sleep mode'" trigger: @@ -60,6 +73,56 @@ This is a top-level `configuration.yaml` example. The timer clears manual contro
+
+Turn a light off when its adaptive brightness target reaches the minimum. + +Prefer a form over editing YAML? Import the [blueprint](https://github.com/basnijholt/adaptive-lighting/blob/main/blueprints/automation/turn_off_at_minimum.yaml) in Home Assistant under **Settings → Automations & scenes → Blueprints → Import Blueprint**. Select your profile, its matching adapt brightness switch, one light managed by that profile, and its minimum brightness percentage. Create one automation per light. If you change the profile's minimum later, update the automation too. The blueprint and YAML example below have the same behavior. + +The Adaptive Lighting switch already exposes its calculated `brightness_pct` target. Use its state changes to choose a power policy in an automation; no custom event is needed. This example assumes `min_brightness: 1`. Change `minimum_pct` to match your profile, and replace the switch and light entity IDs with your own. + +The comparison uses the same rounded 0–255 brightness as an adaptation command. Comparing floating-point percentages for exact equality can miss the minimum between updates. This detects the calculated target reaching its minimum command, not the bulb finishing a transition or reaching its physical dimming limit. + +```yaml +- alias: "Adaptive lighting: turn off at minimum brightness" + mode: single + triggers: + - trigger: state + entity_id: switch.adaptive_lighting_living_room + attribute: brightness_pct + conditions: + - condition: state + entity_id: + - switch.adaptive_lighting_living_room + - switch.adaptive_lighting_living_room_adapt_brightness + state: "on" + - condition: template + value_template: >- + {% set minimum_pct = 1 %} + {% set minimum = (minimum_pct * 255 / 100) | round(0) %} + {% set before = trigger.from_state.attributes.get('brightness_pct') + if trigger.from_state else none %} + {% set after = trigger.to_state.attributes.get('brightness_pct') + if trigger.to_state else none %} + {{ is_number(before) and is_number(after) + and (before | float * 255 / 100) | round(0) > minimum + and (after | float * 255 / 100) | round(0) <= minimum }} + - condition: state + entity_id: light.living_room + state: "on" + - condition: template + value_template: >- + {{ 'light.living_room' not in + (state_attr('switch.adaptive_lighting_living_room', 'manual_control') or []) }} + actions: + - action: light.turn_off + target: + entity_id: light.living_room +``` + +This runs once when a valid target crosses down into the minimum range. It skips lights currently marked as manually controlled, does not repeatedly turn them off while the target remains low, and does not turn them back on later. Startup or re-enabling the profile while already at the minimum is not a new crossing. Sleep mode can also cause a crossing if its brightness is at or below the chosen minimum. Changing sleep mode clears manual control by default; set `reset_manual_control_on_sleep_mode_change: false` if you want to preserve it. For a bedtime-only policy, trigger directly on the sleep-mode switch changing to `on` instead. + +
+
Set sunrise and sunset from an alarm. @@ -86,6 +149,8 @@ script:
Use a Schedule helper as a step-based custom lighting profile. +Also available as a [blueprint](https://github.com/basnijholt/adaptive-lighting/blob/main/blueprints/automation/schedule_profile.yaml). Select the main profile switch and your Schedule helper. + Create a [Schedule helper](https://www.home-assistant.io/integrations/schedule/) named `Adaptive Lighting Profile`. Add time blocks with Additional data like this: ```yaml @@ -135,6 +200,8 @@ This creates step changes at block boundaries. It does not interpolate between s
Reduce daytime brightness when an illuminance sensor detects strong daylight. +Also available as a [blueprint](https://github.com/basnijholt/adaptive-lighting/blob/main/blueprints/automation/daylight_limit.yaml). Select the profile and sensor, then set the lux thresholds and brightness limits. The high lux threshold must exceed the low threshold; the blueprint does nothing if they are reversed or equal. + Keep a low configured `min_brightness` for late night and let an automation lower `max_brightness` while the room has ample daylight. Use a sensor that is not significantly affected by the controlled lights to avoid a feedback loop. ```yaml diff --git a/tests/test_automation_examples.py b/tests/test_automation_examples.py index e5f3c2d5..d0dc8e3e 100644 --- a/tests/test_automation_examples.py +++ b/tests/test_automation_examples.py @@ -4,6 +4,7 @@ from __future__ import annotations import asyncio import re +import shutil from datetime import UTC, datetime, timedelta from pathlib import Path from typing import TYPE_CHECKING @@ -16,6 +17,9 @@ from homeassistant.components.adaptive_lighting.adaptation_utils import ( LightControlAttributes, ) from homeassistant.components.adaptive_lighting.const import ( + CONF_BRIGHTNESS_MODE, + CONF_BRIGHTNESS_MODE_TIME_DARK, + CONF_BRIGHTNESS_MODE_TIME_LIGHT, CONF_INITIAL_TRANSITION, CONF_LIGHTS, CONF_MAX_BRIGHTNESS, @@ -31,6 +35,7 @@ from homeassistant.components.adaptive_lighting.const import ( CONF_TRANSITION, DOMAIN, ) +from homeassistant.components.blueprint.models import Blueprint from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP_KELVIN, @@ -52,6 +57,7 @@ from homeassistant.const import ( from homeassistant.core import CoreState, Event, HomeAssistant, State, callback from homeassistant.setup import async_setup_component from homeassistant.util import dt as dt_util +from homeassistant.util import yaml as yaml_util from tests.common import async_fire_time_changed @@ -146,12 +152,247 @@ def _prepare_hass_startup(hass: HomeAssistant) -> None: hass.set_state(CoreState.not_running) +def _blueprint_config(hass, tmp_path, filename, inputs, alias): + """Install an actual published blueprint for Home Assistant to load.""" + relative_path = f"adaptive_lighting/{filename}" + hass.config.config_dir = str(tmp_path) + destination = tmp_path / "blueprints" / "automation" / relative_path + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(README.parent / "blueprints" / "automation" / filename, destination) + return { + "alias": alias, + "use_blueprint": {"path": relative_path, "input": inputs}, + } + + +@pytest.fixture(params=["yaml", "blueprint"]) +def published_automation(hass: HomeAssistant, tmp_path: Path, request): + """Use the published YAML or blueprint with the same behavioral assertions.""" + + def config(summary, filename, inputs): + yaml_config = _yaml_documents(summary)[-1] + if request.param == "yaml": + return yaml_config + return _blueprint_config( + hass, + tmp_path, + filename, + inputs, + yaml_config[0]["alias"], + ) + + return config + + +@pytest.mark.parametrize( + "path", + sorted((README.parent / "blueprints" / "automation").glob("*.yaml")), + ids=lambda path: path.stem, +) +def test_published_blueprint_schema(path: Path) -> None: + """Validate every published blueprint with Home Assistant's own schema.""" + blueprint = Blueprint( + yaml_util.load_yaml(str(path)), + expected_domain=automation.DOMAIN, + schema=automation.config.AUTOMATION_BLUEPRINT_SCHEMA, + ) + assert blueprint.validate() is None + + +@pytest.fixture(params=["yaml", "blueprint", "blueprint-custom-minimum"]) +def minimum_automation_config(hass: HomeAssistant, tmp_path: Path, request): + """Run the same behavior checks against both published formats.""" + if request.param == "yaml": + return _yaml_documents( + "Turn a light off when its adaptive brightness target reaches the minimum.", + )[0] + inputs = { + "adaptive_switch": "switch.adaptive_lighting_living_room", + "brightness_switch": "switch.adaptive_lighting_living_room_adapt_brightness", + "light_entity": "light.living_room", + } + if request.param == "blueprint-custom-minimum": + inputs["minimum_pct"] = 10 + return _blueprint_config( + hass, + tmp_path, + "turn_off_at_minimum.yaml", + inputs, + "Turn off at minimum", + ) + + +@pytest.mark.parametrize("manual_control", [False, True]) +@pytest.mark.parametrize("trigger_kind", ["interval", "sleep"]) +@patch( + "homeassistant.components.adaptive_lighting.color_and_brightness.utcnow", + new=dt_util.utcnow, +) +async def test_minimum_brightness_power_automation( + hass: HomeAssistant, + freezer, + manual_control: bool, + trigger_kind: str, + minimum_automation_config, +) -> None: + """Catch exact-float comparisons, repeated power actions, or lost manual control.""" + minimum = ( + minimum_automation_config.get("use_blueprint", {}) + .get("input", {}) + .get("minimum_pct", 1) + if isinstance(minimum_automation_config, dict) + else 1 + ) + freezer.move_to(datetime(2026, 9, 6, 18, 58, tzinfo=dt_util.DEFAULT_TIME_ZONE)) + await _setup_template_lights(hass, ["Living Room"]) + await hass.services.async_call( + LIGHT_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: "light.living_room", ATTR_BRIGHTNESS: 77}, + blocking=True, + ) + _, adaptive_switch = await setup_switch( + hass, + { + CONF_NAME: "Living Room", + CONF_LIGHTS: ["light.living_room"], + CONF_MIN_BRIGHTNESS: minimum, + CONF_MAX_BRIGHTNESS: 100, + CONF_BRIGHTNESS_MODE: "linear", + CONF_BRIGHTNESS_MODE_TIME_DARK: timedelta(hours=1), + CONF_BRIGHTNESS_MODE_TIME_LIGHT: timedelta(hours=1), + CONF_SUNRISE_TIME: "06:00:00", + CONF_SUNSET_TIME: "18:00:00", + CONF_TRANSITION: 0, + CONF_INITIAL_TRANSITION: 0, + }, + ) + if manual_control: + await hass.services.async_call( + DOMAIN, + "set_manual_control", + {ATTR_ENTITY_ID: adaptive_switch.entity_id, "manual_control": True}, + blocking=True, + ) + await _setup_automation(hass, minimum_automation_config) + off_calls = [] + + @callback + def record_off(event: Event) -> None: + if ( + event.data["domain"] == LIGHT_DOMAIN + and event.data["service"] == SERVICE_TURN_OFF + ): + off_calls.append(event.data["service_data"]) + + hass.bus.async_listen(EVENT_CALL_SERVICE, record_off) + assert hass.states.get("light.living_room").state == STATE_ON + assert adaptive_switch.extra_state_attributes["brightness_pct"] > minimum + 1 + + # The curve is above the minimum, but rounds to the same brightness command. + freezer.move_to(datetime(2026, 9, 6, 18, 59, 50, tzinfo=dt_util.DEFAULT_TIME_ZONE)) + if trigger_kind == "sleep": + await hass.services.async_call( + SWITCH_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: "switch.adaptive_lighting_living_room_sleep_mode"}, + blocking=True, + ) + else: + await adaptive_switch._async_update_at_interval_action() + await hass.async_block_till_done() + if trigger_kind == "sleep": + assert adaptive_switch.extra_state_attributes["brightness_pct"] == 1 + else: + assert ( + minimum + < adaptive_switch.extra_state_attributes["brightness_pct"] + < minimum + 0.2 + ) + # The default sleep-mode policy clears manual control before publishing its target. + should_turn_off = not manual_control or trigger_kind == "sleep" + assert hass.states.get("light.living_room").state == ( + STATE_OFF if should_turn_off else STATE_ON + ) + assert len(off_calls) == int(should_turn_off) + + # Further target changes inside the minimum command range do not retrigger. + freezer.move_to(datetime(2026, 9, 6, 19, 1, tzinfo=dt_util.DEFAULT_TIME_ZONE)) + await adaptive_switch._async_update_at_interval_action() + await hass.async_block_till_done() + assert adaptive_switch.extra_state_attributes["brightness_pct"] == ( + 1 if trigger_kind == "sleep" else minimum + ) + assert len(off_calls) == int(should_turn_off) + + if should_turn_off: + await hass.services.async_call( + LIGHT_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: "light.living_room"}, + blocking=True, + ) + await hass.async_block_till_done() + assert hass.states.get("light.living_room").state == STATE_ON + assert len(off_calls) == 1 + + +@pytest.mark.parametrize("previous", [None, "unknown", "unavailable"]) +async def test_minimum_brightness_ignores_missing_previous_target( + hass: HomeAssistant, + previous: str | None, + minimum_automation_config, +) -> None: + """A missing target must not become a numeric crossing during recovery.""" + await _setup_template_lights(hass, ["Living Room"]) + await hass.services.async_call( + LIGHT_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: "light.living_room"}, + blocking=True, + ) + _, adaptive_switch = await setup_switch( + hass, + { + CONF_NAME: "Living Room", + CONF_LIGHTS: ["light.living_room"], + CONF_MIN_BRIGHTNESS: 1, + CONF_MAX_BRIGHTNESS: 1, + CONF_TRANSITION: 0, + CONF_INITIAL_TRANSITION: 0, + }, + ) + await _setup_automation(hass, minimum_automation_config) + attributes = dict(hass.states.get(adaptive_switch.entity_id).attributes) + assert attributes["brightness_pct"] == 1 + if previous is None: + hass.states.async_remove(adaptive_switch.entity_id) + else: + hass.states.async_set( + adaptive_switch.entity_id, + previous, + {**attributes, "brightness_pct": previous}, + ) + await hass.async_block_till_done() + hass.states.async_set(adaptive_switch.entity_id, STATE_ON, attributes) + await hass.async_block_till_done() + assert hass.states.get("light.living_room").state == STATE_ON + + async def test_schedule_profile_executes_blocks_and_restore( hass: HomeAssistant, + published_automation, ) -> None: """Catch ignored attribute changes, incomplete restore, or switch coupling.""" summary = "Use a Schedule helper as a step-based custom lighting profile." - automation_config = _yaml_documents(summary)[-1] + automation_config = published_automation( + summary, + "schedule_profile.yaml", + { + "adaptive_switch": "switch.adaptive_lighting_living_room", + "schedule_entity": "schedule.adaptive_lighting_profile", + }, + ) _, adaptive_switch = await setup_switch( hass, { @@ -220,11 +461,21 @@ async def test_schedule_profile_executes_blocks_and_restore( assert adaptive_switch._sun_light_settings.max_color_temp == 2750 -async def test_schedule_profile_reapplies_at_startup(hass: HomeAssistant) -> None: +async def test_schedule_profile_reapplies_at_startup( + hass: HomeAssistant, + published_automation, +) -> None: """Verify startup applies the already-active schedule block.""" _prepare_hass_startup(hass) summary = "Use a Schedule helper as a step-based custom lighting profile." - automation_config = _yaml_documents(summary)[-1] + automation_config = published_automation( + summary, + "schedule_profile.yaml", + { + "adaptive_switch": "switch.adaptive_lighting_living_room", + "schedule_entity": "schedule.adaptive_lighting_profile", + }, + ) _, adaptive_switch = await setup_switch(hass, {CONF_NAME: "Living Room"}) hass.states.async_set( "schedule.adaptive_lighting_profile", @@ -241,12 +492,22 @@ async def test_schedule_profile_reapplies_at_startup(hass: HomeAssistant) -> Non assert adaptive_switch._sun_light_settings.max_color_temp == 2500 -async def test_lux_profile_executes_hysteresis(hass: HomeAssistant) -> None: +async def test_lux_profile_executes_hysteresis( + hass: HomeAssistant, + published_automation, +) -> None: """Catch missing threshold actions or changes inside the dead band.""" summary = ( "Reduce daytime brightness when an illuminance sensor detects strong daylight." ) - automation_config = _yaml_documents(summary)[0] + automation_config = published_automation( + summary, + "daylight_limit.yaml", + { + "adaptive_switch": "switch.adaptive_lighting_living_room", + "illuminance_sensor": "sensor.living_room_illuminance", + }, + ) _, adaptive_switch = await setup_switch( hass, {CONF_NAME: "Living Room", CONF_MAX_BRIGHTNESS: 80}, @@ -273,13 +534,21 @@ async def test_lux_profile_executes_hysteresis(hass: HomeAssistant) -> None: async def test_lux_profile_executes_unknown_recovery_at_startup( hass: HomeAssistant, + published_automation, ) -> None: """Catch a startup hang or failure to recover from an unknown sensor.""" _prepare_hass_startup(hass) summary = ( "Reduce daytime brightness when an illuminance sensor detects strong daylight." ) - automation_config = _yaml_documents(summary)[0] + automation_config = published_automation( + summary, + "daylight_limit.yaml", + { + "adaptive_switch": "switch.adaptive_lighting_living_room", + "illuminance_sensor": "sensor.living_room_illuminance", + }, + ) _, adaptive_switch = await setup_switch( hass, {CONF_NAME: "Living Room", CONF_MAX_BRIGHTNESS: 80}, @@ -302,6 +571,44 @@ async def test_lux_profile_executes_unknown_recovery_at_startup( assert adaptive_switch._sun_light_settings.max_brightness == 30 +@pytest.mark.parametrize(("high_lux", "low_lux"), [(400, 250), (200, 300), (200, 200)]) +async def test_daylight_blueprint_custom_inputs( + hass: HomeAssistant, + tmp_path: Path, + high_lux: int, + low_lux: int, +) -> None: + """Use selected entities and limits; invalid threshold order must do nothing.""" + config = _blueprint_config( + hass, + tmp_path, + "daylight_limit.yaml", + { + "adaptive_switch": "switch.adaptive_lighting_office", + "illuminance_sensor": "sensor.office_illuminance", + "high_lux": high_lux, + "low_lux": low_lux, + "daylight_maximum": 20, + "normal_maximum": 70, + }, + "Custom daylight", + ) + _, adaptive_switch = await setup_switch( + hass, + {CONF_NAME: "Office", CONF_MAX_BRIGHTNESS: 80}, + ) + hass.states.async_set("sensor.office_illuminance", "300") + await _setup_automation(hass, config) + assert hass.states.get("automation.custom_daylight") is not None + valid_thresholds = high_lux > low_lux + for lux, expected in [(500, 20), (300, 20), (100, 70)]: + hass.states.async_set("sensor.office_illuminance", str(lux)) + await hass.async_block_till_done() + assert adaptive_switch._sun_light_settings.max_brightness == ( + expected if valid_thresholds else 80 + ) + + async def test_hue_script_applies_current_values_to_fresh_profile_targets( hass: HomeAssistant, ) -> None: @@ -574,13 +881,24 @@ async def test_autoreset_manual_control_uses_one_renewable_timer( async def test_sleep_toggle_uses_fresh_profile_entity_ids( hass: HomeAssistant, + published_automation, ) -> None: """Execute state triggers against fresh child entity IDs.""" summary = ( 'Toggle multiple Adaptive Lighting switches to "sleep mode" using an ' "input_boolean.sleep_mode." ) - automation_config = _yaml_documents(summary)[0] + automation_config = published_automation( + summary, + "sleep_mode.yaml", + { + "sleep_helper": "input_boolean.sleep_mode", + "sleep_switches": [ + "switch.adaptive_lighting_living_room_sleep_mode", + "switch.adaptive_lighting_bedroom_sleep_mode", + ], + }, + ) assert await async_setup_component( hass, "input_boolean", @@ -623,6 +941,7 @@ async def test_sleep_toggle_uses_fresh_profile_entity_ids( async def test_sleep_toggle_applies_restored_state_at_startup( hass: HomeAssistant, + published_automation, ) -> None: """Verify startup applies the input boolean's restored state.""" _prepare_hass_startup(hass) @@ -630,13 +949,24 @@ async def test_sleep_toggle_applies_restored_state_at_startup( 'Toggle multiple Adaptive Lighting switches to "sleep mode" using an ' "input_boolean.sleep_mode." ) - automation_config = _yaml_documents(summary)[0] + automation_config = published_automation( + summary, + "sleep_mode.yaml", + { + "sleep_helper": "input_boolean.sleep_mode", + "sleep_switches": [ + "switch.adaptive_lighting_living_room_sleep_mode", + "switch.adaptive_lighting_bedroom_sleep_mode", + ], + }, + ) assert await async_setup_component( hass, "input_boolean", {"input_boolean": {"sleep_mode": {}}}, ) await setup_switch(hass, {CONF_NAME: "Living Room"}) + await setup_switch(hass, {CONF_NAME: "Bedroom"}) await hass.services.async_call( "input_boolean", SERVICE_TURN_ON, diff --git a/tests/test_switch.py b/tests/test_switch.py index 733b1ef3..cfebc4f6 100644 --- a/tests/test_switch.py +++ b/tests/test_switch.py @@ -1891,9 +1891,10 @@ async def test_shared_profiles_track_manual_brightness( hass.states.get(ENTITY_LIGHT_1).attributes[ATTR_BRIGHTNESS] == expected_brightness ) - assert [event.data[SWITCH_DOMAIN] for event in events] == [ + # Independent profiles may publish their events in either order. + assert sorted(event.data[SWITCH_DOMAIN] for event in events) == sorted( profiles[name].entity_id for name in event_profiles - ] + ) assert all(event.context == context for event in events) assert all( event.data[CONF_MANUAL_CONTROL] == LightControlAttributes.BRIGHTNESS From 11bd5cf2aa3bcd2ec60fe77396cda48da56e697b Mon Sep 17 00:00:00 2001 From: Bas Nijholt Date: Sun, 6 Sep 2026 20:46:14 +0200 Subject: [PATCH 11/26] Pause brightness at minimum using existing manual-control resets (#1578) --- README.md | 106 ++++++- .../automation/manual_control_at_minimum.yaml | 123 ++++++++ docs/automation-examples.md | 106 ++++++- tests/test_automation_examples.py | 298 ++++++++++++++++++ 4 files changed, 617 insertions(+), 16 deletions(-) create mode 100644 blueprints/automation/manual_control_at_minimum.yaml diff --git a/README.md b/README.md index af016c54..1ee91993 100644 --- a/README.md +++ b/README.md @@ -272,16 +272,17 @@ Replace every entity ID below with the IDs from your Home Assistant instance. Fr Blocks that begin with `- alias` are entries for `automations.yaml`. Blocks with a top-level `script:` or `adaptive_lighting:` key are complete `configuration.yaml` examples. If your configuration uses `script: !include scripts.yaml`, omit that outer key and place its contents in `scripts.yaml`. -Four examples also have blueprints with selectors, so you can configure them without editing YAML: +Five examples also have blueprints with selectors, so you can configure them without editing YAML: -| Blueprint | Purpose | -| --- | --- | -| [Sleep mode](https://github.com/basnijholt/adaptive-lighting/blob/main/blueprints/automation/sleep_mode.yaml) | Synchronize several profiles with one sleep-mode helper. | -| [Minimum brightness](https://github.com/basnijholt/adaptive-lighting/blob/main/blueprints/automation/turn_off_at_minimum.yaml) | Turn one light off when its target crosses down to the minimum. | -| [Schedule profile](https://github.com/basnijholt/adaptive-lighting/blob/main/blueprints/automation/schedule_profile.yaml) | Apply brightness and color temperature from Schedule helper blocks. | -| [Daylight limit](https://github.com/basnijholt/adaptive-lighting/blob/main/blueprints/automation/daylight_limit.yaml) | Lower maximum brightness in strong daylight. | +| Blueprint | Purpose | Import | +| --- | --- | --- | +| [Sleep mode](https://github.com/basnijholt/adaptive-lighting/blob/main/blueprints/automation/sleep_mode.yaml) | Synchronize several profiles with one sleep-mode helper. | [![Import blueprint](https://my.home-assistant.io/badges/blueprint_import.svg)](https://my.home-assistant.io/redirect/blueprint_import/?blueprint_url=https%3A%2F%2Fgithub.com%2Fbasnijholt%2Fadaptive-lighting%2Fblob%2Fmain%2Fblueprints%2Fautomation%2Fsleep_mode.yaml) | +| [Minimum brightness](https://github.com/basnijholt/adaptive-lighting/blob/main/blueprints/automation/turn_off_at_minimum.yaml) | Turn one light off when its target crosses down to the minimum. | [![Import blueprint](https://my.home-assistant.io/badges/blueprint_import.svg)](https://my.home-assistant.io/redirect/blueprint_import/?blueprint_url=https%3A%2F%2Fgithub.com%2Fbasnijholt%2Fadaptive-lighting%2Fblob%2Fmain%2Fblueprints%2Fautomation%2Fturn_off_at_minimum.yaml) | +| [Pause at minimum](https://github.com/basnijholt/adaptive-lighting/blob/main/blueprints/automation/manual_control_at_minimum.yaml) | Pause brightness through manual control, using its existing reset behavior. | [![Import blueprint](https://my.home-assistant.io/badges/blueprint_import.svg)](https://my.home-assistant.io/redirect/blueprint_import/?blueprint_url=https%3A%2F%2Fgithub.com%2Fbasnijholt%2Fadaptive-lighting%2Fblob%2Fmain%2Fblueprints%2Fautomation%2Fmanual_control_at_minimum.yaml) | +| [Schedule profile](https://github.com/basnijholt/adaptive-lighting/blob/main/blueprints/automation/schedule_profile.yaml) | Apply brightness and color temperature from Schedule helper blocks. | [![Import blueprint](https://my.home-assistant.io/badges/blueprint_import.svg)](https://my.home-assistant.io/redirect/blueprint_import/?blueprint_url=https%3A%2F%2Fgithub.com%2Fbasnijholt%2Fadaptive-lighting%2Fblob%2Fmain%2Fblueprints%2Fautomation%2Fschedule_profile.yaml) | +| [Daylight limit](https://github.com/basnijholt/adaptive-lighting/blob/main/blueprints/automation/daylight_limit.yaml) | Lower maximum brightness in strong daylight. | [![Import blueprint](https://my.home-assistant.io/badges/blueprint_import.svg)](https://my.home-assistant.io/redirect/blueprint_import/?blueprint_url=https%3A%2F%2Fgithub.com%2Fbasnijholt%2Fadaptive-lighting%2Fblob%2Fmain%2Fblueprints%2Fautomation%2Fdaylight_limit.yaml) | -Copy a blueprint's link into **Settings → Automations & scenes → Blueprints → Import Blueprint**, then create an automation from it. Read the matching example below for setup and behavior. Each blueprint is tested through Home Assistant alongside its YAML example. The built-in manual-control timeout needs no automation; the scripts below remain useful as actions in your own automations. +Click a blueprint's import badge, confirm the import in Home Assistant, then create an automation and select your entities. You can also copy its source link into **Settings → Automations & scenes → Blueprints → Import Blueprint**. Read the matching example below for setup and behavior. Each blueprint is tested through Home Assistant alongside its YAML example. The built-in manual-control timeout needs no automation; the scripts below remain useful as actions in your own automations. `change_switch_settings` updates a profile while its main switch is off, but lights are adapted only while that switch is on. It preserves manual-control flags, so manually controlled lights remain paused. @@ -379,6 +380,95 @@ This runs once when a valid target crosses down into the minimum range. It skips
+
+Pause brightness at the minimum using manual control. + +Use the [blueprint](https://github.com/basnijholt/adaptive-lighting/blob/main/blueprints/automation/manual_control_at_minimum.yaml) to mark an individual light's brightness as manually controlled when the calculated target reaches its minimum. The light stays on and the adaptation switches stay enabled. Set `take_over_control_mode: pause_changed` on the profile to keep adapting color; the default `pause_all` pauses both attributes. + +Select the profile, its adapt-brightness switch, and a light managed by it. Match the minimum percentage to the profile's `min_brightness`. This YAML example assumes `min_brightness: 1`; change `minimum_pct` and the entity IDs to match your setup. + +```yaml +- alias: "Adaptive lighting: pause brightness at minimum" + mode: single + variables: + minimum_pct: 1 + minimum: "{{ (minimum_pct * 255 / 100) | round(0) }}" + triggers: + - trigger: state + entity_id: switch.adaptive_lighting_living_room + attribute: brightness_pct + conditions: + - condition: state + entity_id: + - switch.adaptive_lighting_living_room + - switch.adaptive_lighting_living_room_adapt_brightness + state: "on" + - condition: template + value_template: >- + {% set before = trigger.from_state.attributes.get('brightness_pct') + if trigger.from_state else none %} + {% set after = trigger.to_state.attributes.get('brightness_pct') + if trigger.to_state else none %} + {{ is_number(before) and is_number(after) + and (before | float * 255 / 100) | round(0) > minimum + and (after | float * 255 / 100) | round(0) <= minimum }} + - condition: state + entity_id: light.living_room + state: "on" + - condition: template + value_template: >- + {{ 'light.living_room' not in + (state_attr('switch.adaptive_lighting_living_room', 'manual_control_brightness') or []) }} + actions: + - variables: + light_session: "{{ states.light.living_room.last_changed.isoformat() }}" + profile_session: "{{ states.switch.adaptive_lighting_living_room.last_changed.isoformat() }}" + brightness_session: "{{ states.switch.adaptive_lighting_living_room_adapt_brightness.last_changed.isoformat() }}" + - wait_template: >- + {% set target = state_attr('switch.adaptive_lighting_living_room', 'brightness_pct') %} + {{ not is_state('light.living_room', 'on') + or not is_state('switch.adaptive_lighting_living_room', 'on') + or not is_state('switch.adaptive_lighting_living_room_adapt_brightness', 'on') + or states.light.living_room.last_changed.isoformat() != light_session + or states.switch.adaptive_lighting_living_room.last_changed.isoformat() != profile_session + or states.switch.adaptive_lighting_living_room_adapt_brightness.last_changed.isoformat() != brightness_session + or not is_number(target) or (target | float * 255 / 100) | round(0) > minimum + or 'light.living_room' in + (state_attr('switch.adaptive_lighting_living_room', 'manual_control_brightness') or []) + or (state_attr('light.living_room', 'brightness') | float(256)) <= minimum }} + timeout: "00:05:00" + continue_on_timeout: false + - condition: template + value_template: >- + {% set target = state_attr('switch.adaptive_lighting_living_room', 'brightness_pct') %} + {{ is_state('light.living_room', 'on') + and is_state('switch.adaptive_lighting_living_room', 'on') + and is_state('switch.adaptive_lighting_living_room_adapt_brightness', 'on') + and states.light.living_room.last_changed.isoformat() == light_session + and states.switch.adaptive_lighting_living_room.last_changed.isoformat() == profile_session + and states.switch.adaptive_lighting_living_room_adapt_brightness.last_changed.isoformat() == brightness_session + and is_number(target) and (target | float * 255 / 100) | round(0) <= minimum + and (state_attr('light.living_room', 'brightness') | float(256)) <= minimum + and 'light.living_room' not in + (state_attr('switch.adaptive_lighting_living_room', 'manual_control_brightness') or []) }} + - action: adaptive_lighting.set_manual_control + data: + entity_id: switch.adaptive_lighting_living_room + lights: light.living_room + manual_control: >- + {{ true if 'light.living_room' in + (state_attr('switch.adaptive_lighting_living_room', 'manual_control_color') or []) + else 'brightness' }} +``` + +The comparison uses the rounded 0–255 target, so it does not depend on sampling an exact floating-point minimum. It waits up to five minutes for the light to report that minimum before marking manual control, so the final dimming command can complete. Reported brightness does not prove physical fade completion. If the light, profile, or adapt-brightness switch is toggled, the target rises, brightness is marked manually controlled elsewhere, or brightness never reaches the minimum, the attempt is abandoned. Lights that cannot report the configured minimum will not be paused. Existing manual color flags are preserved, and lights whose brightness is already manually controlled are left alone. Manual-control state is shared for lights managed by multiple profiles, so their existing takeover policies still apply. + +The usual resets apply: turning the light off, the configured `autoreset_control_seconds` timeout, clearing manual control through its service, and existing profile/sleep-switch reset behavior. After a reset, normal adaptation can increase brightness again. This runs once per downward crossing; resetting while the target remains at its minimum does not immediately mark the light again. Startup at the minimum is not a crossing either. + +This pauses further dimming as well as brightening. To pause brightness immediately after a brightness change made through Home Assistant, use `take_over_control_mode: pause_changed` with `take_over_control: true`; that needs no additional automation. + +
+
Set sunrise and sunset from an alarm. diff --git a/blueprints/automation/manual_control_at_minimum.yaml b/blueprints/automation/manual_control_at_minimum.yaml new file mode 100644 index 00000000..95cb5f79 --- /dev/null +++ b/blueprints/automation/manual_control_at_minimum.yaml @@ -0,0 +1,123 @@ +blueprint: + name: "Adaptive Lighting: pause brightness at minimum" + description: >- + Mark one light's brightness as manually controlled when its calculated + brightness target crosses down to the configured minimum. Set the profile's + take_over_control_mode to pause_changed to keep adapting color; pause_all + pauses both. Existing manual color control is preserved. Uses the normal + manual-control resets, including turning the light off and any configured + autoreset_control_seconds timeout. Runs once per downward crossing, so a + reset while the target remains low does not immediately pause it again. + Waits up to five minutes for reported brightness to reach the rounded + 0–255 minimum before pausing. This does not prove physical fade completion. Does not + change power or adaptation switches. Select an individual light managed by + the profile. Shared profiles retain their usual manual-control behavior. + domain: automation + homeassistant: + min_version: "2025.9.0" + input: + adaptive_switch: + name: Adaptive Lighting profile + description: Select the main Adaptive Lighting switch, not a sleep or adaptation switch. + selector: + entity: + filter: + domain: switch + integration: adaptive_lighting + brightness_switch: + name: Adapt brightness switch + description: Select the adapt brightness switch belonging to the same profile. + selector: + entity: + filter: + domain: switch + integration: adaptive_lighting + light_entity: + name: Light + description: Select one light managed by this profile. Create an automation for each light. + selector: + entity: + filter: + domain: light + minimum_pct: + name: Minimum brightness + description: Match the profile's min_brightness setting. Update this if that setting changes. + default: 1 + selector: + number: + min: 1 + max: 100 + step: 1 + unit_of_measurement: "%" + mode: box + +mode: single +variables: + adaptive_switch: !input adaptive_switch + light_entity: !input light_entity + minimum_pct: !input minimum_pct + minimum: "{{ (minimum_pct * 255 / 100) | round(0) }}" + brightness_switch: !input brightness_switch +triggers: + - trigger: state + entity_id: !input adaptive_switch + attribute: brightness_pct +conditions: + - condition: state + entity_id: !input adaptive_switch + state: "on" + - condition: state + entity_id: !input brightness_switch + state: "on" + - condition: template + value_template: >- + {% set before = trigger.from_state.attributes.get('brightness_pct') + if trigger.from_state else none %} + {% set after = trigger.to_state.attributes.get('brightness_pct') + if trigger.to_state else none %} + {{ is_number(before) and is_number(after) + and (before | float * 255 / 100) | round(0) > minimum + and (after | float * 255 / 100) | round(0) <= minimum }} + - condition: state + entity_id: !input light_entity + state: "on" + - condition: template + value_template: >- + {{ light_entity not in (state_attr(adaptive_switch, 'manual_control_brightness') or []) }} +actions: + - variables: + light_session: "{{ states[light_entity].last_changed.isoformat() }}" + profile_session: "{{ states[adaptive_switch].last_changed.isoformat() }}" + brightness_session: "{{ states[brightness_switch].last_changed.isoformat() }}" + - wait_template: >- + {% set target = state_attr(adaptive_switch, 'brightness_pct') %} + {{ not is_state(light_entity, 'on') or not is_state(adaptive_switch, 'on') + or not is_state(brightness_switch, 'on') + or states[light_entity].last_changed.isoformat() != light_session + or states[adaptive_switch].last_changed.isoformat() != profile_session + or states[brightness_switch].last_changed.isoformat() != brightness_session + or not is_number(target) or (target | float * 255 / 100) | round(0) > minimum + or light_entity in (state_attr(adaptive_switch, 'manual_control_brightness') or []) + or (state_attr(light_entity, 'brightness') | float(256)) <= minimum }} + timeout: "00:05:00" + continue_on_timeout: false + - condition: template + value_template: >- + {% set target = state_attr(adaptive_switch, 'brightness_pct') %} + {{ is_state(light_entity, 'on') and is_state(adaptive_switch, 'on') + and is_state(brightness_switch, 'on') + and states[light_entity].last_changed.isoformat() == light_session + and states[adaptive_switch].last_changed.isoformat() == profile_session + and states[brightness_switch].last_changed.isoformat() == brightness_session + and is_number(target) and (target | float * 255 / 100) | round(0) <= minimum + and (state_attr(light_entity, 'brightness') | float(256)) <= minimum + and light_entity not in + (state_attr(adaptive_switch, 'manual_control_brightness') or []) }} + - action: adaptive_lighting.set_manual_control + data: + entity_id: !input adaptive_switch + lights: !input light_entity + manual_control: >- + {{ true if light_entity in + (state_attr(adaptive_switch, 'manual_control_color') or []) + else 'brightness' }} diff --git a/docs/automation-examples.md b/docs/automation-examples.md index 5686c5d7..ec5c2831 100644 --- a/docs/automation-examples.md +++ b/docs/automation-examples.md @@ -16,16 +16,17 @@ Replace every entity ID below with the IDs from your Home Assistant instance. Fr Blocks that begin with `- alias` are entries for `automations.yaml`. Blocks with a top-level `script:` or `adaptive_lighting:` key are complete `configuration.yaml` examples. If your configuration uses `script: !include scripts.yaml`, omit that outer key and place its contents in `scripts.yaml`. -Four examples also have blueprints with selectors, so you can configure them without editing YAML: +Five examples also have blueprints with selectors, so you can configure them without editing YAML: -| Blueprint | Purpose | -| --- | --- | -| [Sleep mode](https://github.com/basnijholt/adaptive-lighting/blob/main/blueprints/automation/sleep_mode.yaml) | Synchronize several profiles with one sleep-mode helper. | -| [Minimum brightness](https://github.com/basnijholt/adaptive-lighting/blob/main/blueprints/automation/turn_off_at_minimum.yaml) | Turn one light off when its target crosses down to the minimum. | -| [Schedule profile](https://github.com/basnijholt/adaptive-lighting/blob/main/blueprints/automation/schedule_profile.yaml) | Apply brightness and color temperature from Schedule helper blocks. | -| [Daylight limit](https://github.com/basnijholt/adaptive-lighting/blob/main/blueprints/automation/daylight_limit.yaml) | Lower maximum brightness in strong daylight. | +| Blueprint | Purpose | Import | +| --- | --- | --- | +| [Sleep mode](https://github.com/basnijholt/adaptive-lighting/blob/main/blueprints/automation/sleep_mode.yaml) | Synchronize several profiles with one sleep-mode helper. | [![Import blueprint](https://my.home-assistant.io/badges/blueprint_import.svg)](https://my.home-assistant.io/redirect/blueprint_import/?blueprint_url=https%3A%2F%2Fgithub.com%2Fbasnijholt%2Fadaptive-lighting%2Fblob%2Fmain%2Fblueprints%2Fautomation%2Fsleep_mode.yaml) | +| [Minimum brightness](https://github.com/basnijholt/adaptive-lighting/blob/main/blueprints/automation/turn_off_at_minimum.yaml) | Turn one light off when its target crosses down to the minimum. | [![Import blueprint](https://my.home-assistant.io/badges/blueprint_import.svg)](https://my.home-assistant.io/redirect/blueprint_import/?blueprint_url=https%3A%2F%2Fgithub.com%2Fbasnijholt%2Fadaptive-lighting%2Fblob%2Fmain%2Fblueprints%2Fautomation%2Fturn_off_at_minimum.yaml) | +| [Pause at minimum](https://github.com/basnijholt/adaptive-lighting/blob/main/blueprints/automation/manual_control_at_minimum.yaml) | Pause brightness through manual control, using its existing reset behavior. | [![Import blueprint](https://my.home-assistant.io/badges/blueprint_import.svg)](https://my.home-assistant.io/redirect/blueprint_import/?blueprint_url=https%3A%2F%2Fgithub.com%2Fbasnijholt%2Fadaptive-lighting%2Fblob%2Fmain%2Fblueprints%2Fautomation%2Fmanual_control_at_minimum.yaml) | +| [Schedule profile](https://github.com/basnijholt/adaptive-lighting/blob/main/blueprints/automation/schedule_profile.yaml) | Apply brightness and color temperature from Schedule helper blocks. | [![Import blueprint](https://my.home-assistant.io/badges/blueprint_import.svg)](https://my.home-assistant.io/redirect/blueprint_import/?blueprint_url=https%3A%2F%2Fgithub.com%2Fbasnijholt%2Fadaptive-lighting%2Fblob%2Fmain%2Fblueprints%2Fautomation%2Fschedule_profile.yaml) | +| [Daylight limit](https://github.com/basnijholt/adaptive-lighting/blob/main/blueprints/automation/daylight_limit.yaml) | Lower maximum brightness in strong daylight. | [![Import blueprint](https://my.home-assistant.io/badges/blueprint_import.svg)](https://my.home-assistant.io/redirect/blueprint_import/?blueprint_url=https%3A%2F%2Fgithub.com%2Fbasnijholt%2Fadaptive-lighting%2Fblob%2Fmain%2Fblueprints%2Fautomation%2Fdaylight_limit.yaml) | -Copy a blueprint's link into **Settings → Automations & scenes → Blueprints → Import Blueprint**, then create an automation from it. Read the matching example below for setup and behavior. Each blueprint is tested through Home Assistant alongside its YAML example. The built-in manual-control timeout needs no automation; the scripts below remain useful as actions in your own automations. +Click a blueprint's import badge, confirm the import in Home Assistant, then create an automation and select your entities. You can also copy its source link into **Settings → Automations & scenes → Blueprints → Import Blueprint**. Read the matching example below for setup and behavior. Each blueprint is tested through Home Assistant alongside its YAML example. The built-in manual-control timeout needs no automation; the scripts below remain useful as actions in your own automations. `change_switch_settings` updates a profile while its main switch is off, but lights are adapted only while that switch is on. It preserves manual-control flags, so manually controlled lights remain paused. @@ -123,6 +124,95 @@ This runs once when a valid target crosses down into the minimum range. It skips
+
+Pause brightness at the minimum using manual control. + +Use the [blueprint](https://github.com/basnijholt/adaptive-lighting/blob/main/blueprints/automation/manual_control_at_minimum.yaml) to mark an individual light's brightness as manually controlled when the calculated target reaches its minimum. The light stays on and the adaptation switches stay enabled. Set `take_over_control_mode: pause_changed` on the profile to keep adapting color; the default `pause_all` pauses both attributes. + +Select the profile, its adapt-brightness switch, and a light managed by it. Match the minimum percentage to the profile's `min_brightness`. This YAML example assumes `min_brightness: 1`; change `minimum_pct` and the entity IDs to match your setup. + +```yaml +- alias: "Adaptive lighting: pause brightness at minimum" + mode: single + variables: + minimum_pct: 1 + minimum: "{{ (minimum_pct * 255 / 100) | round(0) }}" + triggers: + - trigger: state + entity_id: switch.adaptive_lighting_living_room + attribute: brightness_pct + conditions: + - condition: state + entity_id: + - switch.adaptive_lighting_living_room + - switch.adaptive_lighting_living_room_adapt_brightness + state: "on" + - condition: template + value_template: >- + {% set before = trigger.from_state.attributes.get('brightness_pct') + if trigger.from_state else none %} + {% set after = trigger.to_state.attributes.get('brightness_pct') + if trigger.to_state else none %} + {{ is_number(before) and is_number(after) + and (before | float * 255 / 100) | round(0) > minimum + and (after | float * 255 / 100) | round(0) <= minimum }} + - condition: state + entity_id: light.living_room + state: "on" + - condition: template + value_template: >- + {{ 'light.living_room' not in + (state_attr('switch.adaptive_lighting_living_room', 'manual_control_brightness') or []) }} + actions: + - variables: + light_session: "{{ states.light.living_room.last_changed.isoformat() }}" + profile_session: "{{ states.switch.adaptive_lighting_living_room.last_changed.isoformat() }}" + brightness_session: "{{ states.switch.adaptive_lighting_living_room_adapt_brightness.last_changed.isoformat() }}" + - wait_template: >- + {% set target = state_attr('switch.adaptive_lighting_living_room', 'brightness_pct') %} + {{ not is_state('light.living_room', 'on') + or not is_state('switch.adaptive_lighting_living_room', 'on') + or not is_state('switch.adaptive_lighting_living_room_adapt_brightness', 'on') + or states.light.living_room.last_changed.isoformat() != light_session + or states.switch.adaptive_lighting_living_room.last_changed.isoformat() != profile_session + or states.switch.adaptive_lighting_living_room_adapt_brightness.last_changed.isoformat() != brightness_session + or not is_number(target) or (target | float * 255 / 100) | round(0) > minimum + or 'light.living_room' in + (state_attr('switch.adaptive_lighting_living_room', 'manual_control_brightness') or []) + or (state_attr('light.living_room', 'brightness') | float(256)) <= minimum }} + timeout: "00:05:00" + continue_on_timeout: false + - condition: template + value_template: >- + {% set target = state_attr('switch.adaptive_lighting_living_room', 'brightness_pct') %} + {{ is_state('light.living_room', 'on') + and is_state('switch.adaptive_lighting_living_room', 'on') + and is_state('switch.adaptive_lighting_living_room_adapt_brightness', 'on') + and states.light.living_room.last_changed.isoformat() == light_session + and states.switch.adaptive_lighting_living_room.last_changed.isoformat() == profile_session + and states.switch.adaptive_lighting_living_room_adapt_brightness.last_changed.isoformat() == brightness_session + and is_number(target) and (target | float * 255 / 100) | round(0) <= minimum + and (state_attr('light.living_room', 'brightness') | float(256)) <= minimum + and 'light.living_room' not in + (state_attr('switch.adaptive_lighting_living_room', 'manual_control_brightness') or []) }} + - action: adaptive_lighting.set_manual_control + data: + entity_id: switch.adaptive_lighting_living_room + lights: light.living_room + manual_control: >- + {{ true if 'light.living_room' in + (state_attr('switch.adaptive_lighting_living_room', 'manual_control_color') or []) + else 'brightness' }} +``` + +The comparison uses the rounded 0–255 target, so it does not depend on sampling an exact floating-point minimum. It waits up to five minutes for the light to report that minimum before marking manual control, so the final dimming command can complete. Reported brightness does not prove physical fade completion. If the light, profile, or adapt-brightness switch is toggled, the target rises, brightness is marked manually controlled elsewhere, or brightness never reaches the minimum, the attempt is abandoned. Lights that cannot report the configured minimum will not be paused. Existing manual color flags are preserved, and lights whose brightness is already manually controlled are left alone. Manual-control state is shared for lights managed by multiple profiles, so their existing takeover policies still apply. + +The usual resets apply: turning the light off, the configured `autoreset_control_seconds` timeout, clearing manual control through its service, and existing profile/sleep-switch reset behavior. After a reset, normal adaptation can increase brightness again. This runs once per downward crossing; resetting while the target remains at its minimum does not immediately mark the light again. Startup at the minimum is not a crossing either. + +This pauses further dimming as well as brightening. To pause brightness immediately after a brightness change made through Home Assistant, use `take_over_control_mode: pause_changed` with `take_over_control: true`; that needs no additional automation. + +
+
Set sunrise and sunset from an alarm. diff --git a/tests/test_automation_examples.py b/tests/test_automation_examples.py index d0dc8e3e..b500f41e 100644 --- a/tests/test_automation_examples.py +++ b/tests/test_automation_examples.py @@ -17,6 +17,7 @@ from homeassistant.components.adaptive_lighting.adaptation_utils import ( LightControlAttributes, ) from homeassistant.components.adaptive_lighting.const import ( + CONF_AUTORESET_CONTROL, CONF_BRIGHTNESS_MODE, CONF_BRIGHTNESS_MODE_TIME_DARK, CONF_BRIGHTNESS_MODE_TIME_LIGHT, @@ -32,6 +33,7 @@ from homeassistant.components.adaptive_lighting.const import ( CONF_SLEEP_RGB_OR_COLOR_TEMP, CONF_SUNRISE_TIME, CONF_SUNSET_TIME, + CONF_TAKE_OVER_CONTROL_MODE, CONF_TRANSITION, DOMAIN, ) @@ -379,6 +381,302 @@ async def test_minimum_brightness_ignores_missing_previous_target( assert hass.states.get("light.living_room").state == STATE_ON +@pytest.mark.parametrize("previous_manual", [None, "color", "brightness"]) +@patch( + "homeassistant.components.adaptive_lighting.color_and_brightness.utcnow", + new=dt_util.utcnow, +) +async def test_minimum_manual_control_lifecycle( + hass: HomeAssistant, + freezer, + published_automation, + previous_manual: str | None, +) -> None: + """Pause at the calculated floor, preserve other flags, and reset on off/on.""" + freezer.move_to(datetime(2026, 9, 6, 18, 58, tzinfo=dt_util.DEFAULT_TIME_ZONE)) + config = published_automation( + "Pause brightness at the minimum using manual control.", + "manual_control_at_minimum.yaml", + { + "adaptive_switch": "switch.adaptive_lighting_living_room", + "brightness_switch": "switch.adaptive_lighting_living_room_adapt_brightness", + "light_entity": "light.living_room", + }, + ) + await _setup_template_lights(hass, ["Living Room"]) + await hass.services.async_call( + LIGHT_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: "light.living_room", ATTR_BRIGHTNESS: 77}, + blocking=True, + ) + _, profile = await setup_switch( + hass, + { + CONF_NAME: "Living Room", + CONF_LIGHTS: ["light.living_room"], + CONF_MIN_BRIGHTNESS: 1, + CONF_MAX_BRIGHTNESS: 100, + CONF_MIN_COLOR_TEMP: 3000, + CONF_MAX_COLOR_TEMP: 3000, + CONF_BRIGHTNESS_MODE: "linear", + CONF_BRIGHTNESS_MODE_TIME_DARK: timedelta(hours=1), + CONF_BRIGHTNESS_MODE_TIME_LIGHT: timedelta(hours=1), + CONF_SUNRISE_TIME: "06:00:00", + CONF_SUNSET_TIME: "18:00:00", + CONF_TRANSITION: 0, + CONF_INITIAL_TRANSITION: 0, + CONF_TAKE_OVER_CONTROL_MODE: "pause_changed", + }, + ) + if previous_manual: + await hass.services.async_call( + DOMAIN, + "set_manual_control", + {ATTR_ENTITY_ID: profile.entity_id, "manual_control": previous_manual}, + blocking=True, + ) + await _setup_automation(hass, config) + manual_calls = [] + + @callback + def record_manual_call(event: Event) -> None: + if ( + event.data["domain"] == DOMAIN + and event.data["service"] == "set_manual_control" + ): + manual_calls.append(event.data["service_data"]) + + hass.bus.async_listen(EVENT_CALL_SERVICE, record_manual_call) + freezer.move_to(datetime(2026, 9, 6, 18, 59, 50, tzinfo=dt_util.DEFAULT_TIME_ZONE)) + await profile._async_update_at_interval_action() + await hass.async_block_till_done() + flags = profile.manager.get_manual_control_attributes("light.living_room") + assert LightControlAttributes.BRIGHTNESS in flags + assert (LightControlAttributes.COLOR in flags) is (previous_manual == "color") + assert len(manual_calls) == (0 if previous_manual == "brightness" else 1) + paused_brightness = hass.states.get("light.living_room").attributes[ATTR_BRIGHTNESS] + assert profile.is_on + assert profile.adapt_brightness_switch.is_on + if previous_manual != "brightness": + assert paused_brightness == 3 + + freezer.move_to(datetime(2026, 9, 6, 19, 1, tzinfo=dt_util.DEFAULT_TIME_ZONE)) + await profile._async_update_at_interval_action() + await hass.async_block_till_done() + assert len(manual_calls) == (0 if previous_manual == "brightness" else 1) + await hass.services.async_call( + DOMAIN, + "change_switch_settings", + { + ATTR_ENTITY_ID: profile.entity_id, + CONF_MIN_BRIGHTNESS: 100, + CONF_MAX_BRIGHTNESS: 100, + CONF_MIN_COLOR_TEMP: 5000, + CONF_MAX_COLOR_TEMP: 5000, + }, + blocking=True, + ) + await hass.async_block_till_done() + state = hass.states.get("light.living_room") + assert state.state == STATE_ON + assert state.attributes[ATTR_BRIGHTNESS] == paused_brightness + assert state.attributes[ATTR_COLOR_TEMP_KELVIN] == pytest.approx( + 3000 if previous_manual == "color" else 5000, + abs=5, + ) + await hass.services.async_call( + LIGHT_DOMAIN, + SERVICE_TURN_OFF, + {ATTR_ENTITY_ID: "light.living_room"}, + blocking=True, + ) + await hass.async_block_till_done() + assert not profile.manager.get_manual_control_attributes("light.living_room") + await hass.services.async_call( + LIGHT_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: "light.living_room"}, + blocking=True, + ) + await hass.async_block_till_done() + assert hass.states.get("light.living_room").attributes[ATTR_BRIGHTNESS] == 255 + + # Another crossing can pause again, but clearing it at the floor must stick. + await hass.services.async_call( + DOMAIN, + "change_switch_settings", + { + ATTR_ENTITY_ID: profile.entity_id, + CONF_MIN_BRIGHTNESS: 1, + CONF_MAX_BRIGHTNESS: 1, + }, + blocking=True, + ) + await hass.async_block_till_done() + assert profile.manager.get_manual_control_attributes("light.living_room") + await hass.services.async_call( + DOMAIN, + "set_manual_control", + {ATTR_ENTITY_ID: profile.entity_id, "manual_control": False}, + blocking=True, + ) + await profile._async_update_at_interval_action() + await hass.async_block_till_done() + assert not profile.manager.get_manual_control_attributes("light.living_room") + + if previous_manual is None: + await hass.services.async_call( + DOMAIN, + "change_switch_settings", + { + ATTR_ENTITY_ID: profile.entity_id, + CONF_MIN_BRIGHTNESS: 50, + CONF_MAX_BRIGHTNESS: 50, + CONF_AUTORESET_CONTROL: 1, + }, + blocking=True, + ) + await hass.services.async_call( + DOMAIN, + "change_switch_settings", + { + ATTR_ENTITY_ID: profile.entity_id, + CONF_MIN_BRIGHTNESS: 1, + CONF_MAX_BRIGHTNESS: 1, + }, + blocking=True, + ) + await hass.async_block_till_done() + assert profile.manager.get_manual_control_attributes("light.living_room") + cleared, remove_listener = _state_waiter( + hass, + profile.entity_id, + lambda state: state.attributes.get("manual_control_brightness") == [], + ) + freezer.tick(timedelta(seconds=1)) + async_fire_time_changed(hass, dt_util.utcnow()) + await asyncio.wait_for(cleared, timeout=2) + remove_listener() + await hass.async_block_till_done() + assert not profile.manager.get_manual_control_attributes("light.living_room") + + +@pytest.mark.parametrize( + "abort_entity", + [ + "light.living_room", + "switch.adaptive_lighting_living_room", + "switch.adaptive_lighting_living_room_adapt_brightness", + ], +) +async def test_minimum_manual_control_aborts_when_disabled( + hass: HomeAssistant, + published_automation, + abort_entity: str, +) -> None: + """Abandon a pending wait immediately when the light or profile is disabled.""" + config = published_automation( + "Pause brightness at the minimum using manual control.", + "manual_control_at_minimum.yaml", + { + "adaptive_switch": "switch.adaptive_lighting_living_room", + "brightness_switch": "switch.adaptive_lighting_living_room_adapt_brightness", + "light_entity": "light.living_room", + }, + ) + await _setup_template_lights(hass, ["Living Room"]) + await hass.services.async_call( + LIGHT_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: "light.living_room", ATTR_BRIGHTNESS: 128}, + blocking=True, + ) + _, profile = await setup_switch( + hass, + { + CONF_NAME: "Living Room", + CONF_LIGHTS: ["light.living_room"], + CONF_MIN_BRIGHTNESS: 50, + CONF_MAX_BRIGHTNESS: 50, + CONF_INITIAL_TRANSITION: 0, + CONF_TRANSITION: 0, + CONF_TAKE_OVER_CONTROL_MODE: "pause_changed", + }, + ) + await _setup_automation(hass, config) + waiting, remove_listener = _state_waiter( + hass, + "automation.adaptive_lighting_pause_brightness_at_minimum", + lambda state: state.attributes.get("current") == 1, + ) + state = hass.states.get(profile.entity_id) + hass.states.async_set( + profile.entity_id, + STATE_ON, + {**state.attributes, "brightness_pct": 1}, + ) + await asyncio.wait_for(waiting, timeout=1) + remove_listener() + assert not profile.manager.get_manual_control_attributes("light.living_room") + stopped, remove_stopped = _state_waiter( + hass, + "automation.adaptive_lighting_pause_brightness_at_minimum", + lambda state: state.attributes.get("current") == 0, + ) + await hass.services.async_call( + abort_entity.split(".", maxsplit=1)[0], + SERVICE_TURN_OFF, + {ATTR_ENTITY_ID: abort_entity}, + blocking=True, + ) + try: + await asyncio.wait_for(stopped, timeout=1) + finally: + remove_stopped() + if stopped.cancelled(): + await hass.services.async_call( + automation.DOMAIN, + SERVICE_TURN_OFF, + { + ATTR_ENTITY_ID: "automation.adaptive_lighting_pause_brightness_at_minimum", + }, + blocking=True, + ) + await hass.async_block_till_done() + assert not profile.manager.get_manual_control_attributes("light.living_room") + assert ( + hass.states.get( + "automation.adaptive_lighting_pause_brightness_at_minimum", + ).attributes["current"] + == 0 + ) + + await hass.services.async_call( + abort_entity.split(".", maxsplit=1)[0], + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: abort_entity}, + blocking=True, + ) + await profile._async_update_at_interval_action() + await hass.async_block_till_done() + await hass.services.async_call( + DOMAIN, + "change_switch_settings", + { + ATTR_ENTITY_ID: profile.entity_id, + CONF_MIN_BRIGHTNESS: 1, + CONF_MAX_BRIGHTNESS: 1, + }, + blocking=True, + ) + await hass.async_block_till_done() + assert ( + profile.manager.get_manual_control_attributes("light.living_room") + == LightControlAttributes.BRIGHTNESS + ) + + async def test_schedule_profile_executes_blocks_and_restore( hass: HomeAssistant, published_automation, From 9e29a21197deeeba9a5eb96ad2da08e224fd7286 Mon Sep 17 00:00:00 2001 From: Alistair Galbraith Date: Sun, 6 Sep 2026 12:02:30 -0700 Subject: [PATCH 12/26] Add manual_control_on_external_turn_on option (#1490) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: add `adapt_only_on_ha_turn_on` to skip adapting externally turned-on lights When a light turns on from `off` via a source outside Home Assistant — a physical wall switch or a hub/manufacturer scene (e.g. Lutron) — and `detect_non_ha_changes` is enabled, Adaptive Lighting adapts the light on the resulting `off` → `on` event, overriding the brightness/color the external source just set. Disabling `detect_non_ha_changes` avoids this but also stops detection of manual changes to already-on lights; the two behaviors were coupled to a single flag. Add `adapt_only_on_ha_turn_on` (default `false`, requires `take_over_control`). When enabled, an `off` → `on` transition with no matching HA `light.turn_on` context is marked `manual_control` and left untouched, independent of `detect_non_ha_changes`, decoupling the two behaviors. The off→on guard reduces to the previous expression when the option is `false`, so existing configurations are unaffected. Includes a parametrized regression test, docs, and regenerated strings/services/README via scripts/update-generated-content. Refs #435 Co-Authored-By: Claude Opus 4.8 * Shorten generated turn-on option description * Document shared turn-on policy limitations * Name external turn-on policy after manual-control behavior * Clarify settings needed to adapt unmatched turn-ons --------- Co-authored-by: Claude Opus 4.8 Co-authored-by: Bas Nijholt --- README.md | 3 + custom_components/adaptive_lighting/const.py | 15 ++ .../adaptive_lighting/services.yaml | 6 + .../adaptive_lighting/strings.json | 5 + custom_components/adaptive_lighting/switch.py | 30 +++- .../adaptive_lighting/translations/en.json | 5 + docs/advanced/manual-control.md | 22 +++ docs/configuration.md | 1 + docs/troubleshooting.md | 2 + tests/test_config_flow.py | 6 + tests/test_switch.py | 147 ++++++++++++++++++ 11 files changed, 235 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 1ee91993..d15c5249 100644 --- a/README.md +++ b/README.md @@ -157,6 +157,7 @@ The YAML and frontend configuration methods support all of the options listed be | `autoreset_control_seconds` | Automatically reset the manual control after a number of seconds. Set to 0 to disable. ⏲️ | `0` | `int` 0-31536000 | | `only_once` | Adapt lights only when they are turned on (`true`) or keep adapting them (`false`). 🔄 | `False` | `bool` | | `adapt_only_on_bare_turn_on` | When turning lights on initially. If set to `true`, AL adapts only if `light.turn_on` is invoked without specifying color or brightness. ❌🌈 This e.g., prevents adaptation when activating a scene and marks the light as manually controlled. If `false`, AL adapts regardless of the presence of color or brightness in the initial `service_data`. Needs `take_over_control` enabled. 🕵️ | `False` | `bool` | +| `manual_control_on_external_turn_on` | Treat turn-ons without a matching Home Assistant `light.turn_on` context as manual control. Normal manual-control resets apply. Still allows `detect_non_ha_changes` for already-on lights. Needs `take_over_control` enabled. 🕵️ | `False` | `bool` | | `reset_manual_control_on_sleep_mode_change` | Reset manual control when the sleep mode switch is toggled. Set to `false` to preserve manual control across sleep mode changes. 😴 | `True` | `bool` | | `separate_turn_on_commands` | Use separate `light.turn_on` calls for color and brightness, needed for some light types. 🔀 | `False` | `bool` | | `send_split_delay` | Delay (ms) between `separate_turn_on_commands` for lights that don't support simultaneous brightness and color setting. ⏲️ | `0` | `int` 0-10000 | @@ -769,6 +770,8 @@ Addressing these issues will significantly improve your Home Assistant experienc In case lights are suddenly turning on by themselves, this is most likely due to the light incorrectly reporting an "on" state to Home Assistant, leading to an undesired Adaptive Lighting action. To prevent adapting in cases *where the state of the light is suddenly "on" and only adapt if there is an associated `light.turn_on` service call*, set `detect_non_ha_changes: false`. +To keep detecting manual changes to lights that are already on while leaving unmatched `off` to `on` state events unchanged, enable `manual_control_on_external_turn_on`. Matching uses the exact context of the most recently recorded `light.turn_on` call. Some integrations replace or omit that context, so Adaptive Lighting cannot distinguish every physical versus Home Assistant turn-on source. + #### :signal_strength: WiFi Networks Ensure your light bulbs have a strong WiFi connection. If the signal strength is less than -70dBm, the connection may be weak and prone to dropping messages. diff --git a/custom_components/adaptive_lighting/const.py b/custom_components/adaptive_lighting/const.py index 58b37734..7acf2781 100644 --- a/custom_components/adaptive_lighting/const.py +++ b/custom_components/adaptive_lighting/const.py @@ -100,6 +100,16 @@ DOCS[CONF_ADAPT_ONLY_ON_BARE_TURN_ON] = ( "Needs `take_over_control` enabled. 🕵️" ) +CONF_MANUAL_CONTROL_ON_EXTERNAL_TURN_ON, DEFAULT_MANUAL_CONTROL_ON_EXTERNAL_TURN_ON = ( + "manual_control_on_external_turn_on", + False, +) +DOCS[CONF_MANUAL_CONTROL_ON_EXTERNAL_TURN_ON] = ( + "Treat turn-ons without a matching Home Assistant `light.turn_on` context as " + "manual control. Normal manual-control resets apply. Still allows " + "`detect_non_ha_changes` for already-on lights. Needs `take_over_control` enabled. 🕵️" +) + CONF_PREFER_RGB_COLOR, DEFAULT_PREFER_RGB_COLOR = "prefer_rgb_color", False DOCS[CONF_PREFER_RGB_COLOR] = ( "Whether to prefer RGB color adjustment over " @@ -416,6 +426,11 @@ VALIDATION_TUPLES: list[tuple[str, Any, Any]] = [ ), (CONF_ONLY_ONCE, DEFAULT_ONLY_ONCE, bool), (CONF_ADAPT_ONLY_ON_BARE_TURN_ON, DEFAULT_ADAPT_ONLY_ON_BARE_TURN_ON, bool), + ( + CONF_MANUAL_CONTROL_ON_EXTERNAL_TURN_ON, + DEFAULT_MANUAL_CONTROL_ON_EXTERNAL_TURN_ON, + bool, + ), ( CONF_RESET_MANUAL_CONTROL_ON_SLEEP_MODE_CHANGE, DEFAULT_RESET_MANUAL_CONTROL_ON_SLEEP_MODE_CHANGE, diff --git a/custom_components/adaptive_lighting/services.yaml b/custom_components/adaptive_lighting/services.yaml index 2471e83a..23e8ceda 100644 --- a/custom_components/adaptive_lighting/services.yaml +++ b/custom_components/adaptive_lighting/services.yaml @@ -238,6 +238,12 @@ change_switch_settings: example: false selector: boolean: null + manual_control_on_external_turn_on: + description: Treat turn-ons without a matching Home Assistant `light.turn_on` context as manual control. Normal manual-control resets apply. Still allows `detect_non_ha_changes` for already-on lights. Needs `take_over_control` enabled. 🕵️ + required: false + example: false + selector: + boolean: null transition: description: Duration of transition when lights change, in seconds. 🕑 required: false diff --git a/custom_components/adaptive_lighting/strings.json b/custom_components/adaptive_lighting/strings.json index ff576a2b..6e07c69d 100644 --- a/custom_components/adaptive_lighting/strings.json +++ b/custom_components/adaptive_lighting/strings.json @@ -70,6 +70,7 @@ "autoreset_control_seconds": "autoreset_control_seconds", "only_once": "only_once: Adapt lights only when they are turned on (`true`) or keep adapting them (`false`). 🔄", "adapt_only_on_bare_turn_on": "adapt_only_on_bare_turn_on: When turning lights on initially. If set to `true`, AL adapts only if `light.turn_on` is invoked without specifying color or brightness. ❌🌈 This e.g., prevents adaptation when activating a scene and marks the light as manually controlled. If `false`, AL adapts regardless of the presence of color or brightness in the initial `service_data`. Needs `take_over_control` enabled. 🕵️", + "manual_control_on_external_turn_on": "manual_control_on_external_turn_on: Treat turn-ons without a matching Home Assistant `light.turn_on` context as manual control. Normal manual-control resets apply. Still allows `detect_non_ha_changes` for already-on lights. Needs `take_over_control` enabled. 🕵️", "reset_manual_control_on_sleep_mode_change": "reset_manual_control_on_sleep_mode_change: Reset manual control when the sleep mode switch is toggled. Set to `false` to preserve manual control across sleep mode changes. 😴", "separate_turn_on_commands": "separate_turn_on_commands: Use separate `light.turn_on` calls for color and brightness, needed for some light types. 🔀", "send_split_delay": "send_split_delay", @@ -270,6 +271,10 @@ "description": "Detects and halts adaptations for non-`light.turn_on` state changes. Needs `take_over_control` enabled. 🕵️ Caution: ⚠️ Some lights might falsely indicate an 'on' state, which could result in lights turning on unexpectedly. Note that this calls `homeassistant.update_entity` every `interval`! Disable this feature if you encounter such issues.", "name": "detect_non_ha_changes" }, + "manual_control_on_external_turn_on": { + "description": "Treat turn-ons without a matching Home Assistant `light.turn_on` context as manual control. Normal manual-control resets apply. Still allows `detect_non_ha_changes` for already-on lights. Needs `take_over_control` enabled. 🕵️", + "name": "manual_control_on_external_turn_on" + }, "transition": { "description": "Duration of transition when lights change, in seconds. 🕑", "name": "transition" diff --git a/custom_components/adaptive_lighting/switch.py b/custom_components/adaptive_lighting/switch.py index 0a340c6c..ab9273df 100644 --- a/custom_components/adaptive_lighting/switch.py +++ b/custom_components/adaptive_lighting/switch.py @@ -104,6 +104,7 @@ from .const import ( CONF_INTERVAL, CONF_LIGHTS, CONF_MANUAL_CONTROL, + CONF_MANUAL_CONTROL_ON_EXTERNAL_TURN_ON, CONF_MAX_BRIGHTNESS, CONF_MAX_COLOR_TEMP, CONF_MAX_SUNRISE_TIME, @@ -955,12 +956,14 @@ class AdaptiveSwitch(SwitchEntity, RestoreEntity): self._send_split_delay = data[CONF_SEND_SPLIT_DELAY] self._take_over_control = data[CONF_TAKE_OVER_CONTROL] if not data[CONF_TAKE_OVER_CONTROL] and ( - data[CONF_DETECT_NON_HA_CHANGES] or data[CONF_ADAPT_ONLY_ON_BARE_TURN_ON] + data[CONF_DETECT_NON_HA_CHANGES] + or data[CONF_ADAPT_ONLY_ON_BARE_TURN_ON] + or data[CONF_MANUAL_CONTROL_ON_EXTERNAL_TURN_ON] ): _LOGGER.warning( - "%s: Config mismatch: `detect_non_ha_changes` or `adapt_only_on_bare_turn_on` " - "set to `true` requires `take_over_control` to be enabled. Adjusting config " - "and continuing setup with `take_over_control: true`.", + "%s: Config mismatch: `detect_non_ha_changes`, `adapt_only_on_bare_turn_on`, " + "or `manual_control_on_external_turn_on` set to `true` requires `take_over_control` to be " + "enabled. Adjusting config and continuing setup with `take_over_control: true`.", self._name, ) self._take_over_control = True @@ -969,6 +972,9 @@ class AdaptiveSwitch(SwitchEntity, RestoreEntity): ) self._detect_non_ha_changes = data[CONF_DETECT_NON_HA_CHANGES] self._adapt_only_on_bare_turn_on = data[CONF_ADAPT_ONLY_ON_BARE_TURN_ON] + self._manual_control_on_external_turn_on = data[ + CONF_MANUAL_CONTROL_ON_EXTERNAL_TURN_ON + ] self._auto_reset_manual_control_time = data[CONF_AUTORESET_CONTROL] self._reset_manual_control_on_sleep_mode_change = data[ CONF_RESET_MANUAL_CONTROL_ON_SLEEP_MODE_CHANGE @@ -1603,16 +1609,26 @@ class AdaptiveSwitch(SwitchEntity, RestoreEntity): ) if ( self._take_over_control - and not self._detect_non_ha_changes + and ( + not self._detect_non_ha_changes + or self._manual_control_on_external_turn_on + ) and not from_turn_on ): # There is an edge case where 2 switches control the same light, e.g., # one for brightness and one for color. Now we will mark both switches # as manually controlled, which is not 100% correct. + # + # This 'off' → 'on' event does not exactly match the most recently tracked + # `light.turn_on` context for the entity. Hand control over when either: + # - `detect_non_ha_changes` is False (we can't reliably track manual changes + # to already-on lights anyway), or + # - `manual_control_on_external_turn_on` is True (the user explicitly wants external + # turn-ons left untouched, even while `detect_non_ha_changes` is enabled). _LOGGER.debug( "%s: Ignoring 'off' → 'on' event for '%s' with context.id='%s'" - " because 'light.turn_on' was not called by HA and" - " 'detect_non_ha_changes' is False", + " because it does not match a tracked 'light.turn_on' context and" + " ('detect_non_ha_changes' is False or 'manual_control_on_external_turn_on' is True)", self._name, entity_id, event.context.id, diff --git a/custom_components/adaptive_lighting/translations/en.json b/custom_components/adaptive_lighting/translations/en.json index 688bb984..2f1a7085 100644 --- a/custom_components/adaptive_lighting/translations/en.json +++ b/custom_components/adaptive_lighting/translations/en.json @@ -71,6 +71,7 @@ "autoreset_control_seconds": "autoreset_control_seconds", "only_once": "only_once: Adapt lights only when they are turned on (`true`) or keep adapting them (`false`). 🔄", "adapt_only_on_bare_turn_on": "adapt_only_on_bare_turn_on: When turning lights on initially. If set to `true`, AL adapts only if `light.turn_on` is invoked without specifying color or brightness. ❌🌈 This e.g., prevents adaptation when activating a scene and marks the light as manually controlled. If `false`, AL adapts regardless of the presence of color or brightness in the initial `service_data`. Needs `take_over_control` enabled. 🕵️", + "manual_control_on_external_turn_on": "manual_control_on_external_turn_on: Treat turn-ons without a matching Home Assistant `light.turn_on` context as manual control. Normal manual-control resets apply. Still allows `detect_non_ha_changes` for already-on lights. Needs `take_over_control` enabled. 🕵️", "reset_manual_control_on_sleep_mode_change": "reset_manual_control_on_sleep_mode_change: Reset manual control when the sleep mode switch is toggled. Set to `false` to preserve manual control across sleep mode changes. 😴", "separate_turn_on_commands": "separate_turn_on_commands: Use separate `light.turn_on` calls for color and brightness, needed for some light types. 🔀", "send_split_delay": "send_split_delay", @@ -271,6 +272,10 @@ "description": "Detects and halts adaptations for non-`light.turn_on` state changes. Needs `take_over_control` enabled. 🕵️ Caution: ⚠️ Some lights might falsely indicate an 'on' state, which could result in lights turning on unexpectedly. Note that this calls `homeassistant.update_entity` every `interval`! Disable this feature if you encounter such issues.", "name": "detect_non_ha_changes" }, + "manual_control_on_external_turn_on": { + "description": "Treat turn-ons without a matching Home Assistant `light.turn_on` context as manual control. Normal manual-control resets apply. Still allows `detect_non_ha_changes` for already-on lights. Needs `take_over_control` enabled. 🕵️", + "name": "manual_control_on_external_turn_on" + }, "transition": { "description": "Duration of transition when lights change, in seconds. 🕑", "name": "transition" diff --git a/docs/advanced/manual-control.md b/docs/advanced/manual-control.md index 4e84ca3f..dc099c57 100644 --- a/docs/advanced/manual-control.md +++ b/docs/advanced/manual-control.md @@ -112,6 +112,28 @@ adaptive_lighting: adapt_only_on_bare_turn_on: true ``` +### manual_control_on_external_turn_on + +When enabled, a turn-on without a state-change context matching the latest recorded Home Assistant `light.turn_on` is treated as manual control. This pauses brightness and color adaptation until manual control resets, rather than skipping just the first adjustment. The usual off/on, explicit reset, and configured timeout rules apply. A later unmatched turn-on marks the light manually controlled again. + +Manual-control flags are shared by profiles controlling the same light. Use the same turn-on policy on those profiles; mixed policies can allow an earlier profile to adapt before another marks the light manually controlled. + +Enable this if you want turn-ons from physical controls or native scenes to preserve their brightness and color. To adapt unmatched turn-ons, leave this disabled and enable `detect_non_ha_changes`. + +Its advantage over simply disabling `detect_non_ha_changes` is that the two behaviors are decoupled: you can keep `detect_non_ha_changes: true` to catch manual dimming of lights that are *already on*, while leaving unmatched turn-ons untouched. + +Adaptive Lighting cannot identify every physical versus Home Assistant source. Some integrations replace or omit the service context when they publish device state. In that case, even a Home Assistant turn-on does not match and this option treats it as external. + +```yaml +adaptive_lighting: + - name: "Respect physical switches and Lutron scenes" + lights: + - light.living_room + take_over_control: true + detect_non_ha_changes: true # still catch manual changes to already-on lights + manual_control_on_external_turn_on: true # leave unmatched off→on events unchanged +``` + ## Checking Manual Control Status You can see which lights are marked as manually controlled by checking the switch attributes: diff --git a/docs/configuration.md b/docs/configuration.md index 7edaac57..2a7402f0 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -66,6 +66,7 @@ All configuration options are listed below with their default values. These opti | `autoreset_control_seconds` | Automatically reset the manual control after a number of seconds. Set to 0 to disable. ⏲️ | `0` | `int` 0-31536000 | | `only_once` | Adapt lights only when they are turned on (`true`) or keep adapting them (`false`). 🔄 | `False` | `bool` | | `adapt_only_on_bare_turn_on` | When turning lights on initially. If set to `true`, AL adapts only if `light.turn_on` is invoked without specifying color or brightness. ❌🌈 This e.g., prevents adaptation when activating a scene and marks the light as manually controlled. If `false`, AL adapts regardless of the presence of color or brightness in the initial `service_data`. Needs `take_over_control` enabled. 🕵️ | `False` | `bool` | +| `manual_control_on_external_turn_on` | Treat turn-ons without a matching Home Assistant `light.turn_on` context as manual control. Normal manual-control resets apply. Still allows `detect_non_ha_changes` for already-on lights. Needs `take_over_control` enabled. 🕵️ | `False` | `bool` | | `reset_manual_control_on_sleep_mode_change` | Reset manual control when the sleep mode switch is toggled. Set to `false` to preserve manual control across sleep mode changes. 😴 | `True` | `bool` | | `separate_turn_on_commands` | Use separate `light.turn_on` calls for color and brightness, needed for some light types. 🔀 | `False` | `bool` | | `send_split_delay` | Delay (ms) between `separate_turn_on_commands` for lights that don't support simultaneous brightness and color setting. ⏲️ | `0` | `int` 0-10000 | diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index c5f59353..f39c62bc 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -59,6 +59,8 @@ Addressing these issues will significantly improve your Home Assistant experienc In case lights are suddenly turning on by themselves, this is most likely due to the light incorrectly reporting an "on" state to Home Assistant, leading to an undesired Adaptive Lighting action. To prevent adapting in cases *where the state of the light is suddenly "on" and only adapt if there is an associated `light.turn_on` service call*, set `detect_non_ha_changes: false`. +To keep detecting manual changes to lights that are already on while leaving unmatched `off` to `on` state events unchanged, enable `manual_control_on_external_turn_on`. Matching uses the exact context of the most recently recorded `light.turn_on` call. Some integrations replace or omit that context, so Adaptive Lighting cannot distinguish every physical versus Home Assistant turn-on source. + #### :signal_strength: WiFi Networks Ensure your light bulbs have a strong WiFi connection. If the signal strength is less than -70dBm, the connection may be weak and prone to dropping messages. diff --git a/tests/test_config_flow.py b/tests/test_config_flow.py index 04cbed5b..241bd5ae 100644 --- a/tests/test_config_flow.py +++ b/tests/test_config_flow.py @@ -12,8 +12,10 @@ except ImportError: from homeassistant.components.adaptive_lighting.const import ( BASIC_OPTIONS, CONF_INITIAL_TRANSITION, + CONF_MANUAL_CONTROL_ON_EXTERNAL_TURN_ON, CONF_SUNRISE_TIME, CONF_SUNSET_TIME, + DEFAULT_MANUAL_CONTROL_ON_EXTERNAL_TURN_ON, DEFAULT_NAME, DOMAIN, NONE_STR, @@ -149,6 +151,10 @@ async def test_options_schema_has_each_setting_once(hass): advanced = _advanced_section(result) assert advanced.options == {"collapsed": True} + assert ( + _schema_defaults(advanced.schema)[CONF_MANUAL_CONTROL_ON_EXTERNAL_TURN_ON] + is DEFAULT_MANUAL_CONTROL_ON_EXTERNAL_TURN_ON + ) assert {key.schema for key in schema if key.schema != "advanced"} == BASIC_OPTIONS assert {key.schema for key in advanced.schema.schema} == set( DEFAULT_DATA, diff --git a/tests/test_switch.py b/tests/test_switch.py index cfebc4f6..1765fb5e 100644 --- a/tests/test_switch.py +++ b/tests/test_switch.py @@ -39,6 +39,7 @@ from homeassistant.components.adaptive_lighting.const import ( CONF_DETECT_NON_HA_CHANGES, CONF_INITIAL_TRANSITION, CONF_MANUAL_CONTROL, + CONF_MANUAL_CONTROL_ON_EXTERNAL_TURN_ON, CONF_MAX_BRIGHTNESS, CONF_MAX_COLOR_TEMP, CONF_MIN_BRIGHTNESS, @@ -4473,6 +4474,152 @@ async def test_automation_turn_on_from_off_not_marked_as_manual_control(hass): ) +@pytest.mark.parametrize("intercept", [True, False]) +async def test_manual_control_on_external_turn_on_allows_tracked_service_call( + hass, + intercept, +): + """Test a real HA turn-on remains eligible for initial adaptation.""" + switch, _ = await setup_lights_and_switch( + hass, + { + CONF_MANUAL_CONTROL_ON_EXTERNAL_TURN_ON: True, + CONF_DETECT_NON_HA_CHANGES: True, + CONF_INTERCEPT: intercept, + CONF_MIN_BRIGHTNESS: 50, + CONF_MAX_BRIGHTNESS: 50, + }, + ) + await hass.services.async_call( + LIGHT_DOMAIN, + SERVICE_TURN_OFF, + {ATTR_ENTITY_ID: ENTITY_LIGHT_1}, + blocking=True, + ) + + await hass.services.async_call( + LIGHT_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: ENTITY_LIGHT_1, ATTR_BRIGHTNESS: 200}, + blocking=True, + context=Context(id=f"ha_turn_on_{intercept}"), + ) + await hass.async_block_till_done() + + state = hass.states.get(ENTITY_LIGHT_1) + assert state.state == STATE_ON + assert state.attributes[ATTR_BRIGHTNESS] == 128 + assert ( + switch.manager.get_manual_control_attributes(ENTITY_LIGHT_1) + == LightControlAttributes.NONE + ) + + +@pytest.mark.parametrize("intercept", [True, False]) +@pytest.mark.parametrize( + ( + "manual_control_on_external_turn_on", + "detect_non_ha_changes", + "expected_manual_control", + "expected_adaptation", + ), + [ + (True, True, LightControlAttributes.ALL, False), + (True, False, LightControlAttributes.ALL, False), + (False, True, LightControlAttributes.NONE, True), + (False, False, LightControlAttributes.ALL, False), + ], +) +async def test_manual_control_on_external_turn_on_external_state_change( + hass, + freezer, + intercept, + manual_control_on_external_turn_on, + detect_non_ha_changes, + expected_manual_control, + expected_adaptation, +): + """Test an unmatched off-to-on state event follows the opt-in policy.""" + switch, _ = await setup_lights_and_switch( + hass, + { + "manual_control_on_external_turn_on": manual_control_on_external_turn_on, + CONF_DETECT_NON_HA_CHANGES: detect_non_ha_changes, + CONF_INTERCEPT: intercept, + CONF_MIN_BRIGHTNESS: 50, + CONF_MAX_BRIGHTNESS: 50, + }, + ) + external_attributes = dict(hass.states.get(ENTITY_LIGHT_1).attributes) + external_attributes[ATTR_BRIGHTNESS] = 200 + hass.states.async_set( + ENTITY_LIGHT_1, + STATE_OFF, + external_attributes, + context=Context(id=f"unmatched_turn_off_{intercept}"), + ) + await hass.async_block_till_done() + assert hass.states.get(ENTITY_LIGHT_1).state == STATE_OFF + freezer.tick(6) + + hass.states.async_set( + ENTITY_LIGHT_1, + STATE_ON, + external_attributes, + context=Context(id=f"unmatched_turn_on_{intercept}"), + ) + await hass.async_block_till_done() + + assert ( + switch.manager.get_manual_control_attributes(ENTITY_LIGHT_1) + == expected_manual_control + ) + last_service_data = switch.manager.last_service_data.get(ENTITY_LIGHT_1) + if expected_adaptation: + assert last_service_data[ATTR_BRIGHTNESS] == 128 + else: + assert last_service_data is None + assert hass.states.get(ENTITY_LIGHT_1).attributes[ATTR_BRIGHTNESS] == 200 + + +@pytest.mark.parametrize("intercept", [True, False]) +async def test_manual_control_on_external_turn_on_keeps_non_ha_change_detection( + hass, + intercept, +): + """Test the option does not disable manual tracking for an on light.""" + switch, (light, *_) = await setup_lights_and_switch( + hass, + { + CONF_MANUAL_CONTROL_ON_EXTERNAL_TURN_ON: True, + CONF_DETECT_NON_HA_CHANGES: True, + CONF_INTERCEPT: intercept, + CONF_MIN_BRIGHTNESS: 50, + CONF_MAX_BRIGHTNESS: 50, + }, + ) + await switch._update_attrs_and_maybe_adapt_lights( + context=switch.create_context("test"), + transition=0, + ) + await hass.async_block_till_done() + assert hass.states.get(ENTITY_LIGHT_1).attributes[ATTR_BRIGHTNESS] == 128 + + set_light_brightness(light, 200) + light.async_write_ha_state() + await switch._update_attrs_and_maybe_adapt_lights( + context=switch.create_context("test"), + transition=0, + ) + await hass.async_block_till_done() + + assert hass.states.get(ENTITY_LIGHT_1).attributes[ATTR_BRIGHTNESS] == 200 + assert ( + switch.manager.get_manual_control_attributes(ENTITY_LIGHT_1) + == LightControlAttributes.BRIGHTNESS + ) + + @pytest.mark.parametrize("intercept", [True, False]) async def test_adapt_only_on_bare_turn_on_respects_pause_changed_mode(hass, intercept): """Test that adapt_only_on_bare_turn_on respects take_over_control_mode=PAUSE_CHANGED. From aa84eda871b391363b992585f6f2bd32d8590f33 Mon Sep 17 00:00:00 2001 From: Leonhard Hesse <44778508+hesseleo@users.noreply.github.com> Date: Sun, 6 Sep 2026 21:13:35 +0200 Subject: [PATCH 13/26] feat: add expand_light_groups option (#1462) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: add expand_light_groups option Some light group entities act as a proxy that must receive a single combined `light.turn_on` call to function correctly — virtual mixers like for instance, that blend a warm and a cold white channel into one entity. In such setups the individual member entities only expose `ColorMode.BRIGHTNESS`, so sending separate per-member commands bypasses the mixing logic. Setting `expand_light_groups: false` keeps the group entity in `self.lights` instead of expanding it to its members. Adaptation commands go to the group, and the interceptor no longer skips group entities for that switch. Default is `true` — no behaviour change for existing configurations. * tests: regression test for expand_light_groups=False _switches_with_lights was expanding the incoming entity_id globally, causing the switch to never be found when expand_light_groups=False * Resolve group targets consistently across adaptation paths * Discard delayed group events after target changes * Stabilize delayed group target regression test --------- Co-authored-by: Bas Nijholt --- README.md | 5 + custom_components/adaptive_lighting/const.py | 9 + .../adaptive_lighting/services.yaml | 6 + .../adaptive_lighting/strings.json | 7 +- custom_components/adaptive_lighting/switch.py | 102 +++- .../adaptive_lighting/translations/de.json | 6 +- .../adaptive_lighting/translations/en.json | 7 +- docs/advanced/manual-control.md | 4 + docs/configuration.md | 1 + tests/test_config_flow.py | 2 + tests/test_switch.py | 454 ++++++++++++++++-- 11 files changed, 547 insertions(+), 56 deletions(-) diff --git a/README.md b/README.md index d15c5249..3f924fb8 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,10 @@ This feature is available when `take_over_control` is enabled. Additionally, enabling `detect_non_ha_changes` allows Adaptive Lighting to detect all state changes, including those made outside of Home Assistant, by comparing the light's state to its previously used settings. The `adaptive_lighting.manual_control` event is fired when a light is marked as "manually controlled," allowing for integration with automations 🤖. +With `expand_light_groups: false`, manual control belongs to the group. A direct member change cannot pause adaptation for only that member; use group-level manual control or enable expansion for individual tracking. +Explicit member targets in Adaptive Lighting services stay individual targets and do not mark or command the whole group. +Changing expansion at runtime discards tracking and pending adaptation for targets no longer used by any profile. + The Adaptive Lighting switch exposes these read-only attributes for its lights: - `manual_control`: lights with any attribute marked as manually controlled. @@ -166,6 +170,7 @@ The YAML and frontend configuration methods support all of the options listed be | `intercept` | Intercept and adapt `light.turn_on` calls to enabling instantaneous color and brightness adaptation. 🏎️ Disable for lights that do not support `light.turn_on` with color and brightness. | `True` | `bool` | | `multi_light_intercept` | Intercept and adapt `light.turn_on` calls that target multiple lights. ➗⚠️ This might result in splitting up a single `light.turn_on` call into multiple calls, e.g., when lights are in different switches. Requires `intercept` to be enabled. | `True` | `bool` | | `include_config_in_attributes` | Show all options as attributes on the switch in Home Assistant when set to `true`. 📝 | `False` | `bool` | +| `expand_light_groups` | Expand light groups to their members (`true`, default). Set `false` to send commands to the group and track manual control for the group. Explicit member targets in services stay individual targets. | `True` | `bool` | diff --git a/custom_components/adaptive_lighting/const.py b/custom_components/adaptive_lighting/const.py index 7acf2781..afead25c 100644 --- a/custom_components/adaptive_lighting/const.py +++ b/custom_components/adaptive_lighting/const.py @@ -291,6 +291,14 @@ DOCS[CONF_MULTI_LIGHT_INTERCEPT] = ( "Requires `intercept` to be enabled." ) +CONF_EXPAND_LIGHT_GROUPS, DEFAULT_EXPAND_LIGHT_GROUPS = "expand_light_groups", True +DOCS[CONF_EXPAND_LIGHT_GROUPS] = ( + "Expand light groups to their members (`true`, default). Set `false` to send " + "commands to the group and track manual control for the group. Explicit member " + "targets in services stay individual targets." +) + + SLEEP_MODE_SWITCH = "sleep_mode_switch" ADAPT_COLOR_SWITCH = "adapt_color_switch" ADAPT_BRIGHTNESS_SWITCH = "adapt_brightness_switch" @@ -447,6 +455,7 @@ VALIDATION_TUPLES: list[tuple[str, Any, Any]] = [ (CONF_INTERCEPT, DEFAULT_INTERCEPT, bool), (CONF_MULTI_LIGHT_INTERCEPT, DEFAULT_MULTI_LIGHT_INTERCEPT, bool), (CONF_INCLUDE_CONFIG_IN_ATTRIBUTES, DEFAULT_INCLUDE_CONFIG_IN_ATTRIBUTES, bool), + (CONF_EXPAND_LIGHT_GROUPS, DEFAULT_EXPAND_LIGHT_GROUPS, bool), ] diff --git a/custom_components/adaptive_lighting/services.yaml b/custom_components/adaptive_lighting/services.yaml index 23e8ceda..c95e31b5 100644 --- a/custom_components/adaptive_lighting/services.yaml +++ b/custom_components/adaptive_lighting/services.yaml @@ -139,6 +139,12 @@ change_switch_settings: example: false selector: boolean: null + expand_light_groups: + description: Expand light groups to their members (`true`, default). Set `false` to send commands to the group and track manual control for the group. Explicit member targets in services stay individual targets. + required: false + example: true + selector: + boolean: null separate_turn_on_commands: description: Use separate `light.turn_on` calls for color and brightness, needed for some light types. 🔀 required: false diff --git a/custom_components/adaptive_lighting/strings.json b/custom_components/adaptive_lighting/strings.json index 6e07c69d..9e22ff57 100644 --- a/custom_components/adaptive_lighting/strings.json +++ b/custom_components/adaptive_lighting/strings.json @@ -78,7 +78,8 @@ "skip_redundant_commands": "skip_redundant_commands: Skip sending adaptation commands whose target state already equals the light's known state. Minimizes network traffic and improves the adaptation responsivity in some situations. 📉Disable if physical light states get out of sync with HA's recorded state.", "intercept": "intercept: Intercept and adapt `light.turn_on` calls to enabling instantaneous color and brightness adaptation. 🏎️ Disable for lights that do not support `light.turn_on` with color and brightness.", "multi_light_intercept": "multi_light_intercept: Intercept and adapt `light.turn_on` calls that target multiple lights. ➗⚠️ This might result in splitting up a single `light.turn_on` call into multiple calls, e.g., when lights are in different switches. Requires `intercept` to be enabled.", - "include_config_in_attributes": "include_config_in_attributes: Show all options as attributes on the switch in Home Assistant when set to `true`. 📝" + "include_config_in_attributes": "include_config_in_attributes: Show all options as attributes on the switch in Home Assistant when set to `true`. 📝", + "expand_light_groups": "expand_light_groups: Expand light groups to their members (`true`, default). Set `false` to send commands to the group and track manual control for the group. Explicit member targets in services stay individual targets." }, "data_description": { "initial_transition": "Duration of the first transition when lights turn from `off` to `on` in seconds. ⏲️", @@ -211,6 +212,10 @@ "description": "Whether to prefer RGB color adjustment over light color temperature when possible. 🌈", "name": "prefer_rgb_color" }, + "expand_light_groups": { + "description": "Expand light groups to their members (`true`, default). Set `false` to send commands to the group and track manual control for the group. Explicit member targets in services stay individual targets.", + "name": "expand_light_groups" + }, "separate_turn_on_commands": { "description": "Use separate `light.turn_on` calls for color and brightness, needed for some light types. 🔀", "name": "separate_turn_on_commands" diff --git a/custom_components/adaptive_lighting/switch.py b/custom_components/adaptive_lighting/switch.py index ab9273df..c85087a9 100644 --- a/custom_components/adaptive_lighting/switch.py +++ b/custom_components/adaptive_lighting/switch.py @@ -98,6 +98,7 @@ from .const import ( CONF_BRIGHTNESS_MODE_TIME_DARK, CONF_BRIGHTNESS_MODE_TIME_LIGHT, CONF_DETECT_NON_HA_CHANGES, + CONF_EXPAND_LIGHT_GROUPS, CONF_INCLUDE_CONFIG_IN_ATTRIBUTES, CONF_INITIAL_TRANSITION, CONF_INTERCEPT, @@ -252,14 +253,11 @@ def _switches_with_lights( if not loaded_switches: return [] - all_check_lights = ( - _expand_light_groups(hass, lights) if expand_light_groups else set(lights) - ) switches: AdaptiveSwitches = [] for switch in loaded_switches: - switch._expand_light_groups(hass=hass) - # Check if any of the lights are in the switch's lights - if set(switch.lights) & set(all_check_lights): + switch._expand_light_groups() + check_lights = switch._resolve_lights(lights) if expand_light_groups else lights + if set(switch.lights) & set(check_lights): switches.append(switch) return switches @@ -422,7 +420,7 @@ async def handle_apply_service(hass: HomeAssistant, service_call: ServiceCall) - switches = _switches_from_service_call(hass, service_call) lights = data[CONF_LIGHTS] for switch in switches: - all_lights = switch.lights if not lights else _expand_light_groups(hass, lights) + all_lights = switch._resolve_lights(lights or None) switch.manager.lights.update(all_lights) for light in all_lights: if data[CONF_TURN_ON_LIGHTS] or is_on(hass, light): @@ -457,7 +455,7 @@ async def handle_set_manual_control_service( switches = _switches_from_service_call(hass, service_call) lights = data[CONF_LIGHTS] for switch in switches: - all_lights = switch.lights if not lights else _expand_light_groups(hass, lights) + all_lights = switch._resolve_lights(lights or None) manual_attributes = manual_control_event_attribute_to_flags( data[CONF_MANUAL_CONTROL], ) @@ -626,17 +624,22 @@ def _expand_light_groups( hass: HomeAssistant, lights: list[str], ) -> list[str]: + """Resolve nested groups without changing another profile's tracked targets.""" all_lights: set[str] = set() - manager = hass.data[DOMAIN][ATTR_ADAPTIVE_LIGHTING_MANAGER] - for light in lights: + pending = list(lights) + visited: set[str] = set() + while pending: + light = pending.pop() + if light in visited: + continue + visited.add(light) state = hass.states.get(light) if state is None: _LOGGER.debug("State of %s is None", light) all_lights.add(light) elif _is_light_group(state): group = state.attributes["entity_id"] - manager.lights.discard(light) - all_lights.update(group) + pending.extend(group) _LOGGER.debug("Expanded %s to %s", light, group) else: all_lights.add(light) @@ -889,7 +892,8 @@ class AdaptiveSwitch(SwitchEntity, RestoreEntity): self._name = data[CONF_NAME] self._interval: timedelta = data[CONF_INTERVAL] - self.lights: list[str] = data[CONF_LIGHTS] + self._configured_lights: list[str] = list(data[CONF_LIGHTS]) + self.lights: list[str] = [] # backup data for use in change_switch_settings "configuration" CONF_USE_DEFAULTS self._config_backup = deepcopy(data) @@ -990,6 +994,7 @@ class AdaptiveSwitch(SwitchEntity, RestoreEntity): self._name, ) self._multi_light_intercept = False + self._expand_light_groups_flag = data[CONF_EXPAND_LIGHT_GROUPS] self._expand_light_groups() # updates manual control timers observer = get_astral_observer(self.hass) @@ -1073,15 +1078,29 @@ class AdaptiveSwitch(SwitchEntity, RestoreEntity): """Remove the listeners upon removing the component.""" self._remove_listeners() - def _expand_light_groups(self, hass: HomeAssistant | None = None) -> None: - hass = hass or self.hass - all_lights = _expand_light_groups(hass, self.lights) + def _resolve_lights(self, lights: list[str] | None = None) -> list[str]: + """Apply this profile's group policy, preserving explicit member targets.""" + if lights is None: + lights = self._configured_lights + if self._expand_light_groups_flag: + return _expand_light_groups(self.hass, lights) + return sorted(set(lights)) + + def _expand_light_groups(self) -> None: + all_lights = self._resolve_lights() + removed = set(self.lights) - set(all_lights) + self.lights = all_lights + if removed: + # Other profiles may still own a retired member or group, even when off. + for entry in self.hass.data[DOMAIN].values(): + if isinstance(entry, dict) and (switch := entry.get(SWITCH_DOMAIN)): + removed.difference_update(switch._resolve_lights()) + self.manager.remove_lights(*removed) self.manager.lights.update(all_lights) self.manager.set_auto_reset_manual_control_times( all_lights, self._auto_reset_manual_control_time, ) - self.lights = list(all_lights) async def _setup_listeners(self, _: Event[NoEventData] | None = None) -> None: _LOGGER.debug("%s: Called '_setup_listeners'", self._name) @@ -1521,6 +1540,7 @@ class AdaptiveSwitch(SwitchEntity, RestoreEntity): return if lights is None: + self._expand_light_groups() lights = self.lights on_lights = [light for light in lights if is_on(self.hass, light)] @@ -1668,6 +1688,10 @@ class AdaptiveSwitch(SwitchEntity, RestoreEntity): if self._adapt_delay > 0: await asyncio.sleep(self._adapt_delay) + # Runtime settings may retire this profile's target while the event waits. + if entity_id not in self.lights: + return + await self._update_attrs_and_maybe_adapt_lights( context=self.create_context("light_event", parent=event.context), lights=[entity_id], @@ -1983,8 +2007,12 @@ class AdaptiveLightingManager: if ( not switch.is_on or not switch._intercept - # Never adapt on light groups, because HA will make a separate light.turn_on - or ((e := self.hass.states.get(entity_id)) and _is_light_group(e)) + # Never adapt on light groups when expanding, because HA will make a separate light.turn_on + or ( + switch._expand_light_groups_flag + and (e := self.hass.states.get(entity_id)) + and _is_light_group(e) + ) # Prevent adaptation of TURN_ON calls when light is already on, # and of TOGGLE calls when toggling off. or self.hass.states.is_state(entity_id, STATE_ON) @@ -2381,7 +2409,11 @@ class AdaptiveLightingManager: delay, ) self.reset(light) - switches = _switches_with_lights(self.hass, [light]) + switches = _switches_with_lights( + self.hass, + [light], + expand_light_groups=False, + ) for switch in switches: if not switch.is_on: continue @@ -2572,6 +2604,30 @@ class AdaptiveLightingManager: if reset_manual_control: self._schedule_manual_control_state_update(*lights) + def remove_lights(self, *lights: str) -> None: + """Retire tracking and pending work for targets no profile owns anymore.""" + self.reset(*lights) + for light in lights: + self.lights.discard(light) + self.clear_proactively_adapting(light) + if timer := self.transition_timers.pop(light, None): + timer.cancel() + if task := self.sleep_tasks.pop(light, None): + task.cancel() + for records in ( + self.manual_control, + self.auto_reset_manual_control_times, + self.turn_on_event, + self.turn_off_event, + self.toggle_event, + self.on_to_off_event, + self.off_to_on_event, + self.turn_off_locks, + self.adaptation_tasks_brightness, + self.adaptation_tasks_color, + ): + records.pop(light, None) + def _get_entity_list(self, service_data: ServiceData) -> list[str]: if ATTR_ENTITY_ID in service_data: return cv.ensure_list_csv(service_data[ATTR_ENTITY_ID]) @@ -2806,7 +2862,11 @@ class AdaptiveLightingManager: ) return - switches = _switches_with_lights(self.hass, [entity_id]) + switches = _switches_with_lights( + self.hass, + [entity_id], + expand_light_groups=False, + ) for switch in switches: if switch.is_on: await switch._respond_to_off_to_on_event( diff --git a/custom_components/adaptive_lighting/translations/de.json b/custom_components/adaptive_lighting/translations/de.json index a03c238f..4885e753 100644 --- a/custom_components/adaptive_lighting/translations/de.json +++ b/custom_components/adaptive_lighting/translations/de.json @@ -68,7 +68,8 @@ "skip_redundant_commands": "skip_redundant_commands: Überspringt das Senden von Anpassungsbefehlen, deren Zielzustand bereits mit dem bekannten Zustand der Leuchte übereinstimmt. Minimiert den Netzwerkverkehr und verbessert die Anpassungsreaktion in einigen Situationen. 📉 Deaktivieren, falls der physikalische Zustand der Lichter nicht mehr mit dem Zustand in HA übereinstimmt.", "intercept": "intercept: Abfangen und Anpassen von `light.turn_on`-Aufrufen, um eine sofortige Anpassung von Farbe und Helligkeit zu ermöglichen. 🏎️ Deaktivieren für Leuchten, die `light.turn_on` mit Farbe und Helligkeit nicht unterstützen.", "multi_light_intercept": "multi_light_intercept: Abfangen und Anpassen von `light.turn_on`-Aufrufen, die auf mehrere Lichter aufrufen. ➗⚠️ Dies kann dazu führen, dass ein einzelner `light.turn_on`-Aufruf in mehrere Aufrufe aufgeteilt wird, z.B. wenn Lichter in verschiedenen Schaltern sind. Erfordert, dass `intercept` aktiviert ist.", - "include_config_in_attributes": "include_config_in_attributes: Alle Optionen als Attribute auf dem Schalter im Home Assistant anzeigen, wenn auf `true` gesetzt. 📝" + "include_config_in_attributes": "include_config_in_attributes: Alle Optionen als Attribute auf dem Schalter im Home Assistant anzeigen, wenn auf `true` gesetzt. 📝", + "expand_light_groups": "expand_light_groups: Lichtgruppen auf einzelne Mitgliedsentitäten erweitern (`true`) oder die Gruppenentität direkt steuern (`false`)." }, "data_description": { "initial_transition": "Dauer des ersten Übergangs, wenn das Licht von `off` auf `on` schaltet, in Sekunden. ⏲️", @@ -88,7 +89,8 @@ "brightness_mode_time_light": "(Wird ignoriert, wenn `brightness_mode='default'`) Die Dauer in Sekunden, um die Helligkeit nach/vor Sonnenaufgang/Sonnenuntergang hoch/runter zu fahren. 📈📉.", "autoreset_control_seconds": "Setzt die manuelle Steuerung nach einer bestimmten Anzahl von Sekunden automatisch zurück. Zum Deaktivieren auf 0 setzen. ⏲️", "send_split_delay": "Verzögerung (ms) zwischen `separate_turn_on_commands` für Leuchten, die keine gleichzeitige Einstellung von Helligkeit und Farbe unterstützen. ⏲️", - "adapt_delay": "Wartezeit (Sekunden) zwischen dem Einschalten des Lichts und der Anwendung der adaptiven Beleuchtung. Könnte helfen, Flackern zu vermeiden. ⏲️" + "adapt_delay": "Wartezeit (Sekunden) zwischen dem Einschalten des Lichts und der Anwendung der adaptiven Beleuchtung. Könnte helfen, Flackern zu vermeiden. ⏲️", + "expand_light_groups": "Wenn auf `false` gesetzt, werden Anpassungsbefehle direkt an die Gruppenentität gesendet und nicht an die einzelnen Mitglieder." } } } diff --git a/custom_components/adaptive_lighting/translations/en.json b/custom_components/adaptive_lighting/translations/en.json index 2f1a7085..cc589156 100644 --- a/custom_components/adaptive_lighting/translations/en.json +++ b/custom_components/adaptive_lighting/translations/en.json @@ -79,7 +79,8 @@ "skip_redundant_commands": "skip_redundant_commands: Skip sending adaptation commands whose target state already equals the light's known state. Minimizes network traffic and improves the adaptation responsivity in some situations. 📉Disable if physical light states get out of sync with HA's recorded state.", "intercept": "intercept: Intercept and adapt `light.turn_on` calls to enabling instantaneous color and brightness adaptation. 🏎️ Disable for lights that do not support `light.turn_on` with color and brightness.", "multi_light_intercept": "multi_light_intercept: Intercept and adapt `light.turn_on` calls that target multiple lights. ➗⚠️ This might result in splitting up a single `light.turn_on` call into multiple calls, e.g., when lights are in different switches. Requires `intercept` to be enabled.", - "include_config_in_attributes": "include_config_in_attributes: Show all options as attributes on the switch in Home Assistant when set to `true`. 📝" + "include_config_in_attributes": "include_config_in_attributes: Show all options as attributes on the switch in Home Assistant when set to `true`. 📝", + "expand_light_groups": "expand_light_groups: Expand light groups to their members (`true`, default). Set `false` to send commands to the group and track manual control for the group. Explicit member targets in services stay individual targets." }, "data_description": { "initial_transition": "Duration of the first transition when lights turn from `off` to `on` in seconds. ⏲️", @@ -212,6 +213,10 @@ "description": "Whether to prefer RGB color adjustment over light color temperature when possible. 🌈", "name": "prefer_rgb_color" }, + "expand_light_groups": { + "description": "Expand light groups to their members (`true`, default). Set `false` to send commands to the group and track manual control for the group. Explicit member targets in services stay individual targets.", + "name": "expand_light_groups" + }, "separate_turn_on_commands": { "description": "Use separate `light.turn_on` calls for color and brightness, needed for some light types. 🔀", "name": "separate_turn_on_commands" diff --git a/docs/advanced/manual-control.md b/docs/advanced/manual-control.md index dc099c57..4b0bfe51 100644 --- a/docs/advanced/manual-control.md +++ b/docs/advanced/manual-control.md @@ -20,6 +20,10 @@ This feature is available when `take_over_control` is enabled. Additionally, enabling `detect_non_ha_changes` allows Adaptive Lighting to detect all state changes, including those made outside of Home Assistant, by comparing the light's state to its previously used settings. The `adaptive_lighting.manual_control` event is fired when a light is marked as "manually controlled," allowing for integration with automations 🤖. +With `expand_light_groups: false`, manual control belongs to the group. A direct member change cannot pause adaptation for only that member; use group-level manual control or enable expansion for individual tracking. +Explicit member targets in Adaptive Lighting services stay individual targets and do not mark or command the whole group. +Changing expansion at runtime discards tracking and pending adaptation for targets no longer used by any profile. + The Adaptive Lighting switch exposes these read-only attributes for its lights: - `manual_control`: lights with any attribute marked as manually controlled. diff --git a/docs/configuration.md b/docs/configuration.md index 2a7402f0..afd05721 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -75,6 +75,7 @@ All configuration options are listed below with their default values. These opti | `intercept` | Intercept and adapt `light.turn_on` calls to enabling instantaneous color and brightness adaptation. 🏎️ Disable for lights that do not support `light.turn_on` with color and brightness. | `True` | `bool` | | `multi_light_intercept` | Intercept and adapt `light.turn_on` calls that target multiple lights. ➗⚠️ This might result in splitting up a single `light.turn_on` call into multiple calls, e.g., when lights are in different switches. Requires `intercept` to be enabled. | `True` | `bool` | | `include_config_in_attributes` | Show all options as attributes on the switch in Home Assistant when set to `true`. 📝 | `False` | `bool` | +| `expand_light_groups` | Expand light groups to their members (`true`, default). Set `false` to send commands to the group and track manual control for the group. Explicit member targets in services stay individual targets. | `True` | `bool` | diff --git a/tests/test_config_flow.py b/tests/test_config_flow.py index 241bd5ae..addc460c 100644 --- a/tests/test_config_flow.py +++ b/tests/test_config_flow.py @@ -11,6 +11,7 @@ except ImportError: from voluptuous_serialize import convert as to_field_list from homeassistant.components.adaptive_lighting.const import ( BASIC_OPTIONS, + CONF_EXPAND_LIGHT_GROUPS, CONF_INITIAL_TRANSITION, CONF_MANUAL_CONTROL_ON_EXTERNAL_TURN_ON, CONF_SUNRISE_TIME, @@ -106,6 +107,7 @@ async def test_options(hass): # Build input with advanced options nested in "advanced" section advanced_data = ADVANCED_DATA.copy() advanced_data[CONF_INITIAL_TRANSITION] = 23 + advanced_data[CONF_EXPAND_LIGHT_GROUPS] = False advanced_data[CONF_SUNRISE_TIME] = NONE_STR advanced_data[CONF_SUNSET_TIME] = NONE_STR basic_data = {**BASIC_DATA, "min_brightness": 12} diff --git a/tests/test_switch.py b/tests/test_switch.py index 1765fb5e..0b9129e3 100644 --- a/tests/test_switch.py +++ b/tests/test_switch.py @@ -37,6 +37,7 @@ from homeassistant.components.adaptive_lighting.const import ( CONF_BRIGHTNESS_MODE_TIME_DARK, CONF_BRIGHTNESS_MODE_TIME_LIGHT, CONF_DETECT_NON_HA_CHANGES, + CONF_EXPAND_LIGHT_GROUPS, CONF_INITIAL_TRANSITION, CONF_MANUAL_CONTROL, CONF_MANUAL_CONTROL_ON_EXTERNAL_TURN_ON, @@ -2301,7 +2302,8 @@ def test_attributes_have_changed(): 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. @@ -3824,6 +3826,407 @@ async def test_light_group( assert len(events) == 3 +def _track_adaptive_light_calls(hass, *, ours_only=True): + """Capture commands emitted by Adaptive Lighting at the HA service boundary.""" + calls = [] + + def track(event): + if ( + event.data["domain"] == LIGHT_DOMAIN + and event.data["service"] == SERVICE_TURN_ON + and (not ours_only or is_our_context(event.context)) + ): + calls.append(event.data["service_data"]) + + hass.bus.async_listen(EVENT_CALL_SERVICE, track) + return calls + + +async def _setup_group_switch(hass, **settings): + return await setup_switch( + hass, + { + CONF_LIGHTS: ["light.light_group"], + CONF_INITIAL_TRANSITION: 0, + CONF_TRANSITION: 0, + CONF_MIN_BRIGHTNESS: 50, + CONF_MAX_BRIGHTNESS: 50, + **settings, + }, + ) + + +@pytest.mark.parametrize("intercept", [False, True]) +async def test_light_group_expand_disabled_off_to_on(hass, intercept, cleanup): + """Group adaptation reaches members through the group on both turn-on paths.""" + await setup_lights(hass, with_group=True) + _, switch = await _setup_group_switch( + hass, + expand_light_groups=False, + intercept=intercept, + ) + calls = _track_adaptive_light_calls(hass, ours_only=False) + await hass.services.async_call( + LIGHT_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: "light.light_group"}, + blocking=True, + ) + await hass.async_block_till_done() + await asyncio.gather(*switch.manager.adaptation_tasks) + # HA emits the original service event before the interceptor changes its data. + # The group forwards the injected values to its real member entities. + expected_target = ( + ["light.light_4", "light.light_5"] if intercept else "light.light_group" + ) + assert any( + call[ATTR_ENTITY_ID] == expected_target and call.get(ATTR_BRIGHTNESS) == 128 + for call in calls + ), calls + for member in ["light.light_4", "light.light_5"]: + assert hass.states.get(member).attributes[ATTR_BRIGHTNESS] == 128 + + calls.clear() + await switch._async_update_at_interval_action() + await hass.async_block_till_done() + assert any(call[ATTR_ENTITY_ID] == "light.light_group" for call in calls) + await hass.services.async_call( + LIGHT_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: "light.light_group", ATTR_BRIGHTNESS: 77}, + blocking=True, + ) + await hass.async_block_till_done() + await switch._async_update_at_interval_action() + await hass.async_block_till_done() + assert hass.states.get(switch.entity_id).attributes["manual_control"] == [ + "light.light_group", + ] + for member in ["light.light_4", "light.light_5"]: + assert hass.states.get(member).attributes[ATTR_BRIGHTNESS] == 77 + + +@pytest.mark.parametrize("expand", [False, True]) +@pytest.mark.parametrize("explicit_member", [False, True]) +async def test_group_apply_respects_target_policy( + hass, + expand, + explicit_member, + cleanup, +): + """Apply obeys profile expansion without widening an explicit member request.""" + await setup_lights(hass, with_group=True) + _, switch = await _setup_group_switch(hass, expand_light_groups=expand) + calls = _track_adaptive_light_calls(hass) + target = "light.light_4" if explicit_member else "light.light_group" + await hass.services.async_call( + DOMAIN, + SERVICE_APPLY, + { + ATTR_ENTITY_ID: switch.entity_id, + CONF_LIGHTS: [target], + CONF_TURN_ON_LIGHTS: True, + }, + blocking=True, + ) + await hass.async_block_till_done() + expected = ( + ["light.light_4"] + if explicit_member + else (["light.light_4", "light.light_5"] if expand else ["light.light_group"]) + ) + # HA also emits forwarded member calls; AL's own commands use a scalar target. + assert ( + sorted( + { + call[ATTR_ENTITY_ID] + for call in calls + if isinstance(call[ATTR_ENTITY_ID], str) + }, + ) + == expected + ) + assert hass.states.get("light.light_4").attributes[ATTR_BRIGHTNESS] == 128 + assert hass.states.get("light.light_5").state == ( + STATE_OFF if explicit_member else STATE_ON + ) + + +@pytest.mark.parametrize("expand", [False, True]) +async def test_group_manual_control_service(hass, expand, cleanup): + """Group lookup and manual service use the same target policy, including reset.""" + await setup_lights(hass, with_group=True) + _, switch = await _setup_group_switch(hass, expand_light_groups=expand) + await hass.services.async_call( + DOMAIN, + SERVICE_SET_MANUAL_CONTROL, + {CONF_LIGHTS: ["light.light_group"], CONF_MANUAL_CONTROL: True}, + blocking=True, + ) + await hass.async_block_till_done() + expected = ["light.light_4", "light.light_5"] if expand else ["light.light_group"] + assert hass.states.get(switch.entity_id).attributes["manual_control"] == expected + for target in expected: + assert switch.manager.manual_control[target] == LightControlAttributes.ALL + await hass.services.async_call( + DOMAIN, + SERVICE_SET_MANUAL_CONTROL, + {CONF_LIGHTS: ["light.light_group"], CONF_MANUAL_CONTROL: False}, + blocking=True, + ) + await hass.async_block_till_done() + assert hass.states.get(switch.entity_id).attributes["manual_control"] == [] + + +@pytest.mark.parametrize("shared_member", [False, True]) +async def test_group_runtime_expansion_restores_targets(hass, shared_member, cleanup): + """Changing expansion back and forth restores groups and retires member timers.""" + await setup_lights(hass, with_group=True) + _, switch = await _setup_group_switch(hass, autoreset_control_seconds=60) + if shared_member: + _, other = await _setup_group_switch( + hass, + name="member", + lights=["light.light_4"], + autoreset_control_seconds=60, + ) + await other.async_turn_off() + await hass.services.async_call( + DOMAIN, + SERVICE_APPLY, + {ATTR_ENTITY_ID: switch.entity_id, CONF_TURN_ON_LIGHTS: True}, + blocking=True, + ) + await hass.services.async_call( + DOMAIN, + SERVICE_SET_MANUAL_CONTROL, + { + ATTR_ENTITY_ID: switch.entity_id, + CONF_LIGHTS: ["light.light_group"], + CONF_MANUAL_CONTROL: True, + }, + blocking=True, + ) + manager = switch.manager + old_timers = dict(manager.auto_reset_manual_control_timers) + assert len(old_timers) == 2 + calls = _track_adaptive_light_calls(hass) + await hass.services.async_call( + DOMAIN, + SERVICE_CHANGE_SWITCH_SETTINGS, + {ATTR_ENTITY_ID: switch.entity_id, CONF_EXPAND_LIGHT_GROUPS: False}, + blocking=True, + ) + await hass.async_block_till_done() + assert switch.lights == ["light.light_group"] + retained = {"light.light_4"} if shared_member else set() + assert manager.lights == {"light.light_group"} | retained + assert set(manager.auto_reset_manual_control_timers) == retained + for light, timer in old_timers.items(): + assert timer.is_running() == (light in retained) + assert ( + manager.manual_control.get("light.light_5", LightControlAttributes.NONE) + == LightControlAttributes.NONE + ) + assert any(call[ATTR_ENTITY_ID] == "light.light_group" for call in calls) + calls.clear() + await hass.services.async_call( + DOMAIN, + SERVICE_CHANGE_SWITCH_SETTINGS, + {ATTR_ENTITY_ID: switch.entity_id, CONF_EXPAND_LIGHT_GROUPS: True}, + blocking=True, + ) + await hass.async_block_till_done() + assert switch.lights == ["light.light_4", "light.light_5"] + assert manager.lights == {"light.light_4", "light.light_5"} + expected = ( + ["light.light_5"] if shared_member else ["light.light_4", "light.light_5"] + ) + assert sorted({call[ATTR_ENTITY_ID] for call in calls}) == expected + if shared_member: + assert manager.manual_control["light.light_4"] == LightControlAttributes.ALL + + +@pytest.mark.parametrize("expand", [False, True]) +@pytest.mark.parametrize("shared_target", [False, True]) +async def test_group_runtime_change_retires_delayed_events( + hass, + expand, + shared_target, + cleanup, +): + """Delayed reactive handlers must not command targets this profile retired.""" + await setup_lights(hass, with_group=True) + _, switch = await _setup_group_switch( + hass, + expand_light_groups=expand, + adapt_delay=0.1234, + ) + retired_targets = ( + {"light.light_4", "light.light_5"} if expand else {"light.light_group"} + ) + retained_target = "light.light_4" if expand else "light.light_group" + if shared_target: + _, other = await _setup_group_switch( + hass, + name="retained", + lights=[retained_target], + expand_light_groups=False, + ) + await other.async_turn_off() + + entered, release = asyncio.Event(), asyncio.Event() + original_sleep = asyncio.sleep + delayed_count = 0 + + async def controlled_sleep(delay, *args, **kwargs): + nonlocal delayed_count + if delay == 0.1234: + delayed_count += 1 + if delayed_count == (2 if expand else 1): + entered.set() + await release.wait() + else: + await original_sleep(delay, *args, **kwargs) + + calls = _track_adaptive_light_calls(hass) + with patch.object(asyncio, "sleep", controlled_sleep): + try: + await hass.services.async_call( + LIGHT_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: "light.light_group"}, + blocking=True, + ) + await asyncio.wait_for(entered.wait(), timeout=2) + await hass.services.async_call( + DOMAIN, + SERVICE_CHANGE_SWITCH_SETTINGS, + { + ATTR_ENTITY_ID: switch.entity_id, + CONF_EXPAND_LIGHT_GROUPS: not expand, + }, + blocking=True, + ) + expected = ( + ["light.light_group"] if expand else ["light.light_4", "light.light_5"] + ) + assert switch.lights == expected + assert switch.manager.lights == set(expected) | ( + {retained_target} if shared_target else set() + ) + calls.clear() + finally: + release.set() + await hass.async_block_till_done() + + retired_calls = [ + call + for call in calls + if isinstance(call[ATTR_ENTITY_ID], str) + and call[ATTR_ENTITY_ID] in retired_targets + ] + assert ( + not retired_calls + ), f"Retired reactive handlers issued commands: {retired_calls}" + for member in ["light.light_4", "light.light_5"]: + assert hass.states.get(member).attributes[ATTR_BRIGHTNESS] == 128 + + +@pytest.mark.parametrize("trigger", ["turn_on", "autoreset"]) +async def test_group_mixed_profiles_preserve_tracking(hass, trigger, cleanup): + """Expanding one profile must not remove another profile's group tracking.""" + await setup_lights(hass, with_group=True) + _, proxy = await _setup_group_switch( + hass, + expand_light_groups=False, + autoreset_control_seconds=60, + detect_non_ha_changes=True, + ) + _, expanded = await _setup_group_switch( + hass, + name="expanded", + min_brightness=70, + max_brightness=70, + detect_non_ha_changes=True, + ) + calls = _track_adaptive_light_calls(hass) + await hass.services.async_call( + DOMAIN, + SERVICE_APPLY, + { + ATTR_ENTITY_ID: expanded.entity_id, + CONF_LIGHTS: ["light.light_group"], + CONF_TURN_ON_LIGHTS: True, + }, + blocking=True, + ) + await hass.async_block_till_done() + assert "light.light_group" in proxy.manager.lights + calls.clear() + if trigger == "turn_on": + await hass.services.async_call( + LIGHT_DOMAIN, + SERVICE_TURN_OFF, + {ATTR_ENTITY_ID: "light.light_group"}, + blocking=True, + ) + await hass.async_block_till_done() + await hass.services.async_call( + LIGHT_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: "light.light_group"}, + blocking=True, + ) + else: + await hass.services.async_call( + DOMAIN, + SERVICE_SET_MANUAL_CONTROL, + { + ATTR_ENTITY_ID: proxy.entity_id, + CONF_LIGHTS: ["light.light_group"], + CONF_MANUAL_CONTROL: True, + }, + blocking=True, + ) + timer = proxy.manager.auto_reset_manual_control_timers["light.light_group"] + timer.delay = 0 + timer.start() + await timer.task + await hass.async_block_till_done() + # Only the proxy profile may command the group; the expanded profile uses members. + assert { + call[ATTR_BRIGHTNESS] + for call in calls + if call[ATTR_ENTITY_ID] == "light.light_group" and ATTR_BRIGHTNESS in call + } == {128} + + +async def test_nested_group_apply_targets_leaves(hass, cleanup): + """Default expansion reaches nested leaves without sending commands to subgroups.""" + await setup_lights(hass, with_group=True) + hass.states.async_set( + "light.outer", + STATE_OFF, + {ATTR_ENTITY_ID: ["light.light_group", "light.light_3"]}, + ) + _, switch = await _setup_group_switch(hass, lights=["light.outer"]) + calls = _track_adaptive_light_calls(hass) + await hass.services.async_call( + DOMAIN, + SERVICE_APPLY, + {CONF_LIGHTS: ["light.outer"], CONF_TURN_ON_LIGHTS: True}, + blocking=True, + ) + await hass.async_block_till_done() + assert sorted({call[ATTR_ENTITY_ID] for call in calls}) == [ + "light.light_3", + "light.light_4", + "light.light_5", + ] + assert switch.lights == ["light.light_3", "light.light_4", "light.light_5"] + + def _state_changed_event(entity_id: str, ts: float, context: Context) -> Event: return Event( EVENT_STATE_CHANGED, @@ -3960,25 +4363,21 @@ async def test_just_turned_off_same_automation_context(hass, cleanup): async def test_just_turned_off_group_context_reuse_end_to_end(hass, cleanup): - """Drive the issue #1378 scenario through the real event bus listeners. - - Unlike `test_just_turned_off_group_context_reuse`, which calls - `just_turned_off` directly, this test fires the service and state-changed - events on the bus. Light groups are normally expanded out of - `manager.lights`, but they can remain tracked in real setups (e.g., when a - group is nested inside another configured group or is unavailable during - setup), which is the configuration under which issue #1378 was reported. - """ + """A tracked member turn-on explains a group's reused OFF context (#1378).""" await setup_lights(hass, with_group=True) - _, switch = await setup_switch(hass, {CONF_LIGHTS: ["light.light_group"]}) + _, switch = await _setup_group_switch( + hass, + lights=["light.light_group", "light.light_4"], + expand_light_groups=False, + detect_non_ha_changes=True, + ) await hass.async_block_till_done() manager = switch.manager group = "light.light_group" member = "light.light_4" assert member in manager.lights - # Simulate a setup in which the group entity itself remains tracked. - manager.lights.add(group) + assert group in manager.lights turn_off_context = Context() # The group was turned off... @@ -4008,25 +4407,18 @@ async def test_just_turned_off_group_context_reuse_end_to_end(hass, cleanup): assert member in manager.turn_on_event # ...which turned the group back on, but HA reused the old turn_off context. - with patch.object( - AdaptiveSwitch, - "_respond_to_off_to_on_event", - AsyncMock(), - ) as respond: - hass.bus.async_fire( - EVENT_STATE_CHANGED, - { - "entity_id": group, - "old_state": State(group, STATE_OFF), - "new_state": State(group, STATE_ON), - }, - context=turn_off_context, - ) - await hass.async_block_till_done() + calls = _track_adaptive_light_calls(hass) + state = hass.states.get(group) + hass.states.async_set(group, STATE_ON, state.attributes, context=turn_off_context) + await hass.async_block_till_done() - # Adaptation must not have been cancelled as a polling artifact. - respond.assert_called_once() - assert respond.call_args[0][0] == group + # The real group command must survive polling-artifact detection. + assert any( + call[ATTR_ENTITY_ID] == group and call.get(ATTR_BRIGHTNESS) == 128 + for call in calls + ) + for entity_id in ["light.light_4", "light.light_5"]: + assert hass.states.get(entity_id).attributes[ATTR_BRIGHTNESS] == 128 @pytest.mark.parametrize("brightness_mode", ["linear", "tanh"]) From c5d216ea6f07221281f77c05ebb0029c4f55298b Mon Sep 17 00:00:00 2001 From: Bas Nijholt Date: Sun, 6 Sep 2026 21:50:32 +0200 Subject: [PATCH 14/26] fix: synchronize sleep mode and mixed-light split timing (#1579) * fix: synchronize sleep mode and mixed-light split timing * docs: refresh generated sleep automation example --- README.md | 1 + blueprints/automation/sleep_mode.yaml | 1 + custom_components/adaptive_lighting/switch.py | 4 ++ docs/automation-examples.md | 1 + tests/test_automation_examples.py | 51 +++++++++++++++++++ tests/test_switch.py | 28 ++++++++-- 6 files changed, 83 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 3f924fb8..1ea941fd 100644 --- a/README.md +++ b/README.md @@ -316,6 +316,7 @@ Also available as a [blueprint](https://github.com/basnijholt/adaptive-lighting/ ```yaml - alias: "Adaptive lighting: toggle 'sleep mode'" + mode: restart trigger: - platform: state entity_id: input_boolean.sleep_mode diff --git a/blueprints/automation/sleep_mode.yaml b/blueprints/automation/sleep_mode.yaml index fe57079b..62225aed 100644 --- a/blueprints/automation/sleep_mode.yaml +++ b/blueprints/automation/sleep_mode.yaml @@ -39,3 +39,4 @@ actions: - action: "switch.turn_{{ sleep_mode }}" target: entity_id: !input sleep_switches +mode: restart diff --git a/custom_components/adaptive_lighting/switch.py b/custom_components/adaptive_lighting/switch.py index c85087a9..d784f325 100644 --- a/custom_components/adaptive_lighting/switch.py +++ b/custom_components/adaptive_lighting/switch.py @@ -2277,6 +2277,7 @@ class AdaptiveLightingManager: # state can change until the next call), so we just schedule it and let # it sort out by itself. already_applied = get_light_control_attributes(first_service_data) + shared_sleep_time = adaptation_data.sleep_time for index, entity_id in enumerate(entity_ids): self.set_proactively_adapting(call.context.id, entity_id) if index: @@ -2292,6 +2293,9 @@ class AdaptiveLightingManager: if adaptation_data is None or not adaptation_data.max_length: continue self.set_proactively_adapting(adaptation_data.context.id, entity_id) + # Every follow-up waits for the shared first command, even when a + # member's capabilities give it a different number of split phases. + adaptation_data.sleep_time = shared_sleep_time adaptation_data.initial_sleep = True # Don't await to avoid blocking the service call. diff --git a/docs/automation-examples.md b/docs/automation-examples.md index ec5c2831..87ca3aa1 100644 --- a/docs/automation-examples.md +++ b/docs/automation-examples.md @@ -54,6 +54,7 @@ Also available as a [blueprint](https://github.com/basnijholt/adaptive-lighting/ ```yaml - alias: "Adaptive lighting: toggle 'sleep mode'" + mode: restart trigger: - platform: state entity_id: input_boolean.sleep_mode diff --git a/tests/test_automation_examples.py b/tests/test_automation_examples.py index b500f41e..28bd130a 100644 --- a/tests/test_automation_examples.py +++ b/tests/test_automation_examples.py @@ -1237,6 +1237,57 @@ async def test_sleep_toggle_uses_fresh_profile_entity_ids( assert state.state == STATE_OFF +async def test_sleep_toggle_tracks_rapid_helper_changes( + hass: HomeAssistant, + published_automation, +) -> None: + """Keep every sleep switch synchronized when the helper changes rapidly.""" + summary = ( + 'Toggle multiple Adaptive Lighting switches to "sleep mode" using an ' + "input_boolean.sleep_mode." + ) + sleep_switches = ( + "switch.adaptive_lighting_living_room_sleep_mode", + "switch.adaptive_lighting_bedroom_sleep_mode", + ) + automation_config = published_automation( + summary, + "sleep_mode.yaml", + { + "sleep_helper": "input_boolean.sleep_mode", + "sleep_switches": list(sleep_switches), + }, + ) + assert await async_setup_component( + hass, + "input_boolean", + {"input_boolean": {"sleep_mode": {}}}, + ) + await setup_switch(hass, {CONF_NAME: "Living Room"}) + await setup_switch(hass, {CONF_NAME: "Bedroom"}) + await _setup_automation(hass, automation_config) + + for _ in range(10): + await hass.services.async_call( + "input_boolean", + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: "input_boolean.sleep_mode"}, + blocking=True, + ) + await hass.services.async_call( + "input_boolean", + SERVICE_TURN_OFF, + {ATTR_ENTITY_ID: "input_boolean.sleep_mode"}, + blocking=True, + ) + await hass.async_block_till_done() + + for entity_id in sleep_switches: + state = hass.states.get(entity_id) + assert state is not None + assert state.state == STATE_OFF + + async def test_sleep_toggle_applies_restored_state_at_startup( hass: HomeAssistant, published_automation, diff --git a/tests/test_switch.py b/tests/test_switch.py index 0b9129e3..d27aa5f6 100644 --- a/tests/test_switch.py +++ b/tests/test_switch.py @@ -48,6 +48,7 @@ from homeassistant.components.adaptive_lighting.const import ( CONF_MULTI_LIGHT_INTERCEPT, CONF_PREFER_RGB_COLOR, CONF_RESET_MANUAL_CONTROL_ON_SLEEP_MODE_CHANGE, + CONF_SEND_SPLIT_DELAY, CONF_SEPARATE_TURN_ON_COMMANDS, CONF_SKIP_REDUNDANT_COMMANDS, CONF_SLEEP_RGB_OR_COLOR_TEMP, @@ -96,6 +97,7 @@ from homeassistant.components.light import ( ATTR_XY_COLOR, SERVICE_TURN_OFF, ColorMode, + LightEntityFeature, ) from homeassistant.components.light import DOMAIN as LIGHT_DOMAIN from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN @@ -5421,13 +5423,18 @@ async def test_split_command_stays_off_after_turn_off(hass, physical_off): assert hass.states.get(ENTITY_LIGHT_3).state == STATE_OFF -@pytest.mark.parametrize("brightness_only_member", [0, 1]) +@pytest.mark.parametrize( + ("brightness_only_member", "initial_transition", "shared_transition"), + [(0, 0, 0), (1, 0, 0), (0, 0.4, 0.4), (1, 0.4, 0.2)], +) async def test_multi_light_split_with_brightness_only_member( hass, brightness_only_member, + initial_transition, + shared_transition, cleanup, ): - """A brightness-only member must not consume another member's color command.""" + """Each member gets its color command after the shared brightness transition.""" lights = await setup_lights(hass, with_group=True) members = ["light.light_4", "light.light_5"] light = lights[3 + brightness_only_member] @@ -5439,6 +5446,9 @@ async def test_multi_light_split_with_brightness_only_member( light._attr_supported_color_modes = {ColorMode.BRIGHTNESS} light._attr_color_mode = ColorMode.BRIGHTNESS light.async_write_ha_state() + for member in lights[3:5]: + member._attr_supported_features |= LightEntityFeature.TRANSITION + member.async_write_ha_state() _, switch = await setup_switch( hass, { @@ -5446,7 +5456,8 @@ async def test_multi_light_split_with_brightness_only_member( CONF_INTERCEPT: True, CONF_MULTI_LIGHT_INTERCEPT: True, CONF_SEPARATE_TURN_ON_COMMANDS: True, - CONF_INITIAL_TRANSITION: 0, + CONF_INITIAL_TRANSITION: initial_transition, + CONF_SEND_SPLIT_DELAY: 50, }, ) _mock_sun_light_settings( @@ -5457,6 +5468,14 @@ async def test_multi_light_split_with_brightness_only_member( "force_rgb_color": False, }, ) + call_times = [] + loop = asyncio.get_running_loop() + + async def record_call(event): + if event.data["domain"] == LIGHT_DOMAIN: + call_times.append(loop.time()) + + hass.bus.async_listen(EVENT_CALL_SERVICE, record_call) events = await _turn_on_and_track_event_contexts( hass, "mixed_split", @@ -5471,6 +5490,9 @@ async def test_multi_light_split_with_brightness_only_member( if ATTR_COLOR_TEMP_KELVIN in event.data["service_data"] ] assert color_targets == [members[1 - brightness_only_member]] + assert len(call_times) == 2 + # Leave room for event dispatch without accepting overlapping transitions. + assert call_times[1] - call_times[0] >= shared_transition + 0.05 - 0.02 for entity_id in members: state = hass.states.get(entity_id) assert state.state == STATE_ON From 7f7fec4e34d331fa5fd84b95514ddb1baf2a401e Mon Sep 17 00:00:00 2001 From: Bas Nijholt Date: Sun, 6 Sep 2026 22:06:43 +0200 Subject: [PATCH 15/26] chore: release v1.32.0 (#1580) --- custom_components/adaptive_lighting/manifest.json | 2 +- pyproject.toml | 2 +- uv.lock | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/custom_components/adaptive_lighting/manifest.json b/custom_components/adaptive_lighting/manifest.json index 427b730a..db89265b 100644 --- a/custom_components/adaptive_lighting/manifest.json +++ b/custom_components/adaptive_lighting/manifest.json @@ -8,5 +8,5 @@ "iot_class": "calculated", "issue_tracker": "https://github.com/basnijholt/adaptive-lighting/issues", "requirements": ["ulid-transform"], - "version": "1.31.0" + "version": "1.32.0" } diff --git a/pyproject.toml b/pyproject.toml index bdaf9acf..29bee618 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "adaptive-lighting" -version = "1.30.1" +version = "1.32.0" description = "Automatically adjust brightness and color of lights based on the sun position" readme = "README.md" license = "Apache-2.0" diff --git a/uv.lock b/uv.lock index 57564ac4..56d3d2af 100644 --- a/uv.lock +++ b/uv.lock @@ -71,7 +71,7 @@ wheels = [ [[package]] name = "adaptive-lighting" -version = "1.30.1" +version = "1.32.0" source = { editable = "." } [package.dev-dependencies] From 77183ee3eb54e779fff104c99736ddc406e954d8 Mon Sep 17 00:00:00 2001 From: Bas Nijholt Date: Sun, 6 Sep 2026 22:38:25 +0200 Subject: [PATCH 16/26] docs: explain physical turn-ons that require reloading (#1581) * docs: explain physical turn-ons that require reloading * docs: list options that require takeover control --- README.md | 8 ++++++++ docs/troubleshooting.md | 8 ++++++++ 2 files changed, 16 insertions(+) diff --git a/README.md b/README.md index 1ea941fd..6f710516 100644 --- a/README.md +++ b/README.md @@ -762,6 +762,14 @@ represent one sent command or the current desired state. ### :exclamation: Common Problems & Solutions +#### :bulb: Lights Only Adapt After Reloading + +If lights stop adapting after you turn them on with a physical switch or a Zigbee-bound remote, check the Adaptive Lighting switch's `manual_control` attribute. With `take_over_control: true` and `detect_non_ha_changes: false`, a turn-on without a matching Home Assistant `light.turn_on` call marks the light as manually controlled. Reloading clears that state, but the next physical turn-on can trigger it again. + +To adapt these turn-ons while still detecting later manual changes, enable `detect_non_ha_changes` and leave `manual_control_on_external_turn_on` disabled. This requires the light integration to report its state reliably. If you want Adaptive Lighting to keep adapting regardless of manual changes, disable `take_over_control` along with the options that require it: `detect_non_ha_changes`, `adapt_only_on_bare_turn_on`, and `manual_control_on_external_turn_on`. + +This explains the physical-switch case in [#1056](https://github.com/basnijholt/adaptive-lighting/issues/1056), but not every report in that thread. If the light is not listed in `manual_control`, include diagnostics and debug logs from the failed turn-on when reporting it. Lights returning from `unavailable` after a power cut are a separate case from an `off` to `on` state change. + #### :bulb: Lights Not Responding or Turning On by Themselves Adaptive Lighting sends more commands to lights than a typical human user would. If your light control network is unhealthy, you may experience: diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index f39c62bc..f0596563 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -45,6 +45,14 @@ represent one sent command or the current desired state. +#### :bulb: Lights Only Adapt After Reloading + +If lights stop adapting after you turn them on with a physical switch or a Zigbee-bound remote, check the Adaptive Lighting switch's `manual_control` attribute. With `take_over_control: true` and `detect_non_ha_changes: false`, a turn-on without a matching Home Assistant `light.turn_on` call marks the light as manually controlled. Reloading clears that state, but the next physical turn-on can trigger it again. + +To adapt these turn-ons while still detecting later manual changes, enable `detect_non_ha_changes` and leave `manual_control_on_external_turn_on` disabled. This requires the light integration to report its state reliably. If you want Adaptive Lighting to keep adapting regardless of manual changes, disable `take_over_control` along with the options that require it: `detect_non_ha_changes`, `adapt_only_on_bare_turn_on`, and `manual_control_on_external_turn_on`. + +This explains the physical-switch case in [#1056](https://github.com/basnijholt/adaptive-lighting/issues/1056), but not every report in that thread. If the light is not listed in `manual_control`, include diagnostics and debug logs from the failed turn-on when reporting it. Lights returning from `unavailable` after a power cut are a separate case from an `off` to `on` state change. + #### :bulb: Lights Not Responding or Turning On by Themselves Adaptive Lighting sends more commands to lights than a typical human user would. If your light control network is unhealthy, you may experience: From 2299161690922e98fe81c6c70c21a0aa1b36952a Mon Sep 17 00:00:00 2001 From: Bas Nijholt Date: Sun, 6 Sep 2026 22:38:30 +0200 Subject: [PATCH 17/26] docs: clarify persistent sleep mode and daytime dimming (#1582) * docs: clarify persistent sleep mode state * docs: clarify when adaptation targets are available --- docs/advanced/sleep-mode.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/docs/advanced/sleep-mode.md b/docs/advanced/sleep-mode.md index 40736340..9d90c854 100644 --- a/docs/advanced/sleep-mode.md +++ b/docs/advanced/sleep-mode.md @@ -22,6 +22,20 @@ target: entity_id: switch.adaptive_lighting_sleep_mode_living_room ``` +Sleep mode stays active until this switch is turned off. It does not turn off +automatically at sunrise, and Home Assistant restores its previous state after a +restart. Use an automation, such as the sleep-mode blueprint linked under +Automation Examples, when you want the switch to follow a schedule or helper. + +If lights unexpectedly use `sleep_brightness` or `sleep_color_temp` during the +day, first check that the sleep-mode switch is off. While the main Adaptive +Lighting switch is on, it reports the current calculated `brightness_pct` and +`color_temp_kelvin` targets, including the sleep settings while sleep mode is on. +You can compare these attributes with the physical light state. They are `None` +when the main switch is off. In debug logs, +`initial_sleep=True` describes an internal delay before sending a command; it does +not mean that sleep mode is active. + ## Configuration Options Sleep mode is configured through the main Adaptive Lighting configuration. See the [Configuration](../configuration.md) page for the full options table. The sleep-related options are: From 3a27c346b983a7c3491d73b8ad8eacc7dc38d391 Mon Sep 17 00:00:00 2001 From: Bas Nijholt Date: Sun, 6 Sep 2026 22:38:35 +0200 Subject: [PATCH 18/26] test: preserve physical dimming across repeated turn-on calls (#1583) * test: cover repeated bare turn-on after physical dim * test: preserve reported color temperature baseline --- tests/test_switch.py | 82 ++++++++++++++++++++++++++++++++------------ 1 file changed, 61 insertions(+), 21 deletions(-) diff --git a/tests/test_switch.py b/tests/test_switch.py index d27aa5f6..1198f49f 100644 --- a/tests/test_switch.py +++ b/tests/test_switch.py @@ -5099,7 +5099,27 @@ async def test_adapt_only_on_bare_turn_on_respects_pause_changed_mode(hass, inte ) -async def test_detect_non_ha_changes_with_separate_turn_on_commands(hass): +@pytest.mark.parametrize( + ("repeat_bare_turn_on", "mode", "intercept"), + [ + (False, TakeOverControlMode.PAUSE_ALL, False), + (False, TakeOverControlMode.PAUSE_CHANGED, False), + (True, TakeOverControlMode.PAUSE_ALL, True), + (True, TakeOverControlMode.PAUSE_CHANGED, True), + ], + ids=[ + "direct-pause-all-reactive", + "direct-pause-changed-reactive", + "bare-turn-on-pause-all-intercept", + "bare-turn-on-pause-changed-intercept", + ], +) +async def test_detect_non_ha_changes_with_separate_turn_on_commands( + hass, + repeat_bare_turn_on, + mode, + intercept, +): """Regression test for detect_non_ha_changes with separate_turn_on_commands. With separate_turn_on_commands=True, each adaptation cycle makes two sequential @@ -5107,6 +5127,9 @@ async def test_detect_non_ha_changes_with_separate_turn_on_commands(hass): last_service_data instead of merging, brightness is dropped — and _attributes_have_changed silently skips the brightness comparison, so a direct Zigbee brightness change is never detected as manual control. + + A repeated bare light.turn_on from an automation must not hide the physical + change before the periodic adaptation path runs. """ switch, (light, *_) = await setup_lights_and_switch( hass, @@ -5114,10 +5137,21 @@ async def test_detect_non_ha_changes_with_separate_turn_on_commands(hass): CONF_SEPARATE_TURN_ON_COMMANDS: True, CONF_DETECT_NON_HA_CHANGES: True, CONF_TAKE_OVER_CONTROL: True, + CONF_TAKE_OVER_CONTROL_MODE: mode, + CONF_INTERCEPT: intercept, }, ) - context = switch.create_context("test") + _mock_sun_light_settings( + switch, + { + ATTR_BRIGHTNESS_PCT: 50, + ATTR_COLOR_TEMP_KELVIN: 3000, + "force_rgb_color": False, + }, + ) + + context = switch.create_context("interval") async def update(force: bool = False): await switch._update_attrs_and_maybe_adapt_lights( @@ -5129,17 +5163,10 @@ async def test_detect_non_ha_changes_with_separate_turn_on_commands(hass): await update(force=True) - last_sd = switch.manager.last_service_data.get(ENTITY_LIGHT_1) - assert last_sd is not None, "last_service_data not set after force adapt" - assert ( - ATTR_BRIGHTNESS in last_sd - ), f"brightness missing from last_service_data after split calls: {last_sd}" - assert ( - ATTR_COLOR_TEMP_KELVIN in last_sd or ATTR_RGB_COLOR in last_sd - ), f"color missing from last_service_data after split calls: {last_sd}" - al_brightness = light.brightness assert al_brightness is not None + al_color_temp = light.color_temp_kelvin + assert al_color_temp is not None switch.manager.manual_control[ENTITY_LIGHT_1] = LightControlAttributes.NONE manual_brightness = ( @@ -5147,6 +5174,24 @@ async def test_detect_non_ha_changes_with_separate_turn_on_commands(hass): ) set_light_brightness(light, manual_brightness) + if repeat_bare_turn_on: + await hass.services.async_call( + LIGHT_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: light.entity_id}, + blocking=True, + ) + await hass.async_block_till_done() + + _mock_sun_light_settings( + switch, + { + ATTR_BRIGHTNESS_PCT: 50, + ATTR_COLOR_TEMP_KELVIN: 4000, + "force_rgb_color": False, + }, + ) + async def _flush_attr_state(hass, entity_id): """Mimic a ZHA attribute report: write current hardware state to HA.""" light.async_write_ha_state() @@ -5156,20 +5201,15 @@ async def test_detect_non_ha_changes_with_separate_turn_on_commands(hass): new=AsyncMock(side_effect=_flush_attr_state), ): await update(force=False) - - assert LightControlAttributes.BRIGHTNESS in switch.manager.manual_control.get( - ENTITY_LIGHT_1, - LightControlAttributes.NONE, - ), ( - f"manual_control={switch.manager.manual_control.get(ENTITY_LIGHT_1)}, " - f"last_service_data={switch.manager.last_service_data.get(ENTITY_LIGHT_1)}" - ) - await update(force=False) assert ( light.brightness == manual_brightness - ), f"AL overrode manual brightness {manual_brightness} with {al_brightness}" + ), f"AL overrode manual brightness {manual_brightness} with {light.brightness}" + expected_color_temp = ( + 4000 if mode == TakeOverControlMode.PAUSE_CHANGED else al_color_temp + ) + assert light.color_temp_kelvin == expected_color_temp async def test_fresh_install_entity_ids(hass): From a936519866fea7ab49b3b64e6b0f83aa5ed6a18b Mon Sep 17 00:00:00 2001 From: Bas Nijholt Date: Mon, 7 Sep 2026 07:41:28 +0200 Subject: [PATCH 19/26] fix: track mixed targets during light turn-off (#1584) --- .../adaptive_lighting/hass_utils.py | 33 ++- custom_components/adaptive_lighting/switch.py | 100 +++++---- tests/test_switch.py | 197 ++++++++++++++++++ 3 files changed, 276 insertions(+), 54 deletions(-) diff --git a/custom_components/adaptive_lighting/hass_utils.py b/custom_components/adaptive_lighting/hass_utils.py index 550ae350..822e2e29 100644 --- a/custom_components/adaptive_lighting/hass_utils.py +++ b/custom_components/adaptive_lighting/hass_utils.py @@ -4,31 +4,30 @@ import logging from collections.abc import Awaitable, Callable from homeassistant.core import HomeAssistant, ServiceCall -from homeassistant.helpers import device_registry, entity_registry +from homeassistant.helpers.target import async_extract_referenced_entity_ids from homeassistant.util.read_only_dict import ReadOnlyDict +try: + from homeassistant.helpers.target import TargetSelection +except ImportError: # Compatibility with older Home Assistant releases + from homeassistant.helpers.target import TargetSelectorData as TargetSelection + from .adaptation_utils import ServiceData _LOGGER = logging.getLogger(__name__) -def area_entities(hass: HomeAssistant, area_id: str): - """Get all entities linked to an area.""" - ent_reg = entity_registry.async_get(hass) - entity_ids = [ - entry.entity_id - for entry in entity_registry.async_entries_for_area(ent_reg, area_id) - ] - dev_reg = device_registry.async_get(hass) - entity_ids.extend( - [ - entity.entity_id - for device in device_registry.async_entries_for_area(dev_reg, area_id) - for entity in entity_registry.async_entries_for_device(ent_reg, device.id) - if entity.area_id is None - ], +def target_entities( + hass: HomeAssistant, + service_data: ServiceData, +) -> set[str]: + """Resolve all directly and indirectly targeted entities without groups.""" + selected = async_extract_referenced_entity_ids( + hass, + TargetSelection(service_data), + expand_group=False, ) - return entity_ids + return selected.referenced | selected.indirectly_referenced def setup_service_call_interceptor( diff --git a/custom_components/adaptive_lighting/switch.py b/custom_components/adaptive_lighting/switch.py index d784f325..a22c8cb4 100644 --- a/custom_components/adaptive_lighting/switch.py +++ b/custom_components/adaptive_lighting/switch.py @@ -11,7 +11,6 @@ from copy import deepcopy from datetime import timedelta from typing import TYPE_CHECKING, Any -import homeassistant.helpers.config_validation as cv import homeassistant.util.dt as dt_util import ulid_transform from homeassistant.components.light import ( @@ -32,8 +31,11 @@ from homeassistant.components.switch import SwitchEntity from homeassistant.config_entries import SOURCE_IMPORT from homeassistant.const import ( ATTR_AREA_ID, + ATTR_DEVICE_ID, ATTR_DOMAIN, ATTR_ENTITY_ID, + ATTR_FLOOR_ID, + ATTR_LABEL_ID, ATTR_SERVICE, ATTR_SERVICE_DATA, ATTR_SUPPORTED_FEATURES, @@ -149,7 +151,7 @@ from .const import ( change_switch_settings_schema, replace_none_str, ) -from .hass_utils import area_entities, setup_service_call_interceptor +from .hass_utils import setup_service_call_interceptor, target_entities from .helpers import ( clamp, color_difference_redmean, @@ -1970,13 +1972,6 @@ class AdaptiveLightingManager: self._context_cnt += 1 return context - def _is_excluded_from_area(self, entity_id: str) -> bool: - """Match Home Assistant's exclusions for indirect area targets.""" - entry = entity_registry.async_get(self.hass).async_get(entity_id) - return entry is not None and ( - entry.entity_category is not None or entry.hidden_by is not None - ) - def _separate_entity_ids( self, entity_ids: list[str], @@ -2160,8 +2155,14 @@ class AdaptiveLightingManager: entity_ids: list[str], ) -> dict[str, Any]: """Modify the service data to contain the entity IDs.""" - service_data.pop(ATTR_ENTITY_ID, None) - service_data.pop(ATTR_AREA_ID, None) + for target_key in ( + ATTR_ENTITY_ID, + ATTR_AREA_ID, + ATTR_DEVICE_ID, + ATTR_FLOOR_ID, + ATTR_LABEL_ID, + ): + service_data.pop(target_key, None) service_data[ATTR_ENTITY_ID] = entity_ids return service_data @@ -2633,31 +2634,11 @@ class AdaptiveLightingManager: records.pop(light, None) def _get_entity_list(self, service_data: ServiceData) -> list[str]: - if ATTR_ENTITY_ID in service_data: - return cv.ensure_list_csv(service_data[ATTR_ENTITY_ID]) - if ATTR_AREA_ID in service_data: - entity_ids: list[str] = [] - area_ids: list[str] = cv.ensure_list_csv(service_data[ATTR_AREA_ID]) - for area_id in area_ids: - area_entity_ids = area_entities(self.hass, area_id) - eids = [ - entity_id - for entity_id in area_entity_ids - if entity_id.startswith(LIGHT_DOMAIN) - and not self._is_excluded_from_area(entity_id) - ] - entity_ids.extend(eids) - _LOGGER.debug( - "Found entity_ids '%s' for area_id '%s'", - entity_ids, - area_id, - ) - return entity_ids - _LOGGER.debug( - "No entity_ids or area_ids found in service_data: %s", - service_data, + return sorted( + entity_id + for entity_id in target_entities(self.hass, service_data) + if entity_id.startswith(f"{LIGHT_DOMAIN}.") ) - return [] async def turn_on_off_event_listener(self, event: Event) -> None: """Track 'light.turn_off' and 'light.turn_on' service calls.""" @@ -3052,7 +3033,7 @@ class AdaptiveLightingManager: def _member_turn_on_explains_group_turn_on( self, entity_id: str, - on_to_off_event: Event[EventStateChangedData], + off_event: Event, off_to_on_event: Event[EventStateChangedData], ) -> bool: """Check if a light group's 'off' → 'on' is caused by a member's 'light.turn_on'. @@ -3072,7 +3053,7 @@ class AdaptiveLightingManager: member_turn_on = self.turn_on_event.get(member) if ( member_turn_on is not None - and on_to_off_event.time_fired + and off_event.time_fired < member_turn_on.time_fired <= off_to_on_event.time_fired ): @@ -3087,6 +3068,49 @@ class AdaptiveLightingManager: return True return False + def _off_to_on_event_is_during_turn_off( + self, + entity_id: str, + off_to_on_event: Event[EventStateChangedData], + ) -> bool: + """Check if a reported turn-on belongs to a recent turn-off window.""" + turn_off_event = self.turn_off_event.get(entity_id) + if ( + turn_off_event is None + or off_to_on_event.context.id != turn_off_event.context.id + ): + return False + + turn_on_event = self.turn_on_event.get(entity_id) + if ( + turn_on_event is not None + and turn_off_event.time_fired + < turn_on_event.time_fired + <= off_to_on_event.time_fired + ): + return False + if self._member_turn_on_explains_group_turn_on( + entity_id, + turn_off_event, + off_to_on_event, + ): + return False + + transition = turn_off_event.data[ATTR_SERVICE_DATA].get(ATTR_TRANSITION) + delay = max(transition or 0, TURNING_OFF_DELAY) + elapsed = (dt_util.utcnow() - turn_off_event.time_fired).total_seconds() + if not 0 <= elapsed <= delay: + return False + + _LOGGER.debug( + "just_turned_off: Fresh 'light.turn_off' for '%s' shares the" + " 'off' → 'on' context; ignoring the state during its %s second" + " transition window.", + entity_id, + delay, + ) + return True + async def just_turned_off( # noqa: PLR0911, PLR0912 self, entity_id: str, @@ -3105,6 +3129,8 @@ class AdaptiveLightingManager: """ off_to_on_event = self.off_to_on_event[entity_id] on_to_off_event = self.on_to_off_event.get(entity_id) + if self._off_to_on_event_is_during_turn_off(entity_id, off_to_on_event): + return True if on_to_off_event is None: _LOGGER.debug( diff --git a/tests/test_switch.py b/tests/test_switch.py index 1198f49f..5db7c9a5 100644 --- a/tests/test_switch.py +++ b/tests/test_switch.py @@ -108,6 +108,8 @@ from homeassistant.const import ( ATTR_AREA_ID, ATTR_DEVICE_ID, ATTR_ENTITY_ID, + ATTR_FLOOR_ID, + ATTR_LABEL_ID, ATTR_SUPPORTED_FEATURES, CONF_LIGHTS, CONF_NAME, @@ -4251,6 +4253,27 @@ def _turn_on_service_event(entity_ids: list[str], ts: float, context: Context) - ) +def _turn_off_service_event( + entity_ids: list[str], + ts: float, + context: Context, + transition: float, +) -> Event: + return Event( + EVENT_CALL_SERVICE, + { + "domain": LIGHT_DOMAIN, + "service": SERVICE_TURN_OFF, + "service_data": { + ATTR_ENTITY_ID: entity_ids, + ATTR_TRANSITION: transition, + }, + }, + time_fired_timestamp=ts, + context=context, + ) + + async def test_just_turned_off_group_context_reuse(hass, cleanup): """Group 'off' → 'on' with a reused 'turn_off' context must still adapt. @@ -4309,6 +4332,154 @@ async def test_just_turned_off_group_context_reuse(hass, cleanup): assert await manager.just_turned_off(group) +def _register_mixed_target_lights( + hass, + device_registry, + floor_registry, + label_registry, +): + """Assign the three test lights to mixed indirect HA targets.""" + floor = floor_registry.async_create("Upstairs") + area_registry = ar.async_get(hass) + upstairs_area = area_registry.async_create( + "Upstairs room", + floor_id=floor.floor_id, + ) + hall_area = area_registry.async_create("Hall") + + config_entry = MockConfigEntry(domain="test") + config_entry.add_to_hass(hass) + device = device_registry.async_get_or_create( + config_entry_id=config_entry.entry_id, + identifiers={("test", "device-target")}, + ) + label = label_registry.async_create("Skipped light") + + registry = entity_registry.async_get(hass) + registry.async_update_entity(ENTITY_LIGHT_1, area_id=upstairs_area.id) + registry.async_update_entity(ENTITY_LIGHT_2, area_id=hall_area.id) + registry.async_update_entity( + ENTITY_LIGHT_3, + device_id=device.id, + labels={label.label_id}, + ) + return { + ATTR_FLOOR_ID: floor.floor_id, + ATTR_AREA_ID: hall_area.id, + ATTR_DEVICE_ID: device.id, + ATTR_LABEL_ID: label.label_id, + } + + +async def test_mixed_turn_off_targets_do_not_readapt_off_device_light( + hass, + device_registry, + floor_registry, + label_registry, + cleanup, +): + """A mixed-target turn-off must cover an already-off device light (#1069).""" + await setup_lights(hass) + targets = _register_mixed_target_lights( + hass, + device_registry, + floor_registry, + label_registry, + ) + targets.pop(ATTR_LABEL_ID) + + _, switch = await setup_switch( + hass, + { + CONF_LIGHTS: [ENTITY_LIGHT_1, ENTITY_LIGHT_2, ENTITY_LIGHT_3], + CONF_DETECT_NON_HA_CHANGES: True, + CONF_INTERCEPT: True, + CONF_INITIAL_TRANSITION: 0, + }, + ) + assert hass.states.is_state(ENTITY_LIGHT_3, STATE_OFF) + + turn_off_context = Context() + await hass.services.async_call( + LIGHT_DOMAIN, + SERVICE_TURN_OFF, + { + **targets, + ATTR_TRANSITION: 10, + }, + blocking=True, + context=turn_off_context, + ) + await hass.async_block_till_done() + + calls = _track_adaptive_light_calls(hass) + off_state = hass.states.get(ENTITY_LIGHT_3) + assert off_state is not None + hass.states.async_set( + ENTITY_LIGHT_3, + STATE_ON, + off_state.attributes, + context=turn_off_context, + ) + await hass.async_block_till_done() + + assert not calls + + +async def test_intercept_replaces_all_mixed_target_selectors( + hass, + device_registry, + floor_registry, + label_registry, + cleanup, +): + """A narrowed intercepted call must not retain indirect target selectors.""" + lights = await setup_lights(hass) + targets = _register_mixed_target_lights( + hass, + device_registry, + floor_registry, + label_registry, + ) + await hass.services.async_call( + LIGHT_DOMAIN, + SERVICE_TURN_OFF, + { + ATTR_ENTITY_ID: [ENTITY_LIGHT_1, ENTITY_LIGHT_2, ENTITY_LIGHT_3], + }, + blocking=True, + ) + await setup_switch( + hass, + { + CONF_LIGHTS: [ENTITY_LIGHT_1, ENTITY_LIGHT_2], + CONF_INTERCEPT: True, + CONF_MULTI_LIGHT_INTERCEPT: True, + CONF_INITIAL_TRANSITION: 0, + CONF_MIN_BRIGHTNESS: 50, + CONF_MAX_BRIGHTNESS: 50, + }, + ) + + with patch.object( + lights[2], + "async_turn_on", + wraps=lights[2].async_turn_on, + ) as skipped_turn_on: + await hass.services.async_call( + LIGHT_DOMAIN, + SERVICE_TURN_ON, + {**targets, ATTR_BRIGHTNESS: 200}, + blocking=True, + ) + await hass.async_block_till_done() + + assert hass.states.get(ENTITY_LIGHT_1).attributes[ATTR_BRIGHTNESS] == 128 + assert hass.states.get(ENTITY_LIGHT_2).attributes[ATTR_BRIGHTNESS] == 128 + skipped_turn_on.assert_awaited_once() + assert skipped_turn_on.call_args.kwargs[ATTR_BRIGHTNESS] == 200 + + async def test_just_turned_off_same_automation_context(hass, cleanup): """'turn_off' and 'turn_on' from one automation share a context. @@ -4325,6 +4496,12 @@ async def test_just_turned_off_same_automation_context(hass, cleanup): now = dt_util.utcnow().timestamp() automation_context = Context() + manager.turn_off_event[ENTITY_LIGHT_1] = _turn_off_service_event( + [ENTITY_LIGHT_1], + now - 2, + automation_context, + transition=10, + ) manager.on_to_off_event[ENTITY_LIGHT_1] = _state_changed_event( ENTITY_LIGHT_1, now - 2, @@ -4363,6 +4540,26 @@ async def test_just_turned_off_same_automation_context(hass, cleanup): ) assert await manager.just_turned_off(ENTITY_LIGHT_1) + # A later physical turn-on has a fresh context and must not remain blocked by + # the old turn-off record after its transition window has elapsed. + manager.on_to_off_event[ENTITY_LIGHT_1] = _state_changed_event( + ENTITY_LIGHT_1, + now - 20, + automation_context, + ) + manager.turn_off_event[ENTITY_LIGHT_1] = _turn_off_service_event( + [ENTITY_LIGHT_1], + now - 20, + automation_context, + transition=10, + ) + manager.off_to_on_event[ENTITY_LIGHT_1] = _state_changed_event( + ENTITY_LIGHT_1, + now, + Context(), + ) + assert not await manager.just_turned_off(ENTITY_LIGHT_1) + async def test_just_turned_off_group_context_reuse_end_to_end(hass, cleanup): """A tracked member turn-on explains a group's reused OFF context (#1378).""" From 34356a6b56e08b2d82207d382a0e786b553753a4 Mon Sep 17 00:00:00 2001 From: Bas Nijholt Date: Mon, 7 Sep 2026 08:01:35 +0200 Subject: [PATCH 20/26] ci: validate README TOC before merging (#1586) --- .github/workflows/toc.yaml | 12 ------------ .pre-commit-config.yaml | 6 ++++++ README.md | 1 + 3 files changed, 7 insertions(+), 12 deletions(-) delete mode 100644 .github/workflows/toc.yaml diff --git a/.github/workflows/toc.yaml b/.github/workflows/toc.yaml deleted file mode 100644 index cde1b6d4..00000000 --- a/.github/workflows/toc.yaml +++ /dev/null @@ -1,12 +0,0 @@ -on: - push: - branches: [main] -name: TOC Generator -jobs: - generateTOC: - name: TOC Generator - runs-on: ubuntu-latest - steps: - - uses: technote-space/toc-generator@v4.3.1 - with: - TOC_TITLE: "" diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index b5cd6d52..53b84021 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -7,6 +7,12 @@ repos: - id: end-of-file-fixer - id: mixed-line-ending args: ["--fix=lf"] + - repo: https://github.com/thlorenz/doctoc + rev: v2.5.0 + hooks: + - id: doctoc + files: ^README[^/]*\.md$ + args: ["--notitle"] - repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.16.5 hooks: diff --git a/README.md b/README.md index 6f710516..0736b56a 100644 --- a/README.md +++ b/README.md @@ -84,6 +84,7 @@ The attributes are absent when the Adaptive Lighting switch is off. Use a fallba - [Additional Information](#additional-information) - [:sos: Troubleshooting](#sos-troubleshooting) - [:exclamation: Common Problems & Solutions](#exclamation-common-problems--solutions) + - [:bulb: Lights Only Adapt After Reloading](#bulb-lights-only-adapt-after-reloading) - [:bulb: Lights Not Responding or Turning On by Themselves](#bulb-lights-not-responding-or-turning-on-by-themselves) - [:signal_strength: WiFi Networks](#signal_strength-wifi-networks) - [:spider_web: Zigbee, Z-Wave, and Other Mesh Networks](#spider_web-zigbee-z-wave-and-other-mesh-networks) From 2f37b6ea4070e2b9b0637acc3ca2a2aab9252405 Mon Sep 17 00:00:00 2001 From: Bas Nijholt Date: Mon, 7 Sep 2026 09:03:03 +0200 Subject: [PATCH 21/26] Fix pending adaptations after light or profile removal (#1587) --- custom_components/adaptive_lighting/switch.py | 19 +- tests/test_switch.py | 245 ++++++++++++++++++ 2 files changed, 261 insertions(+), 3 deletions(-) diff --git a/custom_components/adaptive_lighting/switch.py b/custom_components/adaptive_lighting/switch.py index a22c8cb4..871dcf03 100644 --- a/custom_components/adaptive_lighting/switch.py +++ b/custom_components/adaptive_lighting/switch.py @@ -886,6 +886,7 @@ class AdaptiveSwitch(SwitchEntity, RestoreEntity): assert hass is not None self.hass = hass self.manager = manager + self._removed = False self.sleep_mode_switch = sleep_mode_switch self.adapt_color_switch = adapt_color_switch self.adapt_brightness_switch = adapt_brightness_switch @@ -1078,6 +1079,7 @@ class AdaptiveSwitch(SwitchEntity, RestoreEntity): async def async_will_remove_from_hass(self) -> None: """Remove the listeners upon removing the component.""" + self._removed = True self._remove_listeners() def _resolve_lights(self, lights: list[str] | None = None) -> list[str]: @@ -1433,6 +1435,9 @@ class AdaptiveSwitch(SwitchEntity, RestoreEntity): if not is_first_call or data.initial_sleep: await asyncio.sleep(data.sleep_time) + if self._removed: + return + # Instead of directly iterating the generator in the while-loop, we get # the next item here after the sleep to make sure it incorporates state # changes which happened during the sleep. @@ -1488,6 +1493,9 @@ class AdaptiveSwitch(SwitchEntity, RestoreEntity): Wraps the sequence of service calls in a task that can be cancelled from elsewhere, e.g., to cancel an ongoing adaptation when a light is turned off. """ + if self._removed: + return + # Prevent overlap of multiple adaptation sequences self.manager.cancel_ongoing_adaptation_calls(data.entity_id) _LOGGER.debug( @@ -1691,7 +1699,7 @@ class AdaptiveSwitch(SwitchEntity, RestoreEntity): await asyncio.sleep(self._adapt_delay) # Runtime settings may retire this profile's target while the event waits. - if entity_id not in self.lights: + if self._removed or entity_id not in self.lights: return await self._update_attrs_and_maybe_adapt_lights( @@ -1705,7 +1713,8 @@ class AdaptiveSwitch(SwitchEntity, RestoreEntity): self, event: Event[EventStateChangedData], ) -> None: - if not _is_state_event(event, (STATE_ON, STATE_OFF)): + new_state = event.data.get("new_state") + if new_state is None or new_state.state not in (STATE_ON, STATE_OFF): _LOGGER.debug("%s: Ignoring sleep event %s", self._name, event) return _LOGGER.debug( @@ -2730,7 +2739,7 @@ class AdaptiveLightingManager: elif state.state == STATE_OFF: # is turning on await on(eid, event) - async def state_changed_event_listener( + async def state_changed_event_listener( # noqa: PLR0912 self, event: Event[EventStateChangedData], ) -> None: @@ -2808,6 +2817,10 @@ class AdaptiveLightingManager: new_on.context.id, ) + if old_on and not new_on: + # Availability loss invalidates pending commands, not manual state. + self.cancel_ongoing_adaptation_calls(entity_id) + if old_on and new_off: # Tracks 'on' → 'off' state changes self.on_to_off_event[entity_id] = event diff --git a/tests/test_switch.py b/tests/test_switch.py index 5db7c9a5..6efe68d5 100644 --- a/tests/test_switch.py +++ b/tests/test_switch.py @@ -30,6 +30,7 @@ from homeassistant.components.adaptive_lighting.const import ( ATTR_ADAPT_BRIGHTNESS, ATTR_ADAPT_COLOR, ATTR_ADAPTIVE_LIGHTING_MANAGER, + CONF_ADAPT_DELAY, CONF_ADAPT_ONLY_ON_BARE_TURN_ON, CONF_ADAPT_UNTIL_SLEEP, CONF_AUTORESET_CONTROL, @@ -46,6 +47,7 @@ from homeassistant.components.adaptive_lighting.const import ( CONF_MIN_BRIGHTNESS, CONF_MIN_COLOR_TEMP, CONF_MULTI_LIGHT_INTERCEPT, + CONF_ONLY_ONCE, CONF_PREFER_RGB_COLOR, CONF_RESET_MANUAL_CONTROL_ON_SLEEP_MODE_CHANGE, CONF_SEND_SPLIT_DELAY, @@ -119,6 +121,7 @@ from homeassistant.const import ( SERVICE_TURN_ON, STATE_OFF, STATE_ON, + STATE_UNAVAILABLE, EntityCategory, ) from homeassistant.core import Context, CoreState, Event, HomeAssistant, State @@ -5988,3 +5991,245 @@ async def test_shared_profiles_keep_independent_sun_schedules( noon = hass.states.get(ENTITY_LIGHT_1) assert noon.attributes[ATTR_BRIGHTNESS] == 77 assert noon.attributes[ATTR_COLOR_TEMP_KELVIN] > 2000 + + +@pytest.mark.parametrize("via_unavailable", [False, True]) +async def test_split_adaptation_cancelled_after_physical_off( + hass, + monkeypatch, + via_unavailable, +): + """Pending split commands must not resurrect a physically switched-off light.""" + switch, _ = await setup_lights_and_switch( + hass, + { + CONF_DETECT_NON_HA_CHANGES: True, + CONF_ONLY_ONCE: True, + CONF_SEPARATE_TURN_ON_COMMANDS: True, + CONF_SEND_SPLIT_DELAY: 1234, + CONF_INITIAL_TRANSITION: 0, + CONF_MIN_BRIGHTNESS: 50, + CONF_MAX_BRIGHTNESS: 50, + }, + ) + state = hass.states.get(ENTITY_LIGHT_1) + hass.states.async_set(ENTITY_LIGHT_1, STATE_OFF, state.attributes) + await hass.async_block_till_done() + # Isolate the split-command lifetime from the separate turn-off debounce. + monkeypatch.setattr( + switch.manager, + "just_turned_off", + AsyncMock(return_value=False), + ) + entered, release = asyncio.Event(), asyncio.Event() + original_sleep = asyncio.sleep + + async def controlled_sleep(delay, *args, **kwargs): + if delay == 1.234: + entered.set() + await release.wait() + else: + await original_sleep(delay, *args, **kwargs) + + monkeypatch.setattr(asyncio, "sleep", controlled_sleep) + calls = _track_adaptive_light_calls(hass) + hass.states.async_set(ENTITY_LIGHT_1, STATE_ON, state.attributes) + await asyncio.wait_for(entered.wait(), 2) + assert len(calls) == 1 + if via_unavailable: + hass.states.async_set(ENTITY_LIGHT_1, STATE_UNAVAILABLE, state.attributes) + await original_sleep(0) + hass.states.async_set(ENTITY_LIGHT_1, STATE_OFF, state.attributes) + await original_sleep(0) + release.set() + await hass.async_block_till_done() + assert len(calls) == 1, f"Physical OFF resurrected by split command: {calls}" + assert hass.states.get(ENTITY_LIGHT_1).state == STATE_OFF + + +@pytest.mark.parametrize("remaining_profile", [False, True]) +async def test_profile_unloaded_during_adapt_delay( + hass, + monkeypatch, + remaining_profile, +): + """A removed profile must not send commands after its adaptation delay.""" + switch, _ = await setup_lights_and_switch( + hass, + { + CONF_DETECT_NON_HA_CHANGES: True, + CONF_ONLY_ONCE: True, + CONF_ADAPT_DELAY: 0.1234, + }, + ) + if remaining_profile: + _, other = await setup_switch( + hass, + { + CONF_NAME: "remaining", + CONF_LIGHTS: [ENTITY_LIGHT_1], + CONF_ONLY_ONCE: True, + CONF_INITIAL_TRANSITION: 0, + }, + ) + await other.async_turn_off() + state = hass.states.get(ENTITY_LIGHT_1) + hass.states.async_set(ENTITY_LIGHT_1, STATE_OFF, state.attributes) + await hass.async_block_till_done() + monkeypatch.setattr( + switch.manager, + "just_turned_off", + AsyncMock(return_value=False), + ) + entered, release = asyncio.Event(), asyncio.Event() + original_sleep = asyncio.sleep + + async def controlled_sleep(delay, *args, **kwargs): + if delay == 0.1234: + entered.set() + await release.wait() + else: + await original_sleep(delay, *args, **kwargs) + + monkeypatch.setattr(asyncio, "sleep", controlled_sleep) + calls = _track_adaptive_light_calls(hass) + hass.states.async_set(ENTITY_LIGHT_1, STATE_ON, state.attributes) + await asyncio.wait_for(entered.wait(), 2) + entry = hass.config_entries.async_entries(DOMAIN)[0] + await hass.config_entries.async_unload(entry.entry_id) + calls.clear() + release.set() + await hass.async_block_till_done() + assert calls == [] + if remaining_profile: + await other.async_turn_on() + await other._update_attrs_and_maybe_adapt_lights( + context=other.create_context("test"), + lights=[ENTITY_LIGHT_1], + force=True, + ) + await hass.async_block_till_done() + assert calls + assert hass.states.get(ENTITY_LIGHT_1).state == STATE_ON + + +async def test_profile_unloaded_during_split_delay(hass, monkeypatch): + """Removed profiles must not send remaining split commands.""" + switch, _ = await setup_lights_and_switch( + hass, + { + CONF_DETECT_NON_HA_CHANGES: True, + CONF_ONLY_ONCE: True, + CONF_SEPARATE_TURN_ON_COMMANDS: True, + CONF_SEND_SPLIT_DELAY: 1234, + CONF_INITIAL_TRANSITION: 0, + CONF_MIN_BRIGHTNESS: 50, + CONF_MAX_BRIGHTNESS: 50, + }, + ) + state = hass.states.get(ENTITY_LIGHT_1) + hass.states.async_set(ENTITY_LIGHT_1, STATE_OFF, state.attributes) + await hass.async_block_till_done() + # Isolate the split-command lifetime from the separate turn-off debounce. + monkeypatch.setattr( + switch.manager, + "just_turned_off", + AsyncMock(return_value=False), + ) + entered, release = asyncio.Event(), asyncio.Event() + original_sleep = asyncio.sleep + + async def controlled_sleep(delay, *args, **kwargs): + if delay == 1.234: + entered.set() + await release.wait() + else: + await original_sleep(delay, *args, **kwargs) + + monkeypatch.setattr(asyncio, "sleep", controlled_sleep) + calls = _track_adaptive_light_calls(hass) + hass.states.async_set(ENTITY_LIGHT_1, STATE_ON, state.attributes) + await asyncio.wait_for(entered.wait(), 2) + assert len(calls) == 1 + entry = hass.config_entries.async_entries(DOMAIN)[0] + assert await hass.config_entries.async_unload(entry.entry_id) + release.set() + await hass.async_block_till_done() + assert len(calls) == 1 + assert hass.states.get(ENTITY_LIGHT_1).state == STATE_ON + + +@pytest.mark.parametrize("unload_before_split", [False, True]) +async def test_unloaded_polling_profile_preserves_other_split_adaptation( + hass, + monkeypatch, + unload_before_split, +): + """A removed profile resuming a poll must not cancel another profile's work.""" + switch, _ = await setup_lights_and_switch(hass, {CONF_ONLY_ONCE: True}) + _, other = await setup_switch( + hass, + { + CONF_NAME: "remaining", + CONF_LIGHTS: [ENTITY_LIGHT_1], + CONF_ONLY_ONCE: True, + CONF_SEPARATE_TURN_ON_COMMANDS: True, + CONF_SEND_SPLIT_DELAY: 1234, + CONF_INITIAL_TRANSITION: 0, + }, + ) + poll_entered, poll_release = asyncio.Event(), asyncio.Event() + split_entered, split_release = asyncio.Event(), asyncio.Event() + original_update = switch.manager.update_manually_controlled_from_untracked_change + original_sleep = asyncio.sleep + + async def delayed_update(profile, *args, **kwargs): + if profile is switch: + poll_entered.set() + await poll_release.wait() + await original_update(profile, *args, **kwargs) + + async def controlled_sleep(delay, *args, **kwargs): + if delay == 1.234: + split_entered.set() + await split_release.wait() + else: + await original_sleep(delay, *args, **kwargs) + + monkeypatch.setattr( + switch.manager, + "update_manually_controlled_from_untracked_change", + delayed_update, + ) + monkeypatch.setattr(asyncio, "sleep", controlled_sleep) + calls = _track_adaptive_light_calls(hass) + polling = hass.async_create_task( + switch._update_attrs_and_maybe_adapt_lights( + context=switch.create_context("test"), + lights=[ENTITY_LIGHT_1], + force=True, + ), + ) + await asyncio.wait_for(poll_entered.wait(), 2) + entry = hass.config_entries.async_entries(DOMAIN)[0] + if unload_before_split: + assert await hass.config_entries.async_unload(entry.entry_id) + adapting = hass.async_create_task( + other._adapt_light( + ENTITY_LIGHT_1, + other.create_context("test"), + 0, + force=True, + ), + ) + await asyncio.wait_for(split_entered.wait(), 2) + assert len(calls) == 1 + if not unload_before_split: + assert await hass.config_entries.async_unload(entry.entry_id) + poll_release.set() + await polling + split_release.set() + await adapting + await hass.async_block_till_done() + assert len(calls) == 2 + assert ATTR_COLOR_TEMP_KELVIN in calls[-1] From 7c445af63bf2684f1b21d1fcb8094fa1f59088aa Mon Sep 17 00:00:00 2001 From: "allcontributors[bot]" <46447321+allcontributors[bot]@users.noreply.github.com> Date: Tue, 8 Sep 2026 13:54:05 +0200 Subject: [PATCH 22/26] docs: add ahmadtawakol as a contributor for code, bug, and maintenance (#1595) * docs: update README.md * docs: update .all-contributorsrc --------- Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com> --- .all-contributorsrc | 11 +++++++++++ README.md | 3 ++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/.all-contributorsrc b/.all-contributorsrc index 6004155e..fbff14b8 100644 --- a/.all-contributorsrc +++ b/.all-contributorsrc @@ -1568,6 +1568,17 @@ "contributions": [ "ideas" ] + }, + { + "login": "ahmadtawakol", + "name": "Ahmad Tawakol", + "avatar_url": "https://avatars.githubusercontent.com/u/2355493?v=4", + "profile": "https://github.com/ahmadtawakol", + "contributions": [ + "code", + "bug", + "maintenance" + ] } ], "contributorsPerLine": 7, diff --git a/README.md b/README.md index 0736b56a..89685620 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ [![hacs_badge](https://img.shields.io/badge/HACS-Default-orange.svg?style=for-the-badge)](https://github.com/hacs/integration) ![Version](https://img.shields.io/github/v/release/basnijholt/adaptive-lighting?style=for-the-badge) -[![All Contributors](https://img.shields.io/badge/all_contributors-172-orange.svg?style=flat-square)](#contributors-) +[![All Contributors](https://img.shields.io/badge/all_contributors-173-orange.svg?style=flat-square)](#contributors-) # 🌞 Adaptive Lighting: Enhance Your Home's Atmosphere with Smart, Sun-Synchronized Lighting 🌙 @@ -1118,6 +1118,7 @@ Notice the values of `brightness_mode_time_light` and `brightness_mode_time_dark Leonhard Hesse
Leonhard Hesse

💻 Tim Stallmann
Tim Stallmann

💻 lehneres
lehneres

🤔 + Ahmad Tawakol
Ahmad Tawakol

💻 🐛 🚧 From 51ea83dba3bc1de7a3a36736de6e8ff34ccc5284 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 8 Sep 2026 14:02:08 +0200 Subject: [PATCH 23/26] [pre-commit.ci] pre-commit autoupdate (#1592) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [pre-commit.ci] pre-commit autoupdate updates: - [github.com/astral-sh/ruff-pre-commit: v0.16.5 → v0.16.6](https://github.com/astral-sh/ruff-pre-commit/compare/v0.16.5...v0.16.6) * test: avoid mired rounding boundary --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Bas Nijholt --- .pre-commit-config.yaml | 2 +- tests/test_switch.py | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 53b84021..80893d1c 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -14,7 +14,7 @@ repos: files: ^README[^/]*\.md$ args: ["--notitle"] - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.16.5 + rev: v0.16.6 hooks: - id: ruff args: ["--fix"] diff --git a/tests/test_switch.py b/tests/test_switch.py index 6efe68d5..65fb5c32 100644 --- a/tests/test_switch.py +++ b/tests/test_switch.py @@ -1537,8 +1537,10 @@ async def test_apply_updates_non_ha_change_baseline( ) direction = 1 if manual_value < adaptive_value else -1 + # Legacy template lights round via mireds; 70 K keeps one reported step + # below 100 K and two steps above it across the configured range. small_change = ( - 15 if manual_attribute == LightControlAttributes.BRIGHTNESS else 60 + 15 if manual_attribute == LightControlAttributes.BRIGHTNESS else 70 ) freezer.tick(90) set_physical_state(manual_value + direction * small_change) From 3e78ac7e212cc215b01ceea29abbd8bfe63f6c62 Mon Sep 17 00:00:00 2001 From: Ahmad Tawakol <2355493+ahmadtawakol@users.noreply.github.com> Date: Tue, 8 Sep 2026 09:02:45 -0300 Subject: [PATCH 24/26] Make scripts/setup-symlinks idempotent (#1590) `ln -fs` dereferences an existing symlink to a directory and creates the new link *inside* it, so running the script a second time left two stray symlinks in the working tree instead of replacing the existing ones: tests/tests -> ../../../tests/ custom_components/adaptive_lighting/adaptive_lighting -> ../../../custom_components/adaptive_lighting Neither path is gitignored, so `git add -A` commits them. Add `-n` so an existing symlink is treated as a file and replaced. Co-authored-by: Claude Opus 5 --- scripts/setup-symlinks | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/scripts/setup-symlinks b/scripts/setup-symlinks index 91026b3a..af95b831 100755 --- a/scripts/setup-symlinks +++ b/scripts/setup-symlinks @@ -2,12 +2,17 @@ set -ex cd "$(dirname "$0")/.." +# '-n' keeps a re-run idempotent: without it 'ln -fs' follows an existing +# symlink and creates the new link *inside* the target directory, leaving a +# stray 'tests/tests' and 'custom_components/adaptive_lighting/adaptive_lighting' +# in the working tree. + # Link custom components cd core/homeassistant/components/ -ln -fs ../../../custom_components/adaptive_lighting adaptive_lighting +ln -fsn ../../../custom_components/adaptive_lighting adaptive_lighting cd - # Link tests cd core/tests/components/ -ln -fs ../../../tests/ adaptive_lighting +ln -fsn ../../../tests/ adaptive_lighting cd - From da749bcf6153d0537bc66fb18f16728f6acdf3b5 Mon Sep 17 00:00:00 2001 From: Ahmad Tawakol <2355493+ahmadtawakol@users.noreply.github.com> Date: Tue, 8 Sep 2026 09:02:51 -0300 Subject: [PATCH 25/26] Add a .dockerignore (#1591) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit tests/README.md has developers clone Home Assistant core into ./core, but Docker does not read .gitignore, so `COPY . /app/` shipped that ~300MB checkout into the build context and into the image on every build. It also changed what the build did. With /app/core already present as a real directory, `ln -s /core /app/core` linked *inside* it — leaving a stray /app/core/core -> /core — and scripts/setup-dependencies then installed from the copied host checkout rather than the image's own pinned clone. Excluding core/ (plus local virtualenvs, VCS state and caches) takes the build context from 412MB to 4.6MB and the image from 2.34GB to 2.1GB, and makes a build with a local ./core behave like a clean one: /app/core is the intended symlink to /core. This does remove an accident. An image built while a local ./core existed happened to run without `-v $(pwd):/app`, because the copied checkout carried relative symlinks that still resolved inside /app. A clean-checkout build never had that property — there the symlinks setup-symlinks writes into /core dangle — and tests/README.md requires the mount either way. 479 passed, unchanged. Co-authored-by: Claude Opus 5 --- .dockerignore | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 .dockerignore diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 00000000..767b6084 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,28 @@ +# The Home Assistant core checkout. tests/README.md has you clone it to ./core, +# but the Dockerfile clones its own copy to /core and links /app/core to it. +# Without this entry `COPY . /app/` ships ~300MB into every build and leaves +# /app/core as a real directory, so `ln -s /core /app/core` links *inside* it +# rather than creating the intended symlink. +core/ + +# Local virtualenvs +.venv/ +venv/ +env/ +ENV/ + +# Not used by the build +.git/ +.vscode/ +.idea/ + +# Caches and test output +__pycache__/ +*.py[cod] +.pytest_cache/ +.ruff_cache/ +.mypy_cache/ +htmlcov/ +.coverage +.coverage.* +coverage.xml From 7d0f4b610acb5088125aff266ba3d9af10164b2f Mon Sep 17 00:00:00 2001 From: Ahmad Tawakol <2355493+ahmadtawakol@users.noreply.github.com> Date: Tue, 8 Sep 2026 09:03:07 -0300 Subject: [PATCH 26/26] Fix TypeError when 'light.turn_off' is called with a string transition (#1589) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Fix TypeError when 'light.turn_off' is called with a string transition `EVENT_CALL_SERVICE` carries the *raw* service data, not the data `light.turn_off`'s schema produced for the service handler, so its `vol.Coerce(float)` never reaches `AdaptiveLightingManager`. A caller passing `transition: "2"` — a template rendering to a string, or any JSON payload where the value was quoted — therefore stores a `str` in `turn_off_event`. Both places that derive a delay from it compare it against an int: delay = max(transition or 0, TURNING_OFF_DELAY) # during turn-off delay = max(transition, TURNING_OFF_DELAY) # just_turned_off which raises `TypeError: '>' not supported between instances of 'int' and 'str'`. Because `just_turned_off` runs inside the state-change listener task, the exception is swallowed: it surfaces only as "Error doing job: Task exception was never retrieved (task: None)", while the light quietly stops being adapted after that turn-off. Read the transition through a helper that coerces to float. Schema validation runs before the event fires, so whatever reaches the helper is coercible. Co-Authored-By: Claude Opus 5 * Normalize turn-off transitions with the light service validator --------- Co-authored-by: Claude Opus 5 Co-authored-by: Bas Nijholt --- custom_components/adaptive_lighting/switch.py | 17 ++- tests/test_switch.py | 119 +++++++++++++++++- 2 files changed, 129 insertions(+), 7 deletions(-) diff --git a/custom_components/adaptive_lighting/switch.py b/custom_components/adaptive_lighting/switch.py index 871dcf03..db1c2d0b 100644 --- a/custom_components/adaptive_lighting/switch.py +++ b/custom_components/adaptive_lighting/switch.py @@ -20,6 +20,7 @@ from homeassistant.components.light import ( ATTR_SUPPORTED_COLOR_MODES, ATTR_TRANSITION, ATTR_XY_COLOR, + VALID_TRANSITION, ColorMode, LightEntityFeature, is_on, @@ -622,6 +623,18 @@ def _is_state_event( ) +def _turn_off_transition(turn_off_event: Event) -> float | None: + """Normalize the raw event transition using the light service's validator. + + Service-call events retain raw data after validation, so repeat the + service's coercion and clamping before calculating transition windows. + """ + transition = turn_off_event.data[ATTR_SERVICE_DATA].get(ATTR_TRANSITION) + if transition is None: + return None + return VALID_TRANSITION(transition) + + def _expand_light_groups( hass: HomeAssistant, lights: list[str], @@ -3109,7 +3122,7 @@ class AdaptiveLightingManager: ): return False - transition = turn_off_event.data[ATTR_SERVICE_DATA].get(ATTR_TRANSITION) + transition = _turn_off_transition(turn_off_event) delay = max(transition or 0, TURNING_OFF_DELAY) elapsed = (dt_util.utcnow() - turn_off_event.time_fired).total_seconds() if not 0 <= elapsed <= delay: @@ -3193,7 +3206,7 @@ class AdaptiveLightingManager: turn_off_event = self.turn_off_event.get(entity_id) if turn_off_event is not None: - transition = turn_off_event.data[ATTR_SERVICE_DATA].get(ATTR_TRANSITION) + transition = _turn_off_transition(turn_off_event) else: transition = None diff --git a/tests/test_switch.py b/tests/test_switch.py index 65fb5c32..a3f5b689 100644 --- a/tests/test_switch.py +++ b/tests/test_switch.py @@ -83,6 +83,7 @@ from homeassistant.components.adaptive_lighting.switch import ( SimpleSwitch, _attributes_have_changed, _expand_light_groups, + _turn_off_transition, color_difference_redmean, create_context, is_our_context, @@ -112,6 +113,7 @@ from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_FLOOR_ID, ATTR_LABEL_ID, + ATTR_SERVICE_DATA, ATTR_SUPPORTED_FEATURES, CONF_LIGHTS, CONF_NAME, @@ -4262,17 +4264,17 @@ def _turn_off_service_event( entity_ids: list[str], ts: float, context: Context, - transition: float, + transition: float | str | None, ) -> Event: + service_data = {ATTR_ENTITY_ID: entity_ids} + if transition is not None: + service_data[ATTR_TRANSITION] = transition return Event( EVENT_CALL_SERVICE, { "domain": LIGHT_DOMAIN, "service": SERVICE_TURN_OFF, - "service_data": { - ATTR_ENTITY_ID: entity_ids, - ATTR_TRANSITION: transition, - }, + "service_data": service_data, }, time_fired_timestamp=ts, context=context, @@ -4566,6 +4568,113 @@ async def test_just_turned_off_same_automation_context(hass, cleanup): assert not await manager.just_turned_off(ENTITY_LIGHT_1) +@pytest.mark.parametrize( + ("transition", "window"), + [(10, 10), (10.0, 10), ("10", 10), ("10000", 6553), ("inf", 6553), (None, 5)], +) +async def test_just_turned_off_normalized_transition(hass, cleanup, transition, window): + """Both turn-off guards use coerced and clamped transition windows.""" + await setup_lights(hass) + _, switch = await setup_switch(hass, {CONF_LIGHTS: [ENTITY_LIGHT_1]}) + await hass.async_block_till_done() + manager = switch.manager + + now = dt_util.utcnow().timestamp() + context = Context() + other_context = Context() + + # Setting up the switch turns the light on, and that 'turn_on' would be read + # as the legitimate explanation for the 'off' → 'on' state changes below. + manager.turn_on_event.pop(ENTITY_LIGHT_1, None) + + def set_events(turn_off_ts: float, off_to_on_context: Context) -> None: + manager.turn_off_event[ENTITY_LIGHT_1] = _turn_off_service_event( + [ENTITY_LIGHT_1], + turn_off_ts, + context, + transition=transition, + ) + manager.on_to_off_event[ENTITY_LIGHT_1] = _state_changed_event( + ENTITY_LIGHT_1, + turn_off_ts, + other_context, + ) + manager.off_to_on_event[ENTITY_LIGHT_1] = _state_changed_event( + ENTITY_LIGHT_1, + now, + off_to_on_context, + ) + + # A matching context is ignored within the normalized transition window. + set_events(now - window + 1, context) + assert await manager.just_turned_off(ENTITY_LIGHT_1) + + # Past that window the same shape must stop matching. + set_events(now - window - 1, context) + assert not await manager.just_turned_off(ENTITY_LIGHT_1) + + # `just_turned_off`'s own `max(transition, TURNING_OFF_DELAY)`: reached when + # the 'off' → 'on' state change carries a fresh context, so the check above + # returns early and the delay is computed from the 'on' → 'off' change. + manager.turn_off_event[ENTITY_LIGHT_1] = _turn_off_service_event( + [ENTITY_LIGHT_1], + now - window - 1, + context, + transition=transition, + ) + manager.on_to_off_event[ENTITY_LIGHT_1] = _state_changed_event( + ENTITY_LIGHT_1, + now - window - 1, + context, + ) + manager.off_to_on_event[ENTITY_LIGHT_1] = _state_changed_event( + ENTITY_LIGHT_1, + now, + Context(), + ) + assert not await manager.just_turned_off(ENTITY_LIGHT_1) + + +@pytest.mark.parametrize( + ("transition", "expected"), + [("2", 2.0), ("10000", 6553), ("inf", 6553), ("-2", 0), (None, None)], +) +async def test_turn_off_event_keeps_raw_transition(hass, cleanup, transition, expected): + """Normalize raw event data to the same transition used by the light service.""" + await setup_lights(hass) + _, switch = await setup_switch(hass, {CONF_LIGHTS: [ENTITY_LIGHT_1]}) + await hass.async_block_till_done() + manager = switch.manager + + service_data = {ATTR_ENTITY_ID: ENTITY_LIGHT_1} + if transition is not None: + service_data[ATTR_TRANSITION] = transition + await hass.services.async_call( + LIGHT_DOMAIN, + SERVICE_TURN_OFF, + service_data, + blocking=True, + ) + await hass.async_block_till_done() + + event = manager.turn_off_event[ENTITY_LIGHT_1] + assert event.data[ATTR_SERVICE_DATA].get(ATTR_TRANSITION) == transition + assert _turn_off_transition(event) == expected + + # A 'transition' that cannot be coerced is rejected by the schema, so it + # never reaches the listener. + manager.turn_off_event.pop(ENTITY_LIGHT_1) + with pytest.raises(voluptuous.error.MultipleInvalid): + await hass.services.async_call( + LIGHT_DOMAIN, + SERVICE_TURN_OFF, + {ATTR_ENTITY_ID: ENTITY_LIGHT_1, ATTR_TRANSITION: "not-a-number"}, + blocking=True, + ) + await hass.async_block_till_done() + assert ENTITY_LIGHT_1 not in manager.turn_off_event + + async def test_just_turned_off_group_context_reuse_end_to_end(hass, cleanup): """A tracked member turn-on explains a group's reused OFF context (#1378).""" await setup_lights(hass, with_group=True)