From 99490b4ad5ac03ef4c1a7efd7ed2afa8868438b0 Mon Sep 17 00:00:00 2001 From: Bas Nijholt Date: Sat, 12 Sep 2020 12:21:40 +0200 Subject: [PATCH] switch to a simpler setup --- .../circadian_lighting/__init__.py | 292 +----------------- .../circadian_lighting/manifest.json | 10 +- .../circadian_lighting/sensor.py | 86 ------ .../circadian_lighting/services.yaml | 2 - .../circadian_lighting/switch.py | 52 ++-- 5 files changed, 32 insertions(+), 410 deletions(-) delete mode 100755 custom_components/circadian_lighting/sensor.py delete mode 100644 custom_components/circadian_lighting/services.yaml diff --git a/custom_components/circadian_lighting/__init__.py b/custom_components/circadian_lighting/__init__.py index 1a0967c7..ca7f15ac 100755 --- a/custom_components/circadian_lighting/__init__.py +++ b/custom_components/circadian_lighting/__init__.py @@ -1,291 +1 @@ -""" -Circadian Lighting Component for Home-Assistant. - -This component calculates color temperature and brightness to synchronize -your color changing lights with perceived color temperature of the sky throughout -the day. This gives your environment a more natural feel, with cooler whites during -the midday and warmer tints near twilight and dawn. - -In addition, the component sets your lights to a nice warm white at 1% in "Sleep" mode, -which is far brighter than starlight but won't reset your circadian rhythm or break down -too much rhodopsin in your eyes. - -Human circadian rhythms are heavily influenced by ambient light levels and -hues. Hormone production, brainwave activity, mood and wakefulness are -just some of the cognitive functions tied to cyclical natural light. -http://en.wikipedia.org/wiki/Zeitgeber - -Here's some further reading: - -http://www.cambridgeincolour.com/tutorials/sunrise-sunset-calculator.htm -http://en.wikipedia.org/wiki/Color_temperature - -Technical notes: I had to make a lot of assumptions when writing this app - * There are no considerations for weather or altitude, but does use your - hub's location to calculate the sun position. - * The component doesn't calculate a true "Blue Hour" -- it just sets the - lights to 2700K (warm white) until your hub goes into Night mode -""" - -import logging -from datetime import timedelta - -import astral -import voluptuous as vol - -import homeassistant.helpers.config_validation as cv -import homeassistant.util.dt as dt_util -from homeassistant.components.light import ATTR_TRANSITION, VALID_TRANSITION -from homeassistant.const import ( - CONF_ELEVATION, - CONF_LATITUDE, - CONF_LONGITUDE, - SUN_EVENT_SUNRISE, - SUN_EVENT_SUNSET, -) -from homeassistant.helpers.discovery import load_platform -from homeassistant.helpers.dispatcher import async_dispatcher_send -from homeassistant.helpers.event import ( - async_track_sunrise, - async_track_sunset, - async_track_time_change, - async_track_time_interval, -) -from homeassistant.util.color import ( - color_RGB_to_xy, - color_temperature_to_rgb, - color_xy_to_hs, -) - -_LOGGER = logging.getLogger(__name__) - -DOMAIN = "circadian_lighting" -CIRCADIAN_LIGHTING_UPDATE_TOPIC = f"{DOMAIN}_update" -SUN_EVENT_NOON = "solar_noon" -SUN_EVENT_MIDNIGHT = "solar_midnight" - -CONF_MIN_CT, DEFAULT_MIN_CT = "min_colortemp", 2500 -CONF_MAX_CT, DEFAULT_MAX_CT = "max_colortemp", 5500 -CONF_INTERVAL, DEFAULT_INTERVAL = "interval", 300 -CONF_SUNRISE_OFFSET = "sunrise_offset" -CONF_SUNSET_OFFSET = "sunset_offset" -CONF_SUNRISE_TIME = "sunrise_time" -CONF_SUNSET_TIME = "sunset_time" -DEFAULT_TRANSITION = 60 -CONF_PROFILE, DEFAULT_PROFILE = "profile", "default" - -_DOMAIN_SCHEMA = vol.Schema( - { - vol.Optional(CONF_MIN_CT, default=DEFAULT_MIN_CT): vol.All(vol.Coerce(int), vol.Range(min=1000, max=10000)), - vol.Optional(CONF_MAX_CT, default=DEFAULT_MAX_CT): vol.All(vol.Coerce(int), vol.Range(min=1000, max=10000)), - vol.Optional(CONF_SUNRISE_OFFSET): cv.time_period_str, - vol.Optional(CONF_SUNSET_OFFSET): cv.time_period_str, - vol.Optional(CONF_SUNRISE_TIME): cv.time, - vol.Optional(CONF_SUNSET_TIME): cv.time, - vol.Optional(CONF_LATITUDE): cv.latitude, - vol.Optional(CONF_LONGITUDE): cv.longitude, - vol.Optional(CONF_ELEVATION): float, - vol.Optional(CONF_INTERVAL, default=DEFAULT_INTERVAL): cv.time_period, - vol.Optional(ATTR_TRANSITION, default=DEFAULT_TRANSITION): VALID_TRANSITION, - vol.Optional(CONF_PROFILE, default=DEFAULT_PROFILE): cv.string, - } -) - - -def _all_unique_profiles(value): - """Validate that all enties have a unique profile name.""" - hosts = [device[CONF_PROFILE] for device in value] - schema = vol.Schema(vol.Unique()) - schema(hosts) - return value - - -CONFIG_SCHEMA = vol.Schema({DOMAIN: vol.All(cv.ensure_list, [_DOMAIN_SCHEMA], _all_unique_profiles)}, extra=vol.ALLOW_EXTRA,) - - -def setup(hass, config): - """Set up the Circadian Lighting platform.""" - if DOMAIN not in hass.data: - hass.data[DOMAIN] = {} - configs = config[DOMAIN] - for conf in configs: - profile = conf[CONF_PROFILE] - hass.data[DOMAIN][profile] = CircadianLighting( - hass, - min_colortemp=conf[CONF_MIN_CT], - max_colortemp=conf[CONF_MAX_CT], - sunrise_offset=conf.get(CONF_SUNRISE_OFFSET), - sunset_offset=conf.get(CONF_SUNSET_OFFSET), - sunrise_time=conf.get(CONF_SUNRISE_TIME), - sunset_time=conf.get(CONF_SUNSET_TIME), - latitude=conf.get(CONF_LATITUDE, hass.config.latitude), - longitude=conf.get(CONF_LONGITUDE, hass.config.longitude), - elevation=conf.get(CONF_ELEVATION, hass.config.elevation), - interval=conf[CONF_INTERVAL], - transition=conf[ATTR_TRANSITION], - profile=profile, - ) - load_platform(hass, "sensor", DOMAIN, {}, config) - - return True - - -class CircadianLighting: - """Calculate universal Circadian values.""" - - def __init__( - self, hass, min_colortemp, max_colortemp, sunrise_offset, sunset_offset, sunrise_time, sunset_time, latitude, longitude, elevation, interval, transition, profile, - ): - self.hass = hass - self._min_colortemp = min_colortemp - self._max_colortemp = max_colortemp - self._sunrise_offset = sunrise_offset - self._sunset_offset = sunset_offset - self._manual_sunset = sunset_time - self._manual_sunrise = sunrise_time - self._latitude = latitude - self._longitude = longitude - self._elevation = elevation - self._transition = transition - self._profile = profile - _LOGGER.debug("profile: %s", self._profile) - - self._percent = self.calc_percent() - self._colortemp = self.calc_colortemp() - self._rgb_color = self.calc_rgb() - self._xy_color = self.calc_xy() - self._hs_color = self.calc_hs() - - if self._manual_sunrise is not None: - async_track_time_change( - self.hass, self.update, hour=self._manual_sunrise.hour, minute=self._manual_sunrise.minute, second=self._manual_sunrise.second, - ) - else: - async_track_sunrise(self.hass, self.update, self._sunrise_offset) - - if self._manual_sunset is not None: - async_track_time_change( - self.hass, self.update, hour=self._manual_sunset.hour, minute=self._manual_sunset.minute, second=self._manual_sunset.second, - ) - else: - async_track_sunset(self.hass, self.update, self._sunset_offset) - - async_track_time_interval(self.hass, self.update, interval) - - def _replace_time(self, date, key): - other_date = self._manual_sunrise if key == "sunrise" else self._manual_sunset - return date.replace(hour=other_date.hour, minute=other_date.minute, second=other_date.second, microsecond=other_date.microsecond,) - - def get_sunrise_sunset(self, date): - if self._manual_sunrise is not None and self._manual_sunset is not None: - sunrise = self._replace_time(date, "sunrise") - sunset = self._replace_time(date, "sunset") - solar_noon = sunrise + (sunset - sunrise) / 2 - solar_midnight = sunset + ((sunrise + timedelta(days=1)) - sunset) / 2 - else: - location = astral.Location() - location.name = "name" - location.region = "region" - location.latitude = self._latitude - location.longitude = self._longitude - location.elevation = self._elevation - - if self._manual_sunrise is not None: - sunrise = self._replace_time(date, "sunrise") - else: - sunrise = location.sunrise(date) - - if self._manual_sunset is not None: - sunset = self._replace_time(date, "sunset") - else: - sunset = location.sunset(date) - - solar_noon = location.solar_noon(date) - solar_midnight = location.solar_midnight(date) - - if self._sunrise_offset is not None: - sunrise = sunrise + self._sunrise_offset - if self._sunset_offset is not None: - sunset = sunset + self._sunset_offset - - datetimes = { - SUN_EVENT_SUNRISE: sunrise, - SUN_EVENT_SUNSET: sunset, - SUN_EVENT_NOON: solar_noon, - SUN_EVENT_MIDNIGHT: solar_midnight, - } - - return {k: dt.astimezone(dt_util.UTC).timestamp() for k, dt in datetimes.items()} - - def calc_percent(self): - now = dt_util.utcnow() - now_ts = now.timestamp() - - today = self.get_sunrise_sunset(now) - if now_ts < today[SUN_EVENT_SUNRISE]: - # It's before sunrise (after midnight), because it's before - # sunrise (and after midnight) sunset must have happend yesterday. - yesterday = self.get_sunrise_sunset(now - timedelta(days=1)) - if today[SUN_EVENT_MIDNIGHT] > today[SUN_EVENT_SUNSET] and yesterday[SUN_EVENT_MIDNIGHT] > yesterday[SUN_EVENT_SUNSET]: - # Solar midnight is after sunset so use yesterdays's time - today[SUN_EVENT_MIDNIGHT] = yesterday[SUN_EVENT_MIDNIGHT] - today[SUN_EVENT_SUNSET] = yesterday[SUN_EVENT_SUNSET] - elif now_ts > today[SUN_EVENT_SUNSET]: - # It's after sunset (before midnight), because it's after sunset - # (and before midnight) sunrise should happen tomorrow. - tomorrow = self.get_sunrise_sunset(now + timedelta(days=1)) - if today[SUN_EVENT_MIDNIGHT] < today[SUN_EVENT_SUNRISE] and tomorrow[SUN_EVENT_MIDNIGHT] < tomorrow[SUN_EVENT_SUNRISE]: - # Solar midnight is before sunrise so use tomorrow's time - today[SUN_EVENT_MIDNIGHT] = tomorrow[SUN_EVENT_MIDNIGHT] - today[SUN_EVENT_SUNRISE] = tomorrow[SUN_EVENT_SUNRISE] - - # Figure out where we are in time so we know which half of the - # parabola to calculate. We're generating a different - # sunset-sunrise parabola for before and after solar midnight. - # because it might not be half way between sunrise and sunset. - # We're also generating a different parabola for sunrise-sunset. - - # sunrise -> sunset parabola - if today[SUN_EVENT_SUNRISE] < now_ts < today[SUN_EVENT_SUNSET]: - h = today[SUN_EVENT_NOON] - k = 100 - # parabola before solar_noon else after solar_noon - x = today[SUN_EVENT_SUNRISE] if now_ts < today[SUN_EVENT_NOON] else today[SUN_EVENT_SUNSET] - - # sunset -> sunrise parabola - elif today[SUN_EVENT_SUNSET] < now_ts < today[SUN_EVENT_SUNRISE]: - h = today[SUN_EVENT_MIDNIGHT] - k = -100 - # parabola before solar_midnight else after solar_midnight - x = today[SUN_EVENT_SUNSET] if now_ts < today[SUN_EVENT_MIDNIGHT] else today[SUN_EVENT_SUNRISE] - - y = 0 - a = (y - k) / (h - x) ** 2 - percentage = a * (now_ts - h) ** 2 + k - return percentage - - def calc_colortemp(self): - if self._percent > 0: - delta = self._max_colortemp - self._min_colortemp - percent = self._percent / 100 - return (delta * percent) + self._min_colortemp - else: - return self._min_colortemp - - def calc_rgb(self): - return color_temperature_to_rgb(self._colortemp) - - def calc_xy(self): - return color_RGB_to_xy(*self.calc_rgb()) - - def calc_hs(self): - return color_xy_to_hs(*self.calc_xy()) - - async def update(self, _=None): - """Update Circadian Values.""" - self._percent = self.calc_percent() - self._colortemp = self.calc_colortemp() - self._rgb_color = self.calc_rgb() - self._xy_color = self.calc_xy() - self._hs_color = self.calc_hs() - async_dispatcher_send(self.hass, CIRCADIAN_LIGHTING_UPDATE_TOPIC) +"""Adaptive Lighting Component for Home-Assistant.""" diff --git a/custom_components/circadian_lighting/manifest.json b/custom_components/circadian_lighting/manifest.json index 756dad08..4b103323 100644 --- a/custom_components/circadian_lighting/manifest.json +++ b/custom_components/circadian_lighting/manifest.json @@ -1,8 +1,8 @@ { - "domain": "circadian_lighting", - "name": "Circadian Lighting", - "documentation": "https://github.com/claytonjn/hass-circadian_lighting", + "domain": "adaptive_lighting", + "name": "Adaptive Lighting", + "documentation": "https://github.com/basnijholt/adaptive_lighting", "dependencies": [], - "codeowners": ["@claytonjn"], - "requirements": ["astral==1.10.1"] + "codeowners": ["@claytonjn", "@basnijholt"], + "requirements": [] } diff --git a/custom_components/circadian_lighting/sensor.py b/custom_components/circadian_lighting/sensor.py deleted file mode 100755 index 5b5e2855..00000000 --- a/custom_components/circadian_lighting/sensor.py +++ /dev/null @@ -1,86 +0,0 @@ -""" -Circadian Lighting Sensor for Home-Assistant. -""" - -from homeassistant.core import callback -from homeassistant.helpers.dispatcher import async_dispatcher_connect -from homeassistant.helpers.entity import Entity - -from . import CIRCADIAN_LIGHTING_UPDATE_TOPIC, DEFAULT_PROFILE, DOMAIN - -ICON = "mdi:theme-light-dark" - - -def setup_platform(hass, config, add_devices, discovery_info=None): - """Set up the Circadian Lighting sensor.""" - sensors = [CircadianSensor(hass, circadian_lighting) for circadian_lighting in hass.data[DOMAIN].values()] - add_devices(sensors, True) - return True - - -class CircadianSensor(Entity): - """Representation of a Circadian Lighting sensor.""" - - def __init__(self, hass, circadian_lighting): - """Initialize the Circadian Lighting sensor.""" - self._circadian_lighting = circadian_lighting - self._name = "Circadian Values" - self._entity_id = "sensor.circadian_values" - profile = circadian_lighting._profile - if profile != DEFAULT_PROFILE: - self._name += f" {profile}" - self._entity_id += f"_{profile.lower()}" - self._unit_of_measurement = "%" - self._icon = ICON - - @property - def entity_id(self): - """Return the entity ID of the sensor.""" - return self._entity_id - - @property - def name(self): - """Return the name of the sensor.""" - return self._name - - @property - def state(self): - """Return the state of the sensor.""" - return self._circadian_lighting._percent - - @property - def unit_of_measurement(self): - """Return the unit of measurement.""" - return self._unit_of_measurement - - @property - def icon(self): - """Icon to use in the frontend, if any.""" - return self._icon - - @property - def hs_color(self): - return self._circadian_lighting._hs_color - - @property - def device_state_attributes(self): - """Return the attributes of the sensor.""" - return { - "colortemp": self._circadian_lighting._colortemp, - "rgb_color": self._circadian_lighting._rgb_color, - "xy_color": self._circadian_lighting._xy_color, - } - - @property - def should_poll(self) -> bool: - """Disable polling.""" - return False - - async def async_added_to_hass(self) -> None: - """Connect dispatcher to signal from CircadianLighting object.""" - self.async_on_remove(async_dispatcher_connect(self.hass, CIRCADIAN_LIGHTING_UPDATE_TOPIC, self._update_callback)) - - @callback - def _update_callback(self) -> None: - """Triggers update of properties.""" - self.async_schedule_update_ha_state(force_refresh=False) diff --git a/custom_components/circadian_lighting/services.yaml b/custom_components/circadian_lighting/services.yaml deleted file mode 100644 index 586f06ea..00000000 --- a/custom_components/circadian_lighting/services.yaml +++ /dev/null @@ -1,2 +0,0 @@ -values_update: - description: Updates values for Circadian Lighting. diff --git a/custom_components/circadian_lighting/switch.py b/custom_components/circadian_lighting/switch.py index b86a0bf4..61a9e793 100755 --- a/custom_components/circadian_lighting/switch.py +++ b/custom_components/circadian_lighting/switch.py @@ -1,5 +1,5 @@ """ -Circadian Lighting Component for Home-Assistant. +Adaptive Lighting Component for Home-Assistant. This component calculates color temperature and brightness to synchronize your color changing lights with perceived color temperature of the sky throughout @@ -7,10 +7,10 @@ the day. This gives your environment a more natural feel, with cooler whites dur the midday and warmer tints near twilight and dawn. In addition, the component sets your lights to a nice warm white at 1% in "Sleep" mode, -which is far brighter than starlight but won't reset your circadian rhythm or break down +which is far brighter than starlight but won't reset your adaptive rhythm or break down too much rhodopsin in your eyes. -Human circadian rhythms are heavily influenced by ambient light levels and +Human adaptive rhythms are heavily influenced by ambient light levels and hues. Hormone production, brainwave activity, mood and wakefulness are just some of the cognitive functions tied to cyclical natural light. http://en.wikipedia.org/wiki/Zeitgeber @@ -75,7 +75,7 @@ _LOGGER = logging.getLogger(__name__) ICON = "mdi:theme-light-dark" -DOMAIN = "circadian_lighting" +DOMAIN = "adaptive_lighting" SUN_EVENT_NOON = "solar_noon" SUN_EVENT_MIDNIGHT = "solar_midnight" @@ -106,8 +106,8 @@ DEFAULT_TRANSITION = 60 PLATFORM_SCHEMA = vol.Schema( { - vol.Required(CONF_PLATFORM): "circadian_lighting", - vol.Optional(CONF_NAME, default="Circadian Lighting"): cv.string, + vol.Required(CONF_PLATFORM): "adaptive_lighting", + vol.Optional(CONF_NAME, default="Adaptive Lighting"): cv.string, vol.Optional(CONF_LIGHTS_BRIGHT): cv.entity_ids, vol.Optional(CONF_LIGHTS_CT): cv.entity_ids, vol.Optional(CONF_LIGHTS_RGB): cv.entity_ids, @@ -141,9 +141,9 @@ PLATFORM_SCHEMA = vol.Schema( ), vol.Optional(CONF_SLEEP_ENTITY): cv.entity_id, vol.Optional(CONF_SLEEP_STATE): vol.All(cv.ensure_list, [cv.string]), - vol.Optional(CONF_SUNRISE_OFFSET, default=0): cv.time_period_str, + vol.Optional(CONF_SUNRISE_OFFSET, default=0): cv.time_period, vol.Optional(CONF_SUNRISE_TIME): cv.time, - vol.Optional(CONF_SUNSET_OFFSET, default=0): cv.time_period_str, + vol.Optional(CONF_SUNSET_OFFSET, default=0): cv.time_period, vol.Optional(CONF_SUNSET_TIME): cv.time, vol.Optional(ATTR_TRANSITION, default=DEFAULT_TRANSITION): VALID_TRANSITION, } @@ -151,8 +151,8 @@ PLATFORM_SCHEMA = vol.Schema( def setup_platform(hass, config, add_devices, discovery_info=None): - """Set up the Circadian Lighting switches.""" - switch = CircadianSwitch( + """Set up the Adaptive Lighting switches.""" + switch = AdaptiveSwitch( hass, name=config[CONF_NAME], lights_brightness=config.get(CONF_LIGHTS_BRIGHT, []), @@ -216,8 +216,8 @@ def _difference_between_states(from_state, to_state): ) -class CircadianSwitch(SwitchEntity, RestoreEntity): - """Representation of a Circadian Lighting switch.""" +class AdaptiveSwitch(SwitchEntity, RestoreEntity): + """Representation of a Adaptive Lighting switch.""" def __init__( self, @@ -248,10 +248,10 @@ class CircadianSwitch(SwitchEntity, RestoreEntity): sunset_time, transition, ): - """Initialize the Circadian Lighting switch.""" + """Initialize the Adaptive Lighting switch.""" self.hass = hass self._name = name - self._entity_id = f"switch.circadian_lighting_{slugify(name)}" + self._entity_id = f"switch.adaptive_lighting_{slugify(name)}" self._state = None self._icon = ICON self._lights_types = dict(zip(lights_ct, repeat("ct"))) @@ -301,7 +301,7 @@ class CircadianSwitch(SwitchEntity, RestoreEntity): @property def is_on(self): - """Return true if circadian lighting is on.""" + """Return true if adaptive lighting is on.""" return self._state async def async_added_to_hass(self): @@ -344,16 +344,16 @@ class CircadianSwitch(SwitchEntity, RestoreEntity): return {"hs_color": self._hs_color, "brightness": self._brightness} async def async_turn_on(self, **kwargs): - """Turn on circadian lighting.""" + """Turn on adaptive lighting.""" self._state = True - await self._update_lights(transition=self._initial_transition) + await self._update_lights(transition=self._initial_transition, force=True) async def async_turn_off(self, **kwargs): - """Turn off circadian lighting.""" + """Turn off adaptive lighting.""" self._state = False def _update_attrs(self, _=None): - """Update Circadian Values.""" + """Update Adaptive Values.""" self._percent = self._calc_percent() self._brightness = self._calc_brightness() self._colortemp_kelvin = self._calc_colortemp_kelvin() @@ -368,14 +368,14 @@ class CircadianSwitch(SwitchEntity, RestoreEntity): self._update_lights(force=False) async def _update_lights(self, lights=None, transition=None, force=True): + self._update_attrs() if self._only_once and not force: return - self._update_attrs() await self._adjust_lights(lights or self._lights, transition) def get_sunrise_sunset(self, date): def _replace_time(date, key): - other_date = getattr(self, f"_manual_{key}") + other_date = getattr(self, f"_{key}_time") return date.replace( hour=other_date.hour, minute=other_date.minute, @@ -386,15 +386,15 @@ class CircadianSwitch(SwitchEntity, RestoreEntity): location = get_astral_location(self.hass) sunrise = ( location.sunrise(date) - if self._manual_sunrise is None + if self._sunrise_time is None else _replace_time(date, "sunrise") ) + self._sunrise_offset sunset = ( location.sunset(date) - if self._manual_sunset is None + if self._sunset_time is None else _replace_time(date, "sunset") ) + self._sunset_offset - if self._manual_sunrise is None and self._manual_sunset is None: + if self._sunrise_time is None and self._sunset_time is None: solar_noon = location.solar_noon(date) solar_midnight = location.solar_midnight(date) else: @@ -555,8 +555,8 @@ class CircadianSwitch(SwitchEntity, RestoreEntity): assert to_state.state == "on" if from_state is None or from_state.state != "on": _LOGGER.debug(_difference_between_states(from_state, to_state)) - await self._update_lights(lights=[entity_id], transition=self._initial_transition) + await self._update_lights(lights=[entity_id], transition=self._initial_transition, force=True) async def _state_changed(self, entity_id, from_state, to_state): _LOGGER.debug(_difference_between_states(from_state, to_state)) - await self._update_lights(transition=self._initial_transition) + await self._update_lights(transition=self._initial_transition, force=True)