2013-12-11 08:07:30 +00:00
|
|
|
"""
|
|
|
|
homeassistant.components.sun
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
Provides functionality to keep track of the sun.
|
2015-02-03 19:18:19 +00:00
|
|
|
|
|
|
|
|
|
|
|
Event listener
|
|
|
|
--------------
|
|
|
|
The suns event listener will call the service
|
|
|
|
when the sun rises or sets with an offset.
|
|
|
|
The sun evnt need to have the type 'sun', which service to call,
|
|
|
|
which event (sunset or sunrise) and the offset.
|
|
|
|
|
|
|
|
{
|
|
|
|
"type": "sun",
|
|
|
|
"service": "switch.turn_on",
|
|
|
|
"event": "sunset",
|
|
|
|
"offset": "-01:00:00"
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2013-12-11 08:07:30 +00:00
|
|
|
"""
|
|
|
|
import logging
|
2014-11-26 06:31:36 +00:00
|
|
|
from datetime import datetime, timedelta
|
2013-12-11 08:07:30 +00:00
|
|
|
|
2014-08-13 12:28:45 +00:00
|
|
|
import homeassistant as ha
|
2014-12-07 07:57:02 +00:00
|
|
|
from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE
|
|
|
|
from homeassistant.helpers import validate_config
|
|
|
|
from homeassistant.util import str_to_datetime, datetime_to_str
|
2013-12-11 08:07:30 +00:00
|
|
|
|
2015-01-28 19:01:16 +00:00
|
|
|
from homeassistant.components.scheduler import ServiceEventListener
|
|
|
|
|
2014-08-13 12:28:45 +00:00
|
|
|
DEPENDENCIES = []
|
|
|
|
DOMAIN = "sun"
|
2014-01-24 06:03:13 +00:00
|
|
|
ENTITY_ID = "sun.sun"
|
2013-12-11 08:07:30 +00:00
|
|
|
|
|
|
|
STATE_ABOVE_HORIZON = "above_horizon"
|
|
|
|
STATE_BELOW_HORIZON = "below_horizon"
|
|
|
|
|
|
|
|
STATE_ATTR_NEXT_RISING = "next_rising"
|
|
|
|
STATE_ATTR_NEXT_SETTING = "next_setting"
|
|
|
|
|
2015-01-28 19:01:16 +00:00
|
|
|
_LOGGER = logging.getLogger(__name__)
|
2013-12-11 08:07:30 +00:00
|
|
|
|
2015-02-02 06:39:11 +00:00
|
|
|
|
2014-04-24 07:40:45 +00:00
|
|
|
def is_on(hass, entity_id=None):
|
2013-12-11 08:07:30 +00:00
|
|
|
""" Returns if the sun is currently up based on the statemachine. """
|
2014-01-24 06:03:13 +00:00
|
|
|
entity_id = entity_id or ENTITY_ID
|
|
|
|
|
2014-04-24 07:40:45 +00:00
|
|
|
return hass.states.is_state(entity_id, STATE_ABOVE_HORIZON)
|
2013-12-11 08:07:30 +00:00
|
|
|
|
|
|
|
|
2014-11-25 07:15:14 +00:00
|
|
|
def next_setting(hass, entity_id=None):
|
2013-12-11 08:07:30 +00:00
|
|
|
""" Returns the datetime object representing the next sun setting. """
|
2014-11-25 07:15:14 +00:00
|
|
|
entity_id = entity_id or ENTITY_ID
|
|
|
|
|
2014-04-24 07:40:45 +00:00
|
|
|
state = hass.states.get(ENTITY_ID)
|
2013-12-11 08:07:30 +00:00
|
|
|
|
2014-02-03 05:20:37 +00:00
|
|
|
try:
|
2014-12-07 07:57:02 +00:00
|
|
|
return str_to_datetime(state.attributes[STATE_ATTR_NEXT_SETTING])
|
2014-02-03 05:20:37 +00:00
|
|
|
except (AttributeError, KeyError):
|
|
|
|
# AttributeError if state is None
|
|
|
|
# KeyError if STATE_ATTR_NEXT_SETTING does not exist
|
|
|
|
return None
|
2013-12-11 08:07:30 +00:00
|
|
|
|
|
|
|
|
2014-11-25 07:15:14 +00:00
|
|
|
def next_rising(hass, entity_id=None):
|
2014-02-03 05:20:37 +00:00
|
|
|
""" Returns the datetime object representing the next sun rising. """
|
2014-11-25 07:15:14 +00:00
|
|
|
entity_id = entity_id or ENTITY_ID
|
|
|
|
|
2014-04-24 07:40:45 +00:00
|
|
|
state = hass.states.get(ENTITY_ID)
|
2013-12-11 08:07:30 +00:00
|
|
|
|
2014-02-03 05:20:37 +00:00
|
|
|
try:
|
2014-12-07 07:57:02 +00:00
|
|
|
return str_to_datetime(state.attributes[STATE_ATTR_NEXT_RISING])
|
2014-02-03 05:20:37 +00:00
|
|
|
except (AttributeError, KeyError):
|
|
|
|
# AttributeError if state is None
|
|
|
|
# KeyError if STATE_ATTR_NEXT_RISING does not exist
|
|
|
|
return None
|
2013-12-11 08:07:30 +00:00
|
|
|
|
|
|
|
|
2014-08-13 12:28:45 +00:00
|
|
|
def setup(hass, config):
|
2013-12-11 08:07:30 +00:00
|
|
|
""" Tracks the state of the sun. """
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2014-12-07 07:57:02 +00:00
|
|
|
if not validate_config(config,
|
|
|
|
{ha.DOMAIN: [CONF_LATITUDE, CONF_LONGITUDE]},
|
|
|
|
logger):
|
2014-08-13 12:28:45 +00:00
|
|
|
return False
|
|
|
|
|
2013-12-11 08:07:30 +00:00
|
|
|
try:
|
|
|
|
import ephem
|
|
|
|
except ImportError:
|
2014-09-25 02:58:39 +00:00
|
|
|
logger.exception("Error while importing dependency ephem.")
|
2013-12-11 08:07:30 +00:00
|
|
|
return False
|
|
|
|
|
|
|
|
sun = ephem.Sun() # pylint: disable=no-member
|
|
|
|
|
2015-03-01 03:14:32 +00:00
|
|
|
latitude = str(config[ha.DOMAIN][CONF_LATITUDE])
|
|
|
|
longitude = str(config[ha.DOMAIN][CONF_LONGITUDE])
|
2014-08-13 12:28:45 +00:00
|
|
|
|
2014-11-25 07:15:14 +00:00
|
|
|
# Validate latitude and longitude
|
|
|
|
observer = ephem.Observer()
|
|
|
|
|
|
|
|
errors = []
|
|
|
|
|
|
|
|
try:
|
|
|
|
observer.lat = latitude # pylint: disable=assigning-non-slot
|
|
|
|
except ValueError:
|
|
|
|
errors.append("invalid value for latitude given: {}".format(latitude))
|
|
|
|
|
|
|
|
try:
|
|
|
|
observer.long = longitude # pylint: disable=assigning-non-slot
|
|
|
|
except ValueError:
|
|
|
|
errors.append("invalid value for latitude given: {}".format(latitude))
|
|
|
|
|
|
|
|
if errors:
|
|
|
|
logger.error("Error setting up: %s", ", ".join(errors))
|
|
|
|
return False
|
|
|
|
|
2014-11-26 06:31:36 +00:00
|
|
|
def update_sun_state(now):
|
2013-12-11 08:07:30 +00:00
|
|
|
""" Method to update the current state of the sun and
|
|
|
|
set time of next setting and rising. """
|
2014-11-26 06:31:36 +00:00
|
|
|
utc_offset = datetime.utcnow() - datetime.now()
|
|
|
|
utc_now = now + utc_offset
|
|
|
|
|
2013-12-11 08:07:30 +00:00
|
|
|
observer = ephem.Observer()
|
2014-08-13 12:28:45 +00:00
|
|
|
observer.lat = latitude # pylint: disable=assigning-non-slot
|
|
|
|
observer.long = longitude # pylint: disable=assigning-non-slot
|
2013-12-11 08:07:30 +00:00
|
|
|
|
2014-11-26 06:31:36 +00:00
|
|
|
next_rising_dt = ephem.localtime(
|
|
|
|
observer.next_rising(sun, start=utc_now))
|
|
|
|
next_setting_dt = ephem.localtime(
|
|
|
|
observer.next_setting(sun, start=utc_now))
|
2013-12-11 08:07:30 +00:00
|
|
|
|
|
|
|
if next_rising_dt > next_setting_dt:
|
|
|
|
new_state = STATE_ABOVE_HORIZON
|
|
|
|
next_change = next_setting_dt
|
|
|
|
|
|
|
|
else:
|
|
|
|
new_state = STATE_BELOW_HORIZON
|
|
|
|
next_change = next_rising_dt
|
|
|
|
|
2014-11-08 21:57:08 +00:00
|
|
|
logger.info("%s. Next change: %s",
|
|
|
|
new_state, next_change.strftime("%H:%M"))
|
2013-12-11 08:07:30 +00:00
|
|
|
|
|
|
|
state_attributes = {
|
2014-12-07 07:57:02 +00:00
|
|
|
STATE_ATTR_NEXT_RISING: datetime_to_str(next_rising_dt),
|
|
|
|
STATE_ATTR_NEXT_SETTING: datetime_to_str(next_setting_dt)
|
2013-12-11 08:07:30 +00:00
|
|
|
}
|
|
|
|
|
2014-04-24 07:40:45 +00:00
|
|
|
hass.states.set(ENTITY_ID, new_state, state_attributes)
|
2013-12-11 08:07:30 +00:00
|
|
|
|
2014-11-26 06:31:36 +00:00
|
|
|
# +1 second so Ephem will report it has set
|
2014-04-24 07:40:45 +00:00
|
|
|
hass.track_point_in_time(update_sun_state,
|
2014-11-26 06:31:36 +00:00
|
|
|
next_change + timedelta(seconds=1))
|
2013-12-11 08:07:30 +00:00
|
|
|
|
2014-11-26 06:31:36 +00:00
|
|
|
update_sun_state(datetime.now())
|
2013-12-11 08:07:30 +00:00
|
|
|
|
|
|
|
return True
|
2015-01-28 19:01:16 +00:00
|
|
|
|
2015-02-02 06:39:11 +00:00
|
|
|
|
2015-01-28 19:01:16 +00:00
|
|
|
def create_event_listener(schedule, event_listener_data):
|
|
|
|
""" Create a sun event listener based on the description. """
|
|
|
|
|
|
|
|
negative_offset = False
|
|
|
|
service = event_listener_data['service']
|
|
|
|
offset_str = event_listener_data['offset']
|
|
|
|
event = event_listener_data['event']
|
|
|
|
|
|
|
|
if offset_str.startswith('-'):
|
|
|
|
negative_offset = True
|
|
|
|
offset_str = offset_str[1:]
|
|
|
|
|
|
|
|
(hour, minute, second) = [int(x) for x in offset_str.split(':')]
|
|
|
|
|
|
|
|
offset = timedelta(hours=hour, minutes=minute, seconds=second)
|
|
|
|
|
|
|
|
if event == 'sunset':
|
|
|
|
return SunsetEventListener(schedule, service, offset, negative_offset)
|
|
|
|
|
|
|
|
return SunriseEventListener(schedule, service, offset, negative_offset)
|
|
|
|
|
2015-02-02 06:39:11 +00:00
|
|
|
|
2015-01-28 19:01:16 +00:00
|
|
|
# pylint: disable=too-few-public-methods
|
|
|
|
class SunEventListener(ServiceEventListener):
|
|
|
|
""" This is the base class for sun event listeners. """
|
|
|
|
|
|
|
|
def __init__(self, schedule, service, offset, negative_offset):
|
|
|
|
ServiceEventListener.__init__(self, schedule, service)
|
|
|
|
|
|
|
|
self.offset = offset
|
|
|
|
self.negative_offset = negative_offset
|
|
|
|
|
|
|
|
def __get_next_time(self, next_event):
|
|
|
|
"""
|
|
|
|
Returns when the next time the service should be called.
|
|
|
|
Taking into account the offset and which days the event should execute.
|
|
|
|
"""
|
|
|
|
|
|
|
|
if self.negative_offset:
|
|
|
|
next_time = next_event - self.offset
|
|
|
|
else:
|
|
|
|
next_time = next_event + self.offset
|
|
|
|
|
|
|
|
while next_time < datetime.now() or \
|
|
|
|
next_time.weekday() not in self.my_schedule.days:
|
|
|
|
next_time = next_time + timedelta(days=1)
|
|
|
|
|
|
|
|
return next_time
|
|
|
|
|
|
|
|
def schedule_next_event(self, hass, next_event):
|
|
|
|
""" Schedule the event """
|
|
|
|
next_time = self.__get_next_time(next_event)
|
|
|
|
|
|
|
|
# pylint: disable=unused-argument
|
|
|
|
def execute(now):
|
|
|
|
""" Call the execute method """
|
|
|
|
self.execute(hass)
|
|
|
|
|
|
|
|
hass.track_point_in_time(execute, next_time)
|
|
|
|
|
|
|
|
return next_time
|
|
|
|
|
|
|
|
|
|
|
|
# pylint: disable=too-few-public-methods
|
|
|
|
class SunsetEventListener(SunEventListener):
|
|
|
|
""" This class is used the call a service when the sun sets. """
|
|
|
|
def schedule(self, hass):
|
|
|
|
""" Schedule the event """
|
|
|
|
next_setting_dt = next_setting(hass)
|
|
|
|
|
|
|
|
next_time_dt = self.schedule_next_event(hass, next_setting_dt)
|
|
|
|
|
|
|
|
_LOGGER.info(
|
|
|
|
'SunsetEventListener scheduled for %s, will call service %s.%s',
|
|
|
|
next_time_dt, self.domain, self.service)
|
|
|
|
|
|
|
|
|
|
|
|
# pylint: disable=too-few-public-methods
|
|
|
|
class SunriseEventListener(SunEventListener):
|
|
|
|
""" This class is used the call a service when the sun rises. """
|
|
|
|
|
|
|
|
def schedule(self, hass):
|
|
|
|
""" Schedule the event """
|
|
|
|
next_rising_dt = next_rising(hass)
|
|
|
|
|
|
|
|
next_time_dt = self.schedule_next_event(hass, next_rising_dt)
|
|
|
|
|
|
|
|
_LOGGER.info(
|
|
|
|
'SunriseEventListener scheduled for %s, will call service %s.%s',
|
|
|
|
next_time_dt, self.domain, self.service)
|