From f9bc6b9857f68b5c298935a8f116387281807250 Mon Sep 17 00:00:00 2001 From: Benoit Anastay <45088785+BenoitAnastay@users.noreply.github.com> Date: Mon, 1 Jul 2024 20:14:15 +0200 Subject: [PATCH 01/23] initial reimplementation of hue scene updating --- custom_components/adaptive_lighting/const.py | 6 +++ .../adaptive_lighting/manifest.json | 2 +- custom_components/adaptive_lighting/switch.py | 45 +++++++++++++++++++ .../adaptive_lighting/translations/en.json | 10 ++++- 4 files changed, 60 insertions(+), 3 deletions(-) diff --git a/custom_components/adaptive_lighting/const.py b/custom_components/adaptive_lighting/const.py index 79d571e2..353ca912 100644 --- a/custom_components/adaptive_lighting/const.py +++ b/custom_components/adaptive_lighting/const.py @@ -274,6 +274,10 @@ 'documented defaults), or "configuration" (reverts to switch config defaults). βš™οΈ' ) +CONF_HUE_KEYWORD, DEFAULT_HUE_KEYWORD = "hue_keyword", "None" +DOCS[CONF_HUE_KEYWORD] = ( + "Scenes witch contain this keyword will be updated on the HUE bridge" +) TURNING_OFF_DELAY = 5 DOCS_MANUAL_CONTROL = { @@ -367,6 +371,7 @@ def int_between(min_int, max_int): (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_HUE_KEYWORD, NONE_STR, str), ] @@ -435,6 +440,7 @@ def apply_service_schema(initial_transition: int = 1): vol.Optional(ATTR_ADAPT_COLOR, default=True): cv.boolean, vol.Optional(CONF_PREFER_RGB_COLOR, default=False): cv.boolean, vol.Optional(CONF_TURN_ON_LIGHTS, default=False): cv.boolean, + vol.Optional(CONF_HUE_KEYWORD): cv.string, }, ) diff --git a/custom_components/adaptive_lighting/manifest.json b/custom_components/adaptive_lighting/manifest.json index 6d8c0f5f..d55f9ffb 100644 --- a/custom_components/adaptive_lighting/manifest.json +++ b/custom_components/adaptive_lighting/manifest.json @@ -7,6 +7,6 @@ "documentation": "https://github.com/basnijholt/adaptive-lighting#readme", "iot_class": "calculated", "issue_tracker": "https://github.com/basnijholt/adaptive-lighting/issues", - "requirements": ["ulid-transform"], + "requirements": ["ulid-transform","aiohue-BenoitAnastay"], "version": "1.22.0" } diff --git a/custom_components/adaptive_lighting/switch.py b/custom_components/adaptive_lighting/switch.py index b4af97ed..37047b43 100644 --- a/custom_components/adaptive_lighting/switch.py +++ b/custom_components/adaptive_lighting/switch.py @@ -3,9 +3,13 @@ from __future__ import annotations import asyncio +import aiohttp +import aiohue_BenoitAnastay +import json import datetime import logging import zoneinfo +from aiohue_BenoitAnastay.discovery import discover_nupnp from copy import deepcopy from datetime import timedelta from typing import TYPE_CHECKING, Any, Literal @@ -147,6 +151,7 @@ CONF_TRANSITION, CONF_TURN_ON_LIGHTS, CONF_USE_DEFAULTS, + CONF_HUE_KEYWORD, DOMAIN, EXTRA_VALIDATION, ICON_BRIGHTNESS, @@ -813,6 +818,7 @@ def __init__( self._name = data[CONF_NAME] self._interval: timedelta = data[CONF_INTERVAL] self.lights: list[str] = data[CONF_LIGHTS] + self.hue_keyword = data[CONF_HUE_KEYWORD] # backup data for use in change_switch_settings "configuration" CONF_USE_DEFAULTS self._config_backup = deepcopy(data) @@ -1266,6 +1272,9 @@ async def _adapt_light( if (lock := self.manager.turn_off_locks.get(light)) and lock.locked(): _LOGGER.debug("%s: '%s' is locked", self._name, light) return + if self.hue_keyword is not None: + async with aiohttp.ClientSession() as session: + await self.update_hue_run(session) data = await self.prepare_adaptation_data( light, @@ -1564,6 +1573,42 @@ async def _sleep_mode_switch_state_event_action(self, event: Event) -> None: force=True, ) + async def update_hue_run(self,websession): + """Function updating HUE scene""" + try: + entriesJson = open('/config/.storage/core.config_entries',) + response = json.load(entriesJson) + + for entry in response["data"]["entries"]: + if entry["domain"] == "hue": + break + bridge = aiohue_BenoitAnastay.HueBridgeV1( + entry["data"]["host"], + entry["data"]["api_key"], + ) + except Exception as e: + raise e + if bridge is None: + if self._hue_username is None: + return False + bridges = await discover_nupnp(websession) + bridge = bridges[0] + bridge.username = self._hue_username + + await bridge.initialize() + for id in bridge.scenes: + scene = bridge.scenes[id] + if self.hue_keyword in scene.name: + color_temp = self._settings["color_temp_kelvin"] + lightstates = await scene.lightstates + for light_id in scene.lights: + try: + await scene.set_lightstate(id=light_id,on=lightstates[light_id]["on"],bri=int(round(254 * self._settings["brightness_pct"] / 100)),ct=color_temp) + except Exception: + _LOGGER.error( + "Cannot update scene %s", + id, + ) class SimpleSwitch(SwitchEntity, RestoreEntity): """Representation of a Adaptive Lighting switch.""" diff --git a/custom_components/adaptive_lighting/translations/en.json b/custom_components/adaptive_lighting/translations/en.json index f55a6d88..42dd8077 100644 --- a/custom_components/adaptive_lighting/translations/en.json +++ b/custom_components/adaptive_lighting/translations/en.json @@ -57,7 +57,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`. πŸ“", + "hue_keyword": "hue_keyword" }, "data_description": { "interval": "Frequency to adapt the lights, in seconds. πŸ”„", @@ -81,7 +82,8 @@ "brightness_mode_time_light": "(Ignored if `brightness_mode='default'`) The duration in seconds to ramp up/down the brightness after/before sunrise/sunset. πŸ“ˆπŸ“‰.", "autoreset_control_seconds": "Automatically reset the manual control after a number of seconds. Set to 0 to disable. ⏲️", "send_split_delay": "Delay (ms) between `separate_turn_on_commands` for lights that don't support simultaneous brightness and color setting. ⏲️", - "adapt_delay": "Wait time (seconds) between light turn on and Adaptive Lighting applying changes. Might help to avoid flickering. ⏲️" + "adapt_delay": "Wait time (seconds) between light turn on and Adaptive Lighting applying changes. Might help to avoid flickering. ⏲️", + "hue_keyword": "Set the HUE scene keyword to update" } } }, @@ -262,6 +264,10 @@ "autoreset_control_seconds": { "description": "Automatically reset the manual control after a number of seconds. Set to 0 to disable. ⏲️", "name": "autoreset_control_seconds" + }, + "hue_keyword": { + "description": "Set the HUE scene keyword to update", + "name": "hue_keyword" } } } From 28e9170188394172927102183c5c6e3c637b9f83 Mon Sep 17 00:00:00 2001 From: Benoit Anastay <45088785+BenoitAnastay@users.noreply.github.com> Date: Mon, 1 Jul 2024 21:41:28 +0200 Subject: [PATCH 02/23] Fixs --- custom_components/adaptive_lighting/switch.py | 60 ++++++++++--------- 1 file changed, 32 insertions(+), 28 deletions(-) diff --git a/custom_components/adaptive_lighting/switch.py b/custom_components/adaptive_lighting/switch.py index 37047b43..9cac64aa 100644 --- a/custom_components/adaptive_lighting/switch.py +++ b/custom_components/adaptive_lighting/switch.py @@ -820,6 +820,16 @@ def __init__( self.lights: list[str] = data[CONF_LIGHTS] self.hue_keyword = data[CONF_HUE_KEYWORD] + # Set bridge + try: + config_entries = hass.config_entries.async_entries(domain="hue") + config_entry = config_entries[0] + self.hue_bridge = aiohue_BenoitAnastay.HueBridgeV1( + config_entry.data["host"], + config_entry.data["api_key"], + ) + except Exception as e: + raise e # backup data for use in change_switch_settings "configuration" CONF_USE_DEFAULTS self._config_backup = deepcopy(data) self._set_changeable_settings(data=data, defaults=None) @@ -1247,6 +1257,9 @@ async def prepare_adaptation_data( context = context or self.create_context("adapt_lights") + async with aiohttp.ClientSession() as session: + await self.update_hue_run(session, service_data) + return prepare_adaptation_data( self.hass, light, @@ -1272,9 +1285,6 @@ async def _adapt_light( if (lock := self.manager.turn_off_locks.get(light)) and lock.locked(): _LOGGER.debug("%s: '%s' is locked", self._name, light) return - if self.hue_keyword is not None: - async with aiohttp.ClientSession() as session: - await self.update_hue_run(session) data = await self.prepare_adaptation_data( light, @@ -1573,37 +1583,31 @@ async def _sleep_mode_switch_state_event_action(self, event: Event) -> None: force=True, ) - async def update_hue_run(self,websession): + async def update_hue_run(self, websession, service_data: ServiceData): """Function updating HUE scene""" - try: - entriesJson = open('/config/.storage/core.config_entries',) - response = json.load(entriesJson) - - for entry in response["data"]["entries"]: - if entry["domain"] == "hue": - break - bridge = aiohue_BenoitAnastay.HueBridgeV1( - entry["data"]["host"], - entry["data"]["api_key"], - ) - except Exception as e: - raise e - if bridge is None: - if self._hue_username is None: - return False - bridges = await discover_nupnp(websession) - bridge = bridges[0] - bridge.username = self._hue_username + if self.hue_keyword is None: + return - await bridge.initialize() - for id in bridge.scenes: - scene = bridge.scenes[id] + _LOGGER.debug( + "%s: Will updates scenes containing %s", + self._name, + self.hue_keyword, + ) + await self.hue_bridge.initialize() + for id in self.hue_bridge.scenes: + scene = self.hue_bridge.scenes[id] if self.hue_keyword in scene.name: - color_temp = self._settings["color_temp_kelvin"] + _LOGGER.debug( + "%s: Updating %s", + self._name, + scene.name, + ) + color_temp = service_data["color_temp_kelvin"] + brightness = service_data["brightness"] lightstates = await scene.lightstates for light_id in scene.lights: try: - await scene.set_lightstate(id=light_id,on=lightstates[light_id]["on"],bri=int(round(254 * self._settings["brightness_pct"] / 100)),ct=color_temp) + await scene.set_lightstate(id=light_id,on=lightstates[light_id]["on"],bri=brightness,ct=color_temp) except Exception: _LOGGER.error( "Cannot update scene %s", From 6c2308b3333c32f0c5de24bee2fa3009fbb44498 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 1 Jul 2024 19:48:51 +0000 Subject: [PATCH 03/23] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- custom_components/adaptive_lighting/switch.py | 22 +++++++++++-------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/custom_components/adaptive_lighting/switch.py b/custom_components/adaptive_lighting/switch.py index 9cac64aa..9a560f12 100644 --- a/custom_components/adaptive_lighting/switch.py +++ b/custom_components/adaptive_lighting/switch.py @@ -3,17 +3,15 @@ from __future__ import annotations import asyncio -import aiohttp -import aiohue_BenoitAnastay -import json import datetime import logging import zoneinfo -from aiohue_BenoitAnastay.discovery import discover_nupnp from copy import deepcopy from datetime import timedelta from typing import TYPE_CHECKING, Any, Literal +import aiohttp +import aiohue_BenoitAnastay import homeassistant.helpers.config_validation as cv import homeassistant.util.dt as dt_util import ulid_transform @@ -118,6 +116,7 @@ CONF_BRIGHTNESS_MODE_TIME_DARK, CONF_BRIGHTNESS_MODE_TIME_LIGHT, CONF_DETECT_NON_HA_CHANGES, + CONF_HUE_KEYWORD, CONF_INCLUDE_CONFIG_IN_ATTRIBUTES, CONF_INITIAL_TRANSITION, CONF_INTERCEPT, @@ -151,7 +150,6 @@ CONF_TRANSITION, CONF_TURN_ON_LIGHTS, CONF_USE_DEFAULTS, - CONF_HUE_KEYWORD, DOMAIN, EXTRA_VALIDATION, ICON_BRIGHTNESS, @@ -1589,9 +1587,9 @@ async def update_hue_run(self, websession, service_data: ServiceData): return _LOGGER.debug( - "%s: Will updates scenes containing %s", - self._name, - self.hue_keyword, + "%s: Will updates scenes containing %s", + self._name, + self.hue_keyword, ) await self.hue_bridge.initialize() for id in self.hue_bridge.scenes: @@ -1607,13 +1605,19 @@ async def update_hue_run(self, websession, service_data: ServiceData): lightstates = await scene.lightstates for light_id in scene.lights: try: - await scene.set_lightstate(id=light_id,on=lightstates[light_id]["on"],bri=brightness,ct=color_temp) + await scene.set_lightstate( + id=light_id, + on=lightstates[light_id]["on"], + bri=brightness, + ct=color_temp, + ) except Exception: _LOGGER.error( "Cannot update scene %s", id, ) + class SimpleSwitch(SwitchEntity, RestoreEntity): """Representation of a Adaptive Lighting switch.""" From 1714b6278cebf33c67effda3ac26f683610937f3 Mon Sep 17 00:00:00 2001 From: Benoit Anastay <45088785+BenoitAnastay@users.noreply.github.com> Date: Mon, 1 Jul 2024 21:58:04 +0200 Subject: [PATCH 04/23] =?UTF-8?q?=E2=9E=95=20pip=20install=20aiohue-Benoit?= =?UTF-8?q?Anastay?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/setup-dependencies | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/setup-dependencies b/scripts/setup-dependencies index efe0bd25..8463880a 100755 --- a/scripts/setup-dependencies +++ b/scripts/setup-dependencies @@ -13,4 +13,5 @@ pip install -r core/requirements_test.txt pip install -e core/ pip install ulid-transform # this is in Adaptive-lighting's manifest.json +pip install aiohue-BenoitAnastay # same as above pip install $(python test_dependencies.py) From 9d19f117b106c05ea5bd3feeb03aa8943e55054b Mon Sep 17 00:00:00 2001 From: Benoit Anastay <45088785+BenoitAnastay@users.noreply.github.com> Date: Mon, 1 Jul 2024 22:24:49 +0200 Subject: [PATCH 05/23] =?UTF-8?q?=F0=9F=9A=A8=20a=20bit=20of=20lint?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- custom_components/adaptive_lighting/switch.py | 38 ++++++++----------- 1 file changed, 16 insertions(+), 22 deletions(-) diff --git a/custom_components/adaptive_lighting/switch.py b/custom_components/adaptive_lighting/switch.py index 9a560f12..a3177955 100644 --- a/custom_components/adaptive_lighting/switch.py +++ b/custom_components/adaptive_lighting/switch.py @@ -2,6 +2,7 @@ from __future__ import annotations +import aiohue_BenoitAnastay import asyncio import datetime import logging @@ -10,8 +11,6 @@ from datetime import timedelta from typing import TYPE_CHECKING, Any, Literal -import aiohttp -import aiohue_BenoitAnastay import homeassistant.helpers.config_validation as cv import homeassistant.util.dt as dt_util import ulid_transform @@ -116,7 +115,6 @@ CONF_BRIGHTNESS_MODE_TIME_DARK, CONF_BRIGHTNESS_MODE_TIME_LIGHT, CONF_DETECT_NON_HA_CHANGES, - CONF_HUE_KEYWORD, CONF_INCLUDE_CONFIG_IN_ATTRIBUTES, CONF_INITIAL_TRANSITION, CONF_INTERCEPT, @@ -150,6 +148,7 @@ CONF_TRANSITION, CONF_TURN_ON_LIGHTS, CONF_USE_DEFAULTS, + CONF_HUE_KEYWORD, DOMAIN, EXTRA_VALIDATION, ICON_BRIGHTNESS, @@ -826,8 +825,10 @@ def __init__( config_entry.data["host"], config_entry.data["api_key"], ) - except Exception as e: - raise e + except Exception: + _LOGGER.exception( + "Cannot set hue bridge", + ) # backup data for use in change_switch_settings "configuration" CONF_USE_DEFAULTS self._config_backup = deepcopy(data) self._set_changeable_settings(data=data, defaults=None) @@ -1255,8 +1256,7 @@ async def prepare_adaptation_data( context = context or self.create_context("adapt_lights") - async with aiohttp.ClientSession() as session: - await self.update_hue_run(session, service_data) + await self.update_hue_run(service_data) return prepare_adaptation_data( self.hass, @@ -1581,19 +1581,19 @@ async def _sleep_mode_switch_state_event_action(self, event: Event) -> None: force=True, ) - async def update_hue_run(self, websession, service_data: ServiceData): - """Function updating HUE scene""" + async def update_hue_run(self, service_data: ServiceData): + """Function updating HUE scene.""" if self.hue_keyword is None: return _LOGGER.debug( - "%s: Will updates scenes containing %s", - self._name, - self.hue_keyword, + "%s: Will updates scenes containing %s", + self._name, + self.hue_keyword, ) await self.hue_bridge.initialize() - for id in self.hue_bridge.scenes: - scene = self.hue_bridge.scenes[id] + for scene_id in self.hue_bridge.scenes: + scene = self.hue_bridge.scenes[scene_id] if self.hue_keyword in scene.name: _LOGGER.debug( "%s: Updating %s", @@ -1605,19 +1605,13 @@ async def update_hue_run(self, websession, service_data: ServiceData): lightstates = await scene.lightstates for light_id in scene.lights: try: - await scene.set_lightstate( - id=light_id, - on=lightstates[light_id]["on"], - bri=brightness, - ct=color_temp, - ) + await scene.set_lightstate(id=light_id,on=lightstates[light_id]["on"],bri=brightness,ct=color_temp) except Exception: - _LOGGER.error( + _LOGGER.exception( "Cannot update scene %s", id, ) - class SimpleSwitch(SwitchEntity, RestoreEntity): """Representation of a Adaptive Lighting switch.""" From 9e507532e9f7d8686a5e9ee6c3eb110f874da60a Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 1 Jul 2024 20:25:01 +0000 Subject: [PATCH 06/23] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- custom_components/adaptive_lighting/switch.py | 22 ++++++++++++------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/custom_components/adaptive_lighting/switch.py b/custom_components/adaptive_lighting/switch.py index a3177955..4302293c 100644 --- a/custom_components/adaptive_lighting/switch.py +++ b/custom_components/adaptive_lighting/switch.py @@ -2,7 +2,6 @@ from __future__ import annotations -import aiohue_BenoitAnastay import asyncio import datetime import logging @@ -11,6 +10,7 @@ from datetime import timedelta from typing import TYPE_CHECKING, Any, Literal +import aiohue_BenoitAnastay import homeassistant.helpers.config_validation as cv import homeassistant.util.dt as dt_util import ulid_transform @@ -115,6 +115,7 @@ CONF_BRIGHTNESS_MODE_TIME_DARK, CONF_BRIGHTNESS_MODE_TIME_LIGHT, CONF_DETECT_NON_HA_CHANGES, + CONF_HUE_KEYWORD, CONF_INCLUDE_CONFIG_IN_ATTRIBUTES, CONF_INITIAL_TRANSITION, CONF_INTERCEPT, @@ -148,7 +149,6 @@ CONF_TRANSITION, CONF_TURN_ON_LIGHTS, CONF_USE_DEFAULTS, - CONF_HUE_KEYWORD, DOMAIN, EXTRA_VALIDATION, ICON_BRIGHTNESS, @@ -827,8 +827,8 @@ def __init__( ) except Exception: _LOGGER.exception( - "Cannot set hue bridge", - ) + "Cannot set hue bridge", + ) # backup data for use in change_switch_settings "configuration" CONF_USE_DEFAULTS self._config_backup = deepcopy(data) self._set_changeable_settings(data=data, defaults=None) @@ -1587,9 +1587,9 @@ async def update_hue_run(self, service_data: ServiceData): return _LOGGER.debug( - "%s: Will updates scenes containing %s", - self._name, - self.hue_keyword, + "%s: Will updates scenes containing %s", + self._name, + self.hue_keyword, ) await self.hue_bridge.initialize() for scene_id in self.hue_bridge.scenes: @@ -1605,13 +1605,19 @@ async def update_hue_run(self, service_data: ServiceData): lightstates = await scene.lightstates for light_id in scene.lights: try: - await scene.set_lightstate(id=light_id,on=lightstates[light_id]["on"],bri=brightness,ct=color_temp) + await scene.set_lightstate( + id=light_id, + on=lightstates[light_id]["on"], + bri=brightness, + ct=color_temp, + ) except Exception: _LOGGER.exception( "Cannot update scene %s", id, ) + class SimpleSwitch(SwitchEntity, RestoreEntity): """Representation of a Adaptive Lighting switch.""" From 426696c6c1f8fed7bd9bbdec28b017c6ad0771bc Mon Sep 17 00:00:00 2001 From: Benoit Anastay <45088785+BenoitAnastay@users.noreply.github.com> Date: Mon, 1 Jul 2024 22:49:27 +0200 Subject: [PATCH 07/23] =?UTF-8?q?=E2=9E=95=20add=20pip=20install=20aiohue?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/setup-dependencies | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/setup-dependencies b/scripts/setup-dependencies index 8463880a..e2003be1 100755 --- a/scripts/setup-dependencies +++ b/scripts/setup-dependencies @@ -13,5 +13,6 @@ pip install -r core/requirements_test.txt pip install -e core/ pip install ulid-transform # this is in Adaptive-lighting's manifest.json +pip install aiohue pip install aiohue-BenoitAnastay # same as above pip install $(python test_dependencies.py) From 25f840630120fc2eb9907f92fd3de763d676bc6f Mon Sep 17 00:00:00 2001 From: Benoit Anastay <45088785+BenoitAnastay@users.noreply.github.com> Date: Tue, 2 Jul 2024 19:53:42 +0200 Subject: [PATCH 08/23] avoid oob values, convert kelvin to mired --- custom_components/adaptive_lighting/switch.py | 22 +++++++++---------- 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/custom_components/adaptive_lighting/switch.py b/custom_components/adaptive_lighting/switch.py index 4302293c..5a1447ce 100644 --- a/custom_components/adaptive_lighting/switch.py +++ b/custom_components/adaptive_lighting/switch.py @@ -89,6 +89,7 @@ from homeassistant.loader import bind_hass from homeassistant.util import slugify from homeassistant.util.color import ( + color_temperature_kelvin_to_mired, color_temperature_to_rgb, color_xy_to_RGB, ) @@ -1587,30 +1588,27 @@ async def update_hue_run(self, service_data: ServiceData): return _LOGGER.debug( - "%s: Will updates scenes containing %s", - self._name, - self.hue_keyword, + "%s: Will updates scenes containing %s", + self._name, + self.hue_keyword, ) await self.hue_bridge.initialize() for scene_id in self.hue_bridge.scenes: scene = self.hue_bridge.scenes[scene_id] if self.hue_keyword in scene.name: + color_temp = color_temperature_kelvin_to_mired(service_data[ATTR_COLOR_TEMP_KELVIN]) + brightness = round(254 * self._settings["brightness_pct"] / 100) _LOGGER.debug( - "%s: Updating %s", + "%s: Updating %s with values bri:%s, color_temp:%s", self._name, scene.name, + brightness, + color_temp ) - color_temp = service_data["color_temp_kelvin"] - brightness = service_data["brightness"] lightstates = await scene.lightstates for light_id in scene.lights: try: - await scene.set_lightstate( - id=light_id, - on=lightstates[light_id]["on"], - bri=brightness, - ct=color_temp, - ) + await scene.set_lightstate(id=light_id,on=lightstates[light_id]["on"],bri=brightness,ct=color_temp) except Exception: _LOGGER.exception( "Cannot update scene %s", From 5d680b4a7bdc3875cc9e9c29832939bc0d5d8048 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 2 Jul 2024 17:56:11 +0000 Subject: [PATCH 09/23] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- custom_components/adaptive_lighting/switch.py | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/custom_components/adaptive_lighting/switch.py b/custom_components/adaptive_lighting/switch.py index 5a1447ce..72829fcb 100644 --- a/custom_components/adaptive_lighting/switch.py +++ b/custom_components/adaptive_lighting/switch.py @@ -1588,27 +1588,34 @@ async def update_hue_run(self, service_data: ServiceData): return _LOGGER.debug( - "%s: Will updates scenes containing %s", - self._name, - self.hue_keyword, + "%s: Will updates scenes containing %s", + self._name, + self.hue_keyword, ) await self.hue_bridge.initialize() for scene_id in self.hue_bridge.scenes: scene = self.hue_bridge.scenes[scene_id] if self.hue_keyword in scene.name: - color_temp = color_temperature_kelvin_to_mired(service_data[ATTR_COLOR_TEMP_KELVIN]) + color_temp = color_temperature_kelvin_to_mired( + service_data[ATTR_COLOR_TEMP_KELVIN] + ) brightness = round(254 * self._settings["brightness_pct"] / 100) _LOGGER.debug( "%s: Updating %s with values bri:%s, color_temp:%s", self._name, scene.name, brightness, - color_temp + color_temp, ) lightstates = await scene.lightstates for light_id in scene.lights: try: - await scene.set_lightstate(id=light_id,on=lightstates[light_id]["on"],bri=brightness,ct=color_temp) + await scene.set_lightstate( + id=light_id, + on=lightstates[light_id]["on"], + bri=brightness, + ct=color_temp, + ) except Exception: _LOGGER.exception( "Cannot update scene %s", From ae3a727a32bbb2133449cf3d2bcadbc10b19437b Mon Sep 17 00:00:00 2001 From: Benoit Anastay <45088785+BenoitAnastay@users.noreply.github.com> Date: Mon, 16 Sep 2024 15:43:10 +0200 Subject: [PATCH 10/23] Cleanup dependencies --- custom_components/adaptive_lighting/manifest.json | 2 +- scripts/setup-dependencies | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/custom_components/adaptive_lighting/manifest.json b/custom_components/adaptive_lighting/manifest.json index d55f9ffb..6d8c0f5f 100644 --- a/custom_components/adaptive_lighting/manifest.json +++ b/custom_components/adaptive_lighting/manifest.json @@ -7,6 +7,6 @@ "documentation": "https://github.com/basnijholt/adaptive-lighting#readme", "iot_class": "calculated", "issue_tracker": "https://github.com/basnijholt/adaptive-lighting/issues", - "requirements": ["ulid-transform","aiohue-BenoitAnastay"], + "requirements": ["ulid-transform"], "version": "1.22.0" } diff --git a/scripts/setup-dependencies b/scripts/setup-dependencies index e2003be1..40d26720 100755 --- a/scripts/setup-dependencies +++ b/scripts/setup-dependencies @@ -14,5 +14,4 @@ pip install -r core/requirements_test.txt pip install -e core/ pip install ulid-transform # this is in Adaptive-lighting's manifest.json pip install aiohue -pip install aiohue-BenoitAnastay # same as above pip install $(python test_dependencies.py) From 3c16d176704fd8fce269255d9c6f992746e2c231 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 16 Sep 2024 13:41:49 +0000 Subject: [PATCH 11/23] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- custom_components/adaptive_lighting/switch.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/custom_components/adaptive_lighting/switch.py b/custom_components/adaptive_lighting/switch.py index 72829fcb..f2d65e49 100644 --- a/custom_components/adaptive_lighting/switch.py +++ b/custom_components/adaptive_lighting/switch.py @@ -1597,7 +1597,7 @@ async def update_hue_run(self, service_data: ServiceData): scene = self.hue_bridge.scenes[scene_id] if self.hue_keyword in scene.name: color_temp = color_temperature_kelvin_to_mired( - service_data[ATTR_COLOR_TEMP_KELVIN] + service_data[ATTR_COLOR_TEMP_KELVIN], ) brightness = round(254 * self._settings["brightness_pct"] / 100) _LOGGER.debug( From 916307985f2e8531bf90208406d9b6fe53ee5b0e Mon Sep 17 00:00:00 2001 From: Benoit Anastay <45088785+BenoitAnastay@users.noreply.github.com> Date: Mon, 16 Sep 2024 17:03:20 +0200 Subject: [PATCH 12/23] =?UTF-8?q?=E2=AC=86=EF=B8=8F=20Update=20to=20API=20?= =?UTF-8?q?V2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../adaptive_lighting/hue_utils.py | 17 +++++ custom_components/adaptive_lighting/switch.py | 68 ++++++++----------- 2 files changed, 45 insertions(+), 40 deletions(-) create mode 100644 custom_components/adaptive_lighting/hue_utils.py diff --git a/custom_components/adaptive_lighting/hue_utils.py b/custom_components/adaptive_lighting/hue_utils.py new file mode 100644 index 00000000..2acad3c3 --- /dev/null +++ b/custom_components/adaptive_lighting/hue_utils.py @@ -0,0 +1,17 @@ +"""Help fixing a serialization issue""" + +from dataclasses import dataclass + +@dataclass +class ResourceIdentifier: + """ + Represent a ResourceIdentifier object as used by the Hue api. + + clip-api.schema.json#/definitions/ResourceIdentifierGet + clip-api.schema.json#/definitions/ResourceIdentifierPost + clip-api.schema.json#/definitions/ResourceIdentifierPut + clip-api.schema.json#/definitions/ResourceIdentifierDelete + """ + + rid: str # UUID + rtype: str diff --git a/custom_components/adaptive_lighting/switch.py b/custom_components/adaptive_lighting/switch.py index f2d65e49..77684fac 100644 --- a/custom_components/adaptive_lighting/switch.py +++ b/custom_components/adaptive_lighting/switch.py @@ -10,7 +10,10 @@ from datetime import timedelta from typing import TYPE_CHECKING, Any, Literal -import aiohue_BenoitAnastay +from aiohue import HueBridgeV2 +from aiohue.v2.models.scene import ScenePut +from .hue_utils import ResourceIdentifier + import homeassistant.helpers.config_validation as cv import homeassistant.util.dt as dt_util import ulid_transform @@ -818,18 +821,6 @@ def __init__( self.lights: list[str] = data[CONF_LIGHTS] self.hue_keyword = data[CONF_HUE_KEYWORD] - # Set bridge - try: - config_entries = hass.config_entries.async_entries(domain="hue") - config_entry = config_entries[0] - self.hue_bridge = aiohue_BenoitAnastay.HueBridgeV1( - config_entry.data["host"], - config_entry.data["api_key"], - ) - except Exception: - _LOGGER.exception( - "Cannot set hue bridge", - ) # backup data for use in change_switch_settings "configuration" CONF_USE_DEFAULTS self._config_backup = deepcopy(data) self._set_changeable_settings(data=data, defaults=None) @@ -1592,35 +1583,32 @@ async def update_hue_run(self, service_data: ServiceData): self._name, self.hue_keyword, ) - await self.hue_bridge.initialize() - for scene_id in self.hue_bridge.scenes: - scene = self.hue_bridge.scenes[scene_id] - if self.hue_keyword in scene.name: - color_temp = color_temperature_kelvin_to_mired( + config_entries = self.hass.config_entries.async_entries(domain="hue") + config_entry = config_entries[0] + + color_temp = color_temperature_kelvin_to_mired( service_data[ATTR_COLOR_TEMP_KELVIN], ) - brightness = round(254 * self._settings["brightness_pct"] / 100) - _LOGGER.debug( - "%s: Updating %s with values bri:%s, color_temp:%s", - self._name, - scene.name, - brightness, - color_temp, - ) - lightstates = await scene.lightstates - for light_id in scene.lights: - try: - await scene.set_lightstate( - id=light_id, - on=lightstates[light_id]["on"], - bri=brightness, - ct=color_temp, - ) - except Exception: - _LOGGER.exception( - "Cannot update scene %s", - id, - ) + brightness = self._settings["brightness_pct"] + + async with HueBridgeV2(config_entry.data["host"], config_entry.data["api_key"]) as bridge: + for scene in bridge.scenes: + if self.hue_keyword in scene.metadata.name: + _LOGGER.debug( + "%s: Updating %s with values bri:%s, color_temp:%s", + self._name, + scene.metadata.name, + brightness, + color_temp, + ) + actions = list() + for action in scene.actions: + action.target=ResourceIdentifier(rid=action.target.rid,rtype='light') + action.action.color_temperature.mirek=color_temp + action.action.dimming.brightness=brightness + actions.append(action) + update_obj = ScenePut(actions=actions) + await bridge.scenes.scene.update(scene.id, update_obj) class SimpleSwitch(SwitchEntity, RestoreEntity): From e71bbeff4994834f1a6aa94d0197ec6603a96611 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 16 Sep 2024 15:03:26 +0000 Subject: [PATCH 13/23] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- .../adaptive_lighting/hue_utils.py | 4 ++-- custom_components/adaptive_lighting/switch.py | 24 +++++++++++-------- 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/custom_components/adaptive_lighting/hue_utils.py b/custom_components/adaptive_lighting/hue_utils.py index 2acad3c3..4b3fb728 100644 --- a/custom_components/adaptive_lighting/hue_utils.py +++ b/custom_components/adaptive_lighting/hue_utils.py @@ -2,10 +2,10 @@ from dataclasses import dataclass + @dataclass class ResourceIdentifier: - """ - Represent a ResourceIdentifier object as used by the Hue api. + """Represent a ResourceIdentifier object as used by the Hue api. clip-api.schema.json#/definitions/ResourceIdentifierGet clip-api.schema.json#/definitions/ResourceIdentifierPost diff --git a/custom_components/adaptive_lighting/switch.py b/custom_components/adaptive_lighting/switch.py index bb615776..f2271b35 100644 --- a/custom_components/adaptive_lighting/switch.py +++ b/custom_components/adaptive_lighting/switch.py @@ -10,14 +10,12 @@ from datetime import timedelta from typing import TYPE_CHECKING, Any, Literal -from aiohue import HueBridgeV2 -from aiohue.v2.models.scene import ScenePut -from .hue_utils import ResourceIdentifier - import homeassistant.helpers.config_validation as cv import homeassistant.util.dt as dt_util import ulid_transform import voluptuous as vol +from aiohue import HueBridgeV2 +from aiohue.v2.models.scene import ScenePut from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, @@ -78,6 +76,8 @@ from homeassistant.helpers import entity_platform, entity_registry from homeassistant.helpers.entity_component import async_update_entity +from .hue_utils import ResourceIdentifier + if [MAJOR_VERSION, MINOR_VERSION] < [2023, 9]: from homeassistant.helpers.entity import DeviceInfo else: @@ -1591,11 +1591,13 @@ async def update_hue_run(self, service_data: ServiceData): config_entry = config_entries[0] color_temp = color_temperature_kelvin_to_mired( - service_data[ATTR_COLOR_TEMP_KELVIN], - ) + service_data[ATTR_COLOR_TEMP_KELVIN], + ) brightness = self._settings["brightness_pct"] - async with HueBridgeV2(config_entry.data["host"], config_entry.data["api_key"]) as bridge: + async with HueBridgeV2( + config_entry.data["host"], config_entry.data["api_key"] + ) as bridge: for scene in bridge.scenes: if self.hue_keyword in scene.metadata.name: _LOGGER.debug( @@ -1607,9 +1609,11 @@ async def update_hue_run(self, service_data: ServiceData): ) actions = list() for action in scene.actions: - action.target=ResourceIdentifier(rid=action.target.rid,rtype='light') - action.action.color_temperature.mirek=color_temp - action.action.dimming.brightness=brightness + action.target = ResourceIdentifier( + rid=action.target.rid, rtype="light" + ) + action.action.color_temperature.mirek = color_temp + action.action.dimming.brightness = brightness actions.append(action) update_obj = ScenePut(actions=actions) await bridge.scenes.scene.update(scene.id, update_obj) From 4516a893fb56f883c1e8cd981bee5ddb455d4a3e Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 16 Sep 2024 15:09:34 +0000 Subject: [PATCH 14/23] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- custom_components/adaptive_lighting/switch.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/custom_components/adaptive_lighting/switch.py b/custom_components/adaptive_lighting/switch.py index 92d77649..b526e663 100644 --- a/custom_components/adaptive_lighting/switch.py +++ b/custom_components/adaptive_lighting/switch.py @@ -1597,7 +1597,7 @@ async def update_hue_run(self, service_data: ServiceData): async with HueBridgeV2( config_entry.data["host"], - config_entry.data["api_key"] + config_entry.data["api_key"], ) as bridge: for scene in bridge.scenes: if self.hue_keyword in scene.metadata.name: @@ -1612,7 +1612,7 @@ async def update_hue_run(self, service_data: ServiceData): for action in scene.actions: action.target = ResourceIdentifier( rid=action.target.rid, - rtype="light" + rtype="light", ) action.action.color_temperature.mirek = color_temp action.action.dimming.brightness = brightness From 30fd0d88450c2a3b018c562d34e2f17cd4c8f6d9 Mon Sep 17 00:00:00 2001 From: Benoit Anastay <45088785+BenoitAnastay@users.noreply.github.com> Date: Mon, 16 Sep 2024 17:11:30 +0200 Subject: [PATCH 15/23] =?UTF-8?q?=F0=9F=9A=A8=20lint?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- custom_components/adaptive_lighting/switch.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/custom_components/adaptive_lighting/switch.py b/custom_components/adaptive_lighting/switch.py index f2271b35..92d77649 100644 --- a/custom_components/adaptive_lighting/switch.py +++ b/custom_components/adaptive_lighting/switch.py @@ -1596,7 +1596,8 @@ async def update_hue_run(self, service_data: ServiceData): brightness = self._settings["brightness_pct"] async with HueBridgeV2( - config_entry.data["host"], config_entry.data["api_key"] + config_entry.data["host"], + config_entry.data["api_key"] ) as bridge: for scene in bridge.scenes: if self.hue_keyword in scene.metadata.name: @@ -1610,7 +1611,8 @@ async def update_hue_run(self, service_data: ServiceData): actions = list() for action in scene.actions: action.target = ResourceIdentifier( - rid=action.target.rid, rtype="light" + rid=action.target.rid, + rtype="light" ) action.action.color_temperature.mirek = color_temp action.action.dimming.brightness = brightness From 6e4a4191af4deb03351c973b8b8c9288782e9293 Mon Sep 17 00:00:00 2001 From: Benoit Anastay <45088785+BenoitAnastay@users.noreply.github.com> Date: Mon, 16 Sep 2024 17:16:07 +0200 Subject: [PATCH 16/23] =?UTF-8?q?=F0=9F=9A=A8=20lint?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- custom_components/adaptive_lighting/hue_utils.py | 2 +- custom_components/adaptive_lighting/switch.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/custom_components/adaptive_lighting/hue_utils.py b/custom_components/adaptive_lighting/hue_utils.py index 4b3fb728..91276cd5 100644 --- a/custom_components/adaptive_lighting/hue_utils.py +++ b/custom_components/adaptive_lighting/hue_utils.py @@ -1,4 +1,4 @@ -"""Help fixing a serialization issue""" +"""Help fixing a serialization issue.""" from dataclasses import dataclass diff --git a/custom_components/adaptive_lighting/switch.py b/custom_components/adaptive_lighting/switch.py index 92d77649..fca6ee04 100644 --- a/custom_components/adaptive_lighting/switch.py +++ b/custom_components/adaptive_lighting/switch.py @@ -1608,7 +1608,7 @@ async def update_hue_run(self, service_data: ServiceData): brightness, color_temp, ) - actions = list() + actions = [] for action in scene.actions: action.target = ResourceIdentifier( rid=action.target.rid, From 5e4064792358ef1e5360a6eacd3228054af25dd0 Mon Sep 17 00:00:00 2001 From: Benoit Anastay <45088785+BenoitAnastay@users.noreply.github.com> Date: Mon, 16 Sep 2024 18:11:38 +0200 Subject: [PATCH 17/23] =?UTF-8?q?=F0=9F=8E=A8=20Set=20`color=5Ftemp`=20for?= =?UTF-8?q?=20lights=20individually?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- custom_components/adaptive_lighting/switch.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/custom_components/adaptive_lighting/switch.py b/custom_components/adaptive_lighting/switch.py index 2ba5d149..da379c38 100644 --- a/custom_components/adaptive_lighting/switch.py +++ b/custom_components/adaptive_lighting/switch.py @@ -1252,7 +1252,7 @@ async def prepare_adaptation_data( context = context or self.create_context("adapt_lights") - await self.update_hue_run(service_data) + await self.update_hue_run() return prepare_adaptation_data( self.hass, @@ -1577,7 +1577,7 @@ async def _sleep_mode_switch_state_event_action(self, event: Event) -> None: force=True, ) - async def update_hue_run(self, service_data: ServiceData): + async def update_hue_run(self): """Function updating HUE scene.""" if self.hue_keyword is None: return @@ -1591,8 +1591,9 @@ async def update_hue_run(self, service_data: ServiceData): config_entry = config_entries[0] color_temp = color_temperature_kelvin_to_mired( - service_data[ATTR_COLOR_TEMP_KELVIN], + self._settings["color_temp_kelvin"], ) + brightness = self._settings["brightness_pct"] async with HueBridgeV2( @@ -1614,6 +1615,11 @@ async def update_hue_run(self, service_data: ServiceData): rid=action.target.rid, rtype="light", ) + light = bridge.lights.get(action.target.rid) + color_temp = clamp(color_temp, + light.color_temperature.mirek_schema.mirek_minimum, + light.color_temperature.mirek_schema.mirek_maximum, + ) action.action.color_temperature.mirek = color_temp action.action.dimming.brightness = brightness actions.append(action) From d8a4f5584178b91f9944610161f64f223da6ce97 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 16 Sep 2024 16:09:56 +0000 Subject: [PATCH 18/23] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- custom_components/adaptive_lighting/switch.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/custom_components/adaptive_lighting/switch.py b/custom_components/adaptive_lighting/switch.py index da379c38..660addfa 100644 --- a/custom_components/adaptive_lighting/switch.py +++ b/custom_components/adaptive_lighting/switch.py @@ -1616,9 +1616,10 @@ async def update_hue_run(self): rtype="light", ) light = bridge.lights.get(action.target.rid) - color_temp = clamp(color_temp, - light.color_temperature.mirek_schema.mirek_minimum, - light.color_temperature.mirek_schema.mirek_maximum, + color_temp = clamp( + color_temp, + light.color_temperature.mirek_schema.mirek_minimum, + light.color_temperature.mirek_schema.mirek_maximum, ) action.action.color_temperature.mirek = color_temp action.action.dimming.brightness = brightness From 47bb47026396bf98248d67ef4ec6634827b683e4 Mon Sep 17 00:00:00 2001 From: Benoit Anastay <45088785+BenoitAnastay@users.noreply.github.com> Date: Mon, 16 Sep 2024 18:25:42 +0200 Subject: [PATCH 19/23] =?UTF-8?q?=F0=9F=90=9B=20Updates=20scenes=20when=20?= =?UTF-8?q?lights=20are=20off?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- custom_components/adaptive_lighting/switch.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/custom_components/adaptive_lighting/switch.py b/custom_components/adaptive_lighting/switch.py index 660addfa..cb3d093d 100644 --- a/custom_components/adaptive_lighting/switch.py +++ b/custom_components/adaptive_lighting/switch.py @@ -1252,8 +1252,6 @@ async def prepare_adaptation_data( context = context or self.create_context("adapt_lights") - await self.update_hue_run() - return prepare_adaptation_data( self.hass, light, @@ -1401,6 +1399,8 @@ async def _update_attrs_and_maybe_adapt_lights( # noqa: PLR0912 ) self.async_write_ha_state() + await self.update_hue_run() + if not force and self._only_once: return From 40357ac74dcf38e4ba9b9ca2796fc03b55639979 Mon Sep 17 00:00:00 2001 From: Benoit Anastay <45088785+BenoitAnastay@users.noreply.github.com> Date: Sun, 22 Sep 2024 00:10:12 +0200 Subject: [PATCH 20/23] =?UTF-8?q?=F0=9F=90=9B=20Fix=20`internal=20servor?= =?UTF-8?q?=20error`=20with=20some=20values?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- custom_components/adaptive_lighting/switch.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/custom_components/adaptive_lighting/switch.py b/custom_components/adaptive_lighting/switch.py index cb3d093d..c853d873 100644 --- a/custom_components/adaptive_lighting/switch.py +++ b/custom_components/adaptive_lighting/switch.py @@ -1594,7 +1594,7 @@ async def update_hue_run(self): self._settings["color_temp_kelvin"], ) - brightness = self._settings["brightness_pct"] + brightness = round(self._settings["brightness_pct"], 2) async with HueBridgeV2( config_entry.data["host"], From 908081c610f527b894ab0f439171bdbb1377484b Mon Sep 17 00:00:00 2001 From: Benoit Anastay <45088785+BenoitAnastay@users.noreply.github.com> Date: Mon, 23 Sep 2024 00:32:58 +0200 Subject: [PATCH 21/23] =?UTF-8?q?=E2=9A=A1=EF=B8=8F=20Add=20a=205=20minute?= =?UTF-8?q?s=20delay=20between=20updates=20of=20each=20keyword?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- custom_components/adaptive_lighting/switch.py | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/custom_components/adaptive_lighting/switch.py b/custom_components/adaptive_lighting/switch.py index c853d873..f8301346 100644 --- a/custom_components/adaptive_lighting/switch.py +++ b/custom_components/adaptive_lighting/switch.py @@ -206,6 +206,8 @@ # Keep a short domain version for the context instances (which can only be 36 chars) _DOMAIN_SHORT = "al" +# The interval of time between each scene updates +HUE_SCENE_UPDATE_DELAY = 300 # 5 minutes def create_context( name: str, @@ -1582,6 +1584,19 @@ async def update_hue_run(self): if self.hue_keyword is None: return + timer = self.manager.hue_scene_update_timers.get(self.hue_keyword) + if (timer is not None + and timer.is_running()): + _LOGGER.debug( + "%s: Not updating %s because there is throttle, remaining_time:%s", + self._name, + self.hue_keyword, + timer.remaining_time(), + ) + return + + self.manager.start_hue_scene_update_throttle(self.hue_keyword) + _LOGGER.debug( "%s: Will updates scenes containing %s", self._name, @@ -1743,6 +1758,9 @@ def __init__(self, hass: HomeAssistant) -> None: # Track light transitions self.transition_timers: dict[str, _AsyncSingleShotTimer] = {} + # Handle HUE delay to avoid overloading the bridge + self.hue_scene_update_timers: dict[str, _AsyncSingleShotTimer] = {} + # Track _execute_cancellable_adaptation_calls tasks self.adaptation_tasks = set() @@ -2200,6 +2218,24 @@ async def reset(): self._handle_timer(light, self.transition_timers, last_transition, reset) + def start_hue_scene_update_throttle(self, scene: str) -> None: + """Set a timer between each scene update call.""" + + _LOGGER.debug( + "Start throttle timer of %s seconds for scene %s", + HUE_SCENE_UPDATE_DELAY, + scene, + ) + + async def reset(): + # Called when the timer expires, doesn't need to do anything + _LOGGER.debug( + "Throttle finished for scene %s", + scene, + ) + + self._handle_timer(scene, self.hue_scene_update_timers, HUE_SCENE_UPDATE_DELAY, reset) + def set_auto_reset_manual_control_times(self, lights: list[str], time: float): """Set the time after which the lights are automatically reset.""" if time == 0: From d81c77a940170a0a3783c709f0b41d9fdddde14b Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Sun, 22 Sep 2024 22:31:54 +0000 Subject: [PATCH 22/23] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- custom_components/adaptive_lighting/switch.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/custom_components/adaptive_lighting/switch.py b/custom_components/adaptive_lighting/switch.py index f8301346..ab7405d3 100644 --- a/custom_components/adaptive_lighting/switch.py +++ b/custom_components/adaptive_lighting/switch.py @@ -207,7 +207,8 @@ _DOMAIN_SHORT = "al" # The interval of time between each scene updates -HUE_SCENE_UPDATE_DELAY = 300 # 5 minutes +HUE_SCENE_UPDATE_DELAY = 300 # 5 minutes + def create_context( name: str, @@ -1585,8 +1586,7 @@ async def update_hue_run(self): return timer = self.manager.hue_scene_update_timers.get(self.hue_keyword) - if (timer is not None - and timer.is_running()): + if timer is not None and timer.is_running(): _LOGGER.debug( "%s: Not updating %s because there is throttle, remaining_time:%s", self._name, @@ -2220,7 +2220,6 @@ async def reset(): def start_hue_scene_update_throttle(self, scene: str) -> None: """Set a timer between each scene update call.""" - _LOGGER.debug( "Start throttle timer of %s seconds for scene %s", HUE_SCENE_UPDATE_DELAY, @@ -2234,7 +2233,9 @@ async def reset(): scene, ) - self._handle_timer(scene, self.hue_scene_update_timers, HUE_SCENE_UPDATE_DELAY, reset) + self._handle_timer( + scene, self.hue_scene_update_timers, HUE_SCENE_UPDATE_DELAY, reset + ) def set_auto_reset_manual_control_times(self, lights: list[str], time: float): """Set the time after which the lights are automatically reset.""" From 56cefce62a861ec2f2064a46ddadb194fba4341b Mon Sep 17 00:00:00 2001 From: Benoit Anastay <45088785+BenoitAnastay@users.noreply.github.com> Date: Mon, 23 Sep 2024 18:53:27 +0200 Subject: [PATCH 23/23] =?UTF-8?q?=F0=9F=9A=A8=20lint?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- custom_components/adaptive_lighting/switch.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/custom_components/adaptive_lighting/switch.py b/custom_components/adaptive_lighting/switch.py index ab7405d3..19fc0063 100644 --- a/custom_components/adaptive_lighting/switch.py +++ b/custom_components/adaptive_lighting/switch.py @@ -2234,7 +2234,10 @@ async def reset(): ) self._handle_timer( - scene, self.hue_scene_update_timers, HUE_SCENE_UPDATE_DELAY, reset + scene, + self.hue_scene_update_timers, + HUE_SCENE_UPDATE_DELAY, + reset, ) def set_auto_reset_manual_control_times(self, lights: list[str], time: float):