Refactor sun component for correctness (#7295)

* Refactor sun component for correctness

* Convert datetimes to dates for astral

* Fix tests for updated code

* Fix times now that calcs are fixed

* Move sun functions to helpers

* Fix flake on new file

* Additional tweaks from review

* Update requirements
This commit is contained in:
Adam Mills authored and Paulus Schoutsen committed 2017-05-09 00:03:34 -07:00
1 parent 419d97fc06
commit 40d27cde0e
19 files changed
+754 -756

No files matched your search

@@ -16,8 +16,6 @@ from homeassistant.const import (
from homeassistant.helpers.event import async_track_sunrise, async_track_sunset
import homeassistant.helpers.config_validation as cv
DEPENDENCIES = ['sun']
_LOGGER = logging.getLogger(__name__)
TRIGGER_SCHEMA = vol.Schema({
@@ -14,12 +14,13 @@ from homeassistant.core import callback
import homeassistant.util.dt as dt_util
from homeassistant.const import STATE_HOME, STATE_NOT_HOME
from homeassistant.helpers.event import (
async_track_point_in_time, async_track_state_change)
async_track_point_in_utc_time, async_track_state_change)
from homeassistant.helpers.sun import is_up, get_astral_event_next
from homeassistant.loader import get_component
import homeassistant.helpers.config_validation as cv
DOMAIN = 'device_sun_light_trigger'
DEPENDENCIES = ['light', 'device_tracker', 'group', 'sun']
DEPENDENCIES = ['light', 'device_tracker', 'group']
CONF_DEVICE_GROUP = 'device_group'
CONF_DISABLE_TURN_OFF = 'disable_turn_off'
@@ -50,7 +51,6 @@ def async_setup(hass, config):
device_tracker = get_component('device_tracker')
group = get_component('group')
light = get_component('light')
sun = get_component('sun')
conf = config[DOMAIN]
disable_turn_off = conf.get(CONF_DISABLE_TURN_OFF)
light_group = conf.get(CONF_LIGHT_GROUP, light.ENTITY_ID_ALL_LIGHTS)
@@ -78,7 +78,7 @@ def async_setup(hass, config):
Async friendly.
"""
next_setting = sun.next_setting(hass)
next_setting = get_astral_event_next(hass, 'sunset')
if not next_setting:
return None
return next_setting - LIGHT_TRANSITION_TIME * len(light_ids)
@@ -103,7 +103,7 @@ def async_setup(hass, config):
# Track every time sun rises so we can schedule a time-based
# pre-sun set event
@callback
def schedule_light_turn_on(entity, old_state, new_state):
def schedule_light_turn_on(now):
"""Turn on all the lights at the moment sun sets.
We will schedule to have each light start after one another
@@ -114,26 +114,26 @@ def async_setup(hass, config):
return
for index, light_id in enumerate(light_ids):
async_track_point_in_time(
async_track_point_in_utc_time(
hass, async_turn_on_factory(light_id),
start_point + index * LIGHT_TRANSITION_TIME)
async_track_state_change(hass, sun.ENTITY_ID, schedule_light_turn_on,
sun.STATE_BELOW_HORIZON, sun.STATE_ABOVE_HORIZON)
async_track_point_in_utc_time(hass, schedule_light_turn_on,
get_astral_event_next(hass, 'sunrise'))
# If the sun is already above horizon schedule the time-based pre-sun set
# event.
if sun.is_on(hass):
schedule_light_turn_on(None, None, None)
if is_up(hass):
schedule_light_turn_on(None)
@callback
def check_light_on_dev_state_change(entity, old_state, new_state):
"""Handle tracked device state changes."""
lights_are_on = group.is_on(hass, light_group)
light_needed = not (lights_are_on or sun.is_on(hass))
light_needed = not (lights_are_on or is_up(hass))
# These variables are needed for the elif check
now = dt_util.now()
now = dt_util.utcnow()
start_point = calc_time_for_light_when_sunset()
# Do we need lights?
@@ -146,7 +146,7 @@ def async_setup(hass, config):
# Check this by seeing if current time is later then the point
# in time when we would start putting the lights on.
elif (start_point and
start_point < now < sun.next_setting(hass)):
start_point < now < get_astral_event_next(hass, 'sunset')):
# Check for every light if it would be on if someone was home
# when the fading in started and turn it on if so
-2
View File
@@ -15,8 +15,6 @@ import homeassistant.util.dt as dt_util
from homeassistant.helpers.entity import Entity
import homeassistant.helpers.config_validation as cv
REQUIREMENTS = ['astral==1.4']
_LOGGER = logging.getLogger(__name__)
DEFAULT_NAME = 'Moon'
+34 -266
View File
@@ -4,20 +4,18 @@ Support for functionality to keep track of the sun.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/sun/
"""
import asyncio
import logging
from datetime import timedelta
import voluptuous as vol
from homeassistant.const import CONF_ELEVATION
from homeassistant.core import callback
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.event import (
track_point_in_utc_time, track_utc_time_change)
async_track_point_in_utc_time, async_track_utc_time_change)
from homeassistant.helpers.sun import (
get_astral_location, get_astral_event_next)
from homeassistant.util import dt as dt_util
import homeassistant.helpers.config_validation as cv
import homeassistant.util as util
REQUIREMENTS = ['astral==1.4']
_LOGGER = logging.getLogger(__name__)
@@ -37,223 +35,16 @@ STATE_ATTR_NEXT_NOON = 'next_noon'
STATE_ATTR_NEXT_RISING = 'next_rising'
STATE_ATTR_NEXT_SETTING = 'next_setting'
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({
vol.Optional(CONF_ELEVATION): cv.positive_int,
}),
}, extra=vol.ALLOW_EXTRA)
def is_on(hass, entity_id=None):
"""Test if the sun is currently up based on the statemachine."""
entity_id = entity_id or ENTITY_ID
return hass.states.is_state(entity_id, STATE_ABOVE_HORIZON)
def next_dawn(hass, entity_id=None):
"""Local datetime object of the next dawn.
Async friendly.
"""
utc_next = next_dawn_utc(hass, entity_id)
return dt_util.as_local(utc_next) if utc_next else None
def next_dawn_utc(hass, entity_id=None):
"""UTC datetime object of the next dawn.
Async friendly.
"""
entity_id = entity_id or ENTITY_ID
state = hass.states.get(ENTITY_ID)
try:
return dt_util.parse_datetime(
state.attributes[STATE_ATTR_NEXT_DAWN])
except (AttributeError, KeyError):
# AttributeError if state is None
# KeyError if STATE_ATTR_NEXT_DAWN does not exist
return None
def next_dusk(hass, entity_id=None):
"""Local datetime object of the next dusk.
Async friendly.
"""
utc_next = next_dusk_utc(hass, entity_id)
return dt_util.as_local(utc_next) if utc_next else None
def next_dusk_utc(hass, entity_id=None):
"""UTC datetime object of the next dusk.
Async friendly.
"""
entity_id = entity_id or ENTITY_ID
state = hass.states.get(ENTITY_ID)
try:
return dt_util.parse_datetime(
state.attributes[STATE_ATTR_NEXT_DUSK])
except (AttributeError, KeyError):
# AttributeError if state is None
# KeyError if STATE_ATTR_NEXT_DUSK does not exist
return None
def next_midnight(hass, entity_id=None):
"""Local datetime object of the next midnight.
Async friendly.
"""
utc_next = next_midnight_utc(hass, entity_id)
return dt_util.as_local(utc_next) if utc_next else None
def next_midnight_utc(hass, entity_id=None):
"""UTC datetime object of the next midnight.
Async friendly.
"""
entity_id = entity_id or ENTITY_ID
state = hass.states.get(ENTITY_ID)
try:
return dt_util.parse_datetime(
state.attributes[STATE_ATTR_NEXT_MIDNIGHT])
except (AttributeError, KeyError):
# AttributeError if state is None
# KeyError if STATE_ATTR_NEXT_MIDNIGHT does not exist
return None
def next_noon(hass, entity_id=None):
"""Local datetime object of the next solar noon.
Async friendly.
"""
utc_next = next_noon_utc(hass, entity_id)
return dt_util.as_local(utc_next) if utc_next else None
def next_noon_utc(hass, entity_id=None):
"""UTC datetime object of the next noon.
Async friendly.
"""
entity_id = entity_id or ENTITY_ID
state = hass.states.get(ENTITY_ID)
try:
return dt_util.parse_datetime(
state.attributes[STATE_ATTR_NEXT_NOON])
except (AttributeError, KeyError):
# AttributeError if state is None
# KeyError if STATE_ATTR_NEXT_NOON does not exist
return None
def next_setting(hass, entity_id=None):
"""Local datetime object of the next sun setting.
Async friendly.
"""
utc_next = next_setting_utc(hass, entity_id)
return dt_util.as_local(utc_next) if utc_next else None
def next_setting_utc(hass, entity_id=None):
"""UTC datetime object of the next sun setting.
Async friendly.
"""
entity_id = entity_id or ENTITY_ID
state = hass.states.get(ENTITY_ID)
try:
return dt_util.parse_datetime(
state.attributes[STATE_ATTR_NEXT_SETTING])
except (AttributeError, KeyError):
# AttributeError if state is None
# KeyError if STATE_ATTR_NEXT_SETTING does not exist
return None
def next_rising(hass, entity_id=None):
"""Local datetime object of the next sun rising.
Async friendly.
"""
utc_next = next_rising_utc(hass, entity_id)
return dt_util.as_local(utc_next) if utc_next else None
def next_rising_utc(hass, entity_id=None):
"""UTC datetime object of the next sun rising.
Async friendly.
"""
entity_id = entity_id or ENTITY_ID
state = hass.states.get(ENTITY_ID)
try:
return dt_util.parse_datetime(state.attributes[STATE_ATTR_NEXT_RISING])
except (AttributeError, KeyError):
# AttributeError if state is None
# KeyError if STATE_ATTR_NEXT_RISING does not exist
return None
def setup(hass, config):
@asyncio.coroutine
def async_setup(hass, config):
"""Track the state of the sun."""
if None in (hass.config.latitude, hass.config.longitude):
_LOGGER.error("Latitude or longitude not set in Home Assistant config")
return False
if config.get(CONF_ELEVATION) is not None:
_LOGGER.warning(
"Elevation is now configured in home assistant core. "
"See https://home-assistant.io/docs/configuration/basic/")
latitude = util.convert(hass.config.latitude, float)
longitude = util.convert(hass.config.longitude, float)
errors = []
if latitude is None:
errors.append('Latitude needs to be a decimal value')
elif -90 > latitude < 90:
errors.append('Latitude needs to be -90 .. 90')
if longitude is None:
errors.append('Longitude needs to be a decimal value')
elif -180 > longitude < 180:
errors.append('Longitude needs to be -180 .. 180')
if errors:
_LOGGER.error('Invalid configuration received: %s', ", ".join(errors))
return False
platform_config = config.get(DOMAIN, {})
elevation = platform_config.get(CONF_ELEVATION)
if elevation is None:
elevation = hass.config.elevation or 0
from astral import Location
location = Location(('', '', latitude, longitude,
hass.config.time_zone.zone, elevation))
sun = Sun(hass, location)
sun = Sun(hass, get_astral_location(hass))
sun.point_in_time_listener(dt_util.utcnow())
return True
@@ -273,7 +64,7 @@ class Sun(Entity):
self.next_midnight = self.next_noon = None
self.solar_elevation = self.solar_azimuth = 0
track_utc_time_change(hass, self.timer_update, second=30)
async_track_utc_time_change(hass, self.timer_update, second=30)
@property
def name(self):
@@ -308,64 +99,41 @@ class Sun(Entity):
return min(self.next_dawn, self.next_dusk, self.next_midnight,
self.next_noon, self.next_rising, self.next_setting)
@staticmethod
def get_next_solar_event(callable_on_astral_location,
utc_point_in_time, mod, increment):
"""Calculate sun state at a point in UTC time."""
import astral
while True:
try:
next_dt = callable_on_astral_location(
utc_point_in_time + timedelta(days=mod), local=False)
if next_dt > utc_point_in_time:
break
except astral.AstralError:
pass
mod += increment
return next_dt
@callback
def update_as_of(self, utc_point_in_time):
"""Update the attributes containing solar events."""
self.next_dawn = Sun.get_next_solar_event(
self.location.dawn, utc_point_in_time, -1, 1)
self.next_dusk = Sun.get_next_solar_event(
self.location.dusk, utc_point_in_time, -1, 1)
self.next_midnight = Sun.get_next_solar_event(
self.location.solar_midnight, utc_point_in_time, -1, 1)
self.next_noon = Sun.get_next_solar_event(
self.location.solar_noon, utc_point_in_time, -1, 1)
self.next_rising = Sun.get_next_solar_event(
self.location.sunrise, utc_point_in_time, -1, 1)
self.next_setting = Sun.get_next_solar_event(
self.location.sunset, utc_point_in_time, -1, 1)
self.next_dawn = get_astral_event_next(
self.hass, 'dawn', utc_point_in_time)
self.next_dusk = get_astral_event_next(
self.hass, 'dusk', utc_point_in_time)
self.next_midnight = get_astral_event_next(
self.hass, 'solar_midnight', utc_point_in_time)
self.next_noon = get_astral_event_next(
self.hass, 'solar_noon', utc_point_in_time)
self.next_rising = get_astral_event_next(
self.hass, 'sunrise', utc_point_in_time)
self.next_setting = get_astral_event_next(
self.hass, 'sunset', utc_point_in_time)
@callback
def update_sun_position(self, utc_point_in_time):
"""Calculate the position of the sun."""
from astral import Astral
self.solar_azimuth = Astral().solar_azimuth(
utc_point_in_time,
self.location.latitude,
self.location.longitude)
self.solar_elevation = Astral().solar_elevation(
utc_point_in_time,
self.location.latitude,
self.location.longitude)
self.solar_azimuth = self.location.solar_azimuth(utc_point_in_time)
self.solar_elevation = self.location.solar_elevation(utc_point_in_time)
@callback
def point_in_time_listener(self, now):
"""Run when the state of the sun has changed."""
self.update_as_of(now)
self.schedule_update_ha_state()
self.hass.async_add_job(self.async_update_ha_state())
# Schedule next update at next_change+1 second so sun state has changed
track_point_in_utc_time(
async_track_point_in_utc_time(
self.hass, self.point_in_time_listener,
self.next_change + timedelta(seconds=1))
@callback
def timer_update(self, time):
"""Needed to update solar elevation and azimuth."""
self.update_sun_position(time)
self.schedule_update_ha_state()
self.hass.async_add_job(self.async_update_ha_state())
+5 -7
View File
@@ -11,18 +11,18 @@ import logging
import voluptuous as vol
from homeassistant.components.light import is_on, turn_on
from homeassistant.components.sun import next_setting, next_rising
from homeassistant.components.switch import DOMAIN, SwitchDevice
from homeassistant.const import CONF_NAME, CONF_PLATFORM
from homeassistant.helpers.event import track_time_change
from homeassistant.helpers.sun import get_astral_event_date
from homeassistant.util.color import (
color_temperature_to_rgb, color_RGB_to_xy,
color_temperature_kelvin_to_mired)
from homeassistant.util.dt import now as dt_now
import homeassistant.helpers.config_validation as cv
DEPENDENCIES = ['sun', 'light']
SUN = "sun.sun"
DEPENDENCIES = ['light']
_LOGGER = logging.getLogger(__name__)
CONF_LIGHTS = 'lights'
@@ -159,8 +159,7 @@ class FluxSwitch(SwitchDevice):
"""Update all the lights using flux."""
if now is None:
now = dt_now()
sunset = next_setting(self.hass, SUN).replace(
day=now.day, month=now.month, year=now.year)
sunset = get_astral_event_date(self.hass, 'sunset', now.date())
start_time = self.find_start_time(now)
stop_time = now.replace(
hour=self._stop_time.hour, minute=self._stop_time.minute,
@@ -221,6 +220,5 @@ class FluxSwitch(SwitchDevice):
hour=self._start_time.hour, minute=self._start_time.minute,
second=0)
else:
sunrise = next_rising(self.hass, SUN).replace(
day=now.day, month=now.month, year=now.year)
sunrise = get_astral_event_date(self.hass, 'sunrise', now.date())
return sunrise