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

+21 -11
View File
@@ -7,8 +7,7 @@ import sys
from homeassistant.helpers.typing import ConfigType
from homeassistant.core import HomeAssistant
from homeassistant.components import (
zone as zone_cmp, sun as sun_cmp)
from homeassistant.components import zone as zone_cmp
from homeassistant.const import (
ATTR_GPS_ACCURACY, ATTR_LATITUDE, ATTR_LONGITUDE,
CONF_ENTITY_ID, CONF_VALUE_TEMPLATE, CONF_CONDITION,
@@ -17,6 +16,7 @@ from homeassistant.const import (
CONF_BELOW, CONF_ABOVE)
from homeassistant.exceptions import TemplateError, HomeAssistantError
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.sun import get_astral_event_date
import homeassistant.util.dt as dt_util
from homeassistant.util.async import run_callback_threadsafe
@@ -234,24 +234,34 @@ def state_from_config(config, config_validation=True):
def sun(hass, before=None, after=None, before_offset=None, after_offset=None):
"""Test if current time matches sun requirements."""
now = dt_util.now().time()
utcnow = dt_util.utcnow()
today = dt_util.as_local(utcnow).date()
before_offset = before_offset or timedelta(0)
after_offset = after_offset or timedelta(0)
if before == SUN_EVENT_SUNRISE and now > (sun_cmp.next_rising(hass) +
before_offset).time():
sunrise = get_astral_event_date(hass, 'sunrise', today)
sunset = get_astral_event_date(hass, 'sunset', today)
if sunrise is None and (before == SUN_EVENT_SUNRISE or
after == SUN_EVENT_SUNRISE):
# There is no sunrise today
return False
elif before == SUN_EVENT_SUNSET and now > (sun_cmp.next_setting(hass) +
before_offset).time():
if sunset is None and (before == SUN_EVENT_SUNSET or
after == SUN_EVENT_SUNSET):
# There is no sunset today
return False
if after == SUN_EVENT_SUNRISE and now < (sun_cmp.next_rising(hass) +
after_offset).time():
if before == SUN_EVENT_SUNRISE and utcnow > sunrise + before_offset:
return False
elif after == SUN_EVENT_SUNSET and now < (sun_cmp.next_setting(hass) +
after_offset).time():
elif before == SUN_EVENT_SUNSET and utcnow > sunset + before_offset:
return False
if after == SUN_EVENT_SUNRISE and utcnow < sunrise + after_offset:
return False
elif after == SUN_EVENT_SUNSET and utcnow < sunset + after_offset:
return False
return True
+9 -27
View File
@@ -1,7 +1,7 @@
"""Helpers for listening to events."""
import functools as ft
from datetime import timedelta
from homeassistant.helpers.sun import get_astral_event_next
from ..core import HomeAssistant, callback
from ..const import (
ATTR_NOW, EVENT_STATE_CHANGED, EVENT_TIME_CHANGED, MATCH_ALL)
@@ -197,29 +197,20 @@ track_time_interval = threaded_listener_factory(async_track_time_interval)
@callback
def async_track_sunrise(hass, action, offset=None):
"""Add a listener that will fire a specified offset from sunrise daily."""
from homeassistant.components import sun
offset = offset or timedelta()
remove = None
def next_rise():
"""Return the next sunrise."""
next_time = sun.next_rising_utc(hass) + offset
while next_time < dt_util.utcnow():
next_time = next_time + timedelta(days=1)
return next_time
@callback
def sunrise_automation_listener(now):
"""Handle points in time to execute actions."""
nonlocal remove
remove = async_track_point_in_utc_time(
hass, sunrise_automation_listener, next_rise())
hass, sunrise_automation_listener, get_astral_event_next(
hass, 'sunrise', offset=offset))
hass.async_run_job(action)
remove = async_track_point_in_utc_time(
hass, sunrise_automation_listener, next_rise())
hass, sunrise_automation_listener, get_astral_event_next(
hass, 'sunrise', offset=offset))
def remove_listener():
"""Remove sunset listener."""
@@ -234,29 +225,20 @@ track_sunrise = threaded_listener_factory(async_track_sunrise)
@callback
def async_track_sunset(hass, action, offset=None):
"""Add a listener that will fire a specified offset from sunset daily."""
from homeassistant.components import sun
offset = offset or timedelta()
remove = None
def next_set():
"""Return next sunrise."""
next_time = sun.next_setting_utc(hass) + offset
while next_time < dt_util.utcnow():
next_time = next_time + timedelta(days=1)
return next_time
@callback
def sunset_automation_listener(now):
"""Handle points in time to execute actions."""
nonlocal remove
remove = async_track_point_in_utc_time(
hass, sunset_automation_listener, next_set())
hass, sunset_automation_listener, get_astral_event_next(
hass, 'sunset', offset=offset))
hass.async_run_job(action)
remove = async_track_point_in_utc_time(
hass, sunset_automation_listener, next_set())
hass, sunset_automation_listener, get_astral_event_next(
hass, 'sunset', offset=offset))
def remove_listener():
"""Remove sunset listener."""
+87
View File
@@ -0,0 +1,87 @@
"""Helpers for sun events."""
import datetime
from homeassistant.core import callback
from homeassistant.util import dt as dt_util
DATA_LOCATION_CACHE = 'astral_location_cache'
@callback
def get_astral_location(hass):
"""Get an astral location for the current hass configuration."""
from astral import Location
latitude = hass.config.latitude
longitude = hass.config.longitude
timezone = hass.config.time_zone.zone
elevation = hass.config.elevation
info = ('', '', latitude, longitude, timezone, elevation)
# Cache astral locations so they aren't recreated with the same args
if DATA_LOCATION_CACHE not in hass.data:
hass.data[DATA_LOCATION_CACHE] = {}
if info not in hass.data[DATA_LOCATION_CACHE]:
hass.data[DATA_LOCATION_CACHE][info] = Location(info)
return hass.data[DATA_LOCATION_CACHE][info]
@callback
def get_astral_event_next(hass, event, utc_point_in_time=None, offset=None):
"""Calculate the next specified solar event."""
import astral
location = get_astral_location(hass)
if offset is None:
offset = datetime.timedelta()
if utc_point_in_time is None:
utc_point_in_time = dt_util.utcnow()
mod = -1
while True:
try:
next_dt = getattr(location, event)(
dt_util.as_local(utc_point_in_time).date() +
datetime.timedelta(days=mod),
local=False) + offset
if next_dt > utc_point_in_time:
return next_dt
except astral.AstralError:
pass
mod += 1
@callback
def get_astral_event_date(hass, event, date=None):
"""Calculate the astral event time for the specified date."""
import astral
location = get_astral_location(hass)
if date is None:
date = dt_util.now().date()
if isinstance(date, datetime.datetime):
date = dt_util.as_local(date).date()
try:
return getattr(location, event)(date, local=False)
except astral.AstralError:
# Event never occurs for specified date.
return None
@callback
def is_up(hass, utc_point_in_time=None):
"""Calculate if the sun is currently up."""
if utc_point_in_time is None:
utc_point_in_time = dt_util.utcnow()
next_sunrise = get_astral_event_next(hass, 'sunrise', utc_point_in_time)
next_sunset = get_astral_event_next(hass, 'sunset', utc_point_in_time)
return next_sunrise > next_sunset