2013-09-25 01:39:58 +00:00
|
|
|
"""
|
|
|
|
homeassistant
|
|
|
|
~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
Module to control the lights based on devices at home and the state of the sun.
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
import time
|
2013-09-30 07:20:27 +00:00
|
|
|
import logging
|
|
|
|
import threading
|
|
|
|
from collections import defaultdict, namedtuple
|
|
|
|
from datetime import datetime
|
|
|
|
|
2013-10-09 01:50:30 +00:00
|
|
|
logging.basicConfig(level=logging.INFO)
|
|
|
|
|
2013-09-30 07:20:27 +00:00
|
|
|
ALL_EVENTS = '*'
|
|
|
|
EVENT_START = "start"
|
|
|
|
EVENT_STATE_CHANGED = "state_changed"
|
|
|
|
EVENT_TIME_CHANGED = "time_changed"
|
|
|
|
|
|
|
|
TIMER_INTERVAL = 10 # seconds
|
|
|
|
|
|
|
|
# We want to be able to fire every time a minute starts (seconds=0).
|
|
|
|
# We want this so other modules can use that to make sure they fire
|
|
|
|
# every minute.
|
|
|
|
assert 60 % TIMER_INTERVAL == 0, "60 % TIMER_INTERVAL should be 0!"
|
|
|
|
|
2013-10-24 06:57:08 +00:00
|
|
|
State = namedtuple("State", ['state', 'last_changed', 'attributes'])
|
2013-09-30 07:20:27 +00:00
|
|
|
|
|
|
|
def start_home_assistant(eventbus):
|
|
|
|
""" Start home assistant. """
|
|
|
|
Timer(eventbus)
|
|
|
|
|
2013-10-09 01:50:30 +00:00
|
|
|
eventbus.fire(EVENT_START)
|
2013-09-30 07:20:27 +00:00
|
|
|
|
|
|
|
while True:
|
|
|
|
try:
|
|
|
|
time.sleep(1)
|
|
|
|
|
|
|
|
except KeyboardInterrupt:
|
|
|
|
break
|
|
|
|
|
|
|
|
def ensure_list(parameter):
|
|
|
|
""" Wraps parameter in a list if it is not one and returns it. """
|
|
|
|
return parameter if isinstance(parameter, list) else [parameter]
|
|
|
|
|
|
|
|
def matcher(subject, pattern):
|
|
|
|
""" Returns True if subject matches the pattern.
|
2013-10-08 06:55:19 +00:00
|
|
|
|
|
|
|
Pattern is either a list of allowed subjects or a '*'.
|
|
|
|
"""
|
2013-09-30 07:20:27 +00:00
|
|
|
return '*' in pattern or subject in pattern
|
2013-09-25 01:39:58 +00:00
|
|
|
|
2013-09-30 07:20:27 +00:00
|
|
|
def track_state_change(eventbus, category, from_state, to_state, action):
|
|
|
|
""" Helper method to track specific state changes. """
|
|
|
|
from_state = ensure_list(from_state)
|
|
|
|
to_state = ensure_list(to_state)
|
2013-09-25 01:39:58 +00:00
|
|
|
|
2013-09-30 07:20:27 +00:00
|
|
|
def listener(event):
|
|
|
|
""" State change listener that listens for specific state changes. """
|
|
|
|
if category == event.data['category'] and \
|
|
|
|
matcher(event.data['old_state'].state, from_state) and \
|
|
|
|
matcher(event.data['new_state'].state, to_state):
|
2013-09-25 01:39:58 +00:00
|
|
|
|
2013-10-08 06:55:19 +00:00
|
|
|
action(event.data['category'],
|
|
|
|
event.data['old_state'],
|
|
|
|
event.data['new_state'])
|
2013-09-25 01:39:58 +00:00
|
|
|
|
2013-09-30 07:20:27 +00:00
|
|
|
eventbus.listen(EVENT_STATE_CHANGED, listener)
|
2013-09-25 01:39:58 +00:00
|
|
|
|
2013-10-08 06:55:19 +00:00
|
|
|
# pylint: disable=too-many-arguments
|
|
|
|
def track_time_change(eventbus, action,
|
|
|
|
year='*', month='*', day='*',
|
|
|
|
hour='*', minute='*', second='*',
|
|
|
|
point_in_time=None, listen_once=False):
|
2013-09-30 07:20:27 +00:00
|
|
|
""" Adds a listener that will listen for a specified or matching time. """
|
|
|
|
year, month, day = ensure_list(year), ensure_list(month), ensure_list(day)
|
2013-10-08 06:55:19 +00:00
|
|
|
hour, minute = ensure_list(hour), ensure_list(minute)
|
|
|
|
second = ensure_list(second)
|
2013-09-30 07:20:27 +00:00
|
|
|
|
|
|
|
def listener(event):
|
|
|
|
""" Listens for matching time_changed events. """
|
2013-10-08 06:55:19 +00:00
|
|
|
if (point_in_time and event.data['now'] > point_in_time) or \
|
|
|
|
(not point_in_time and \
|
2013-09-30 07:20:27 +00:00
|
|
|
matcher(event.data['now'].year, year) and \
|
|
|
|
matcher(event.data['now'].month, month) and \
|
|
|
|
matcher(event.data['now'].day, day) and \
|
|
|
|
matcher(event.data['now'].hour, hour) and \
|
|
|
|
matcher(event.data['now'].minute, minute) and \
|
|
|
|
matcher(event.data['now'].second, second)):
|
|
|
|
|
2013-10-08 06:55:19 +00:00
|
|
|
# point_in_time are exact points in time
|
|
|
|
# so we always remove it after fire
|
2013-10-09 01:50:30 +00:00
|
|
|
if listen_once or point_in_time:
|
|
|
|
event.eventbus.remove_listener(EVENT_TIME_CHANGED, listener)
|
2013-09-30 07:20:27 +00:00
|
|
|
|
|
|
|
action(event.data['now'])
|
|
|
|
|
|
|
|
eventbus.listen(EVENT_TIME_CHANGED, listener)
|
|
|
|
|
2013-10-09 01:50:30 +00:00
|
|
|
Event = namedtuple("Event", ["eventbus", "event_type", "data"])
|
|
|
|
|
2013-09-30 07:20:27 +00:00
|
|
|
class EventBus(object):
|
2013-10-08 06:55:19 +00:00
|
|
|
""" Class that allows code to listen for- and fire events. """
|
2013-09-30 07:20:27 +00:00
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
self.listeners = defaultdict(list)
|
2013-09-25 01:39:58 +00:00
|
|
|
self.logger = logging.getLogger(__name__)
|
|
|
|
|
2013-10-09 01:50:30 +00:00
|
|
|
def fire(self, event_type, event_data=None):
|
2013-09-30 07:20:27 +00:00
|
|
|
""" Fire an event. """
|
|
|
|
|
2013-10-09 01:50:30 +00:00
|
|
|
if not event_data:
|
|
|
|
event_data = {}
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2013-10-09 01:50:30 +00:00
|
|
|
self.logger.info("EventBus:Event {}: {}".format(
|
|
|
|
event_type, event_data))
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2013-10-09 01:50:30 +00:00
|
|
|
def run():
|
|
|
|
""" Fire listeners for event. """
|
|
|
|
event = Event(self, event_type, event_data)
|
|
|
|
|
2013-10-23 23:29:33 +00:00
|
|
|
# We do not use itertools.chain() because some listeners might
|
|
|
|
# choose to remove themselves as a listener while being executed
|
|
|
|
for listener in self.listeners[ALL_EVENTS] + \
|
|
|
|
self.listeners[event.event_type]:
|
2013-10-07 06:06:59 +00:00
|
|
|
try:
|
2013-10-09 01:50:30 +00:00
|
|
|
listener(event)
|
2013-10-07 06:06:59 +00:00
|
|
|
|
2013-10-08 06:55:19 +00:00
|
|
|
except Exception: #pylint: disable=broad-except
|
2013-10-07 06:06:59 +00:00
|
|
|
self.logger.exception("EventBus:Exception in listener")
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2013-10-09 01:50:30 +00:00
|
|
|
# We dont want the eventbus to be blocking - run in a thread.
|
2013-09-30 07:20:27 +00:00
|
|
|
threading.Thread(target=run).start()
|
2013-09-25 01:39:58 +00:00
|
|
|
|
2013-10-09 01:50:30 +00:00
|
|
|
def listen(self, event_type, listener):
|
2013-09-30 07:20:27 +00:00
|
|
|
""" Listen for all events or events of a specific type.
|
2013-09-25 01:39:58 +00:00
|
|
|
|
2013-10-08 06:55:19 +00:00
|
|
|
To listen to all events specify the constant ``ALL_EVENTS``
|
|
|
|
as event_type.
|
|
|
|
"""
|
2013-10-09 01:50:30 +00:00
|
|
|
self.listeners[event_type].append(listener)
|
2013-09-25 01:39:58 +00:00
|
|
|
|
2013-10-23 23:29:33 +00:00
|
|
|
def listen_once(self, event_type, listener):
|
|
|
|
""" Listen once for event of a specific type.
|
|
|
|
|
|
|
|
To listen to all events specify the constant ``ALL_EVENTS``
|
|
|
|
as event_type.
|
2013-10-25 10:05:34 +00:00
|
|
|
|
|
|
|
Note: at the moment it is impossible to remove a one time listener.
|
2013-10-23 23:29:33 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
def onetime_listener(event):
|
|
|
|
""" Removes listener from eventbus and then fires listener. """
|
|
|
|
self.remove_listener(event_type, onetime_listener)
|
|
|
|
|
|
|
|
listener(event)
|
|
|
|
|
|
|
|
self.listen(event_type, onetime_listener)
|
|
|
|
|
2013-10-09 01:50:30 +00:00
|
|
|
def remove_listener(self, event_type, listener):
|
|
|
|
""" Removes a listener of a specific event_type. """
|
|
|
|
try:
|
|
|
|
self.listeners[event_type].remove(listener)
|
2013-10-23 23:29:33 +00:00
|
|
|
|
|
|
|
if len(self.listeners[event_type]) == 0:
|
|
|
|
del self.listeners[event_type]
|
|
|
|
|
2013-10-09 01:50:30 +00:00
|
|
|
except ValueError:
|
|
|
|
pass
|
2013-09-30 07:20:27 +00:00
|
|
|
|
|
|
|
class StateMachine(object):
|
2013-10-23 23:08:28 +00:00
|
|
|
""" Helper class that tracks the state of different categories. """
|
2013-09-30 07:20:27 +00:00
|
|
|
|
|
|
|
def __init__(self, eventbus):
|
|
|
|
self.states = dict()
|
|
|
|
self.eventbus = eventbus
|
2013-10-09 01:50:30 +00:00
|
|
|
self.lock = threading.Lock()
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2013-10-23 23:08:28 +00:00
|
|
|
@property
|
|
|
|
def categories(self):
|
|
|
|
""" List of categories which states are being tracked. """
|
|
|
|
return self.states.keys()
|
|
|
|
|
2013-10-24 06:57:08 +00:00
|
|
|
def set_state(self, category, new_state, attributes=None):
|
|
|
|
""" Set the state of a category, add category if it does not exist.
|
|
|
|
|
|
|
|
Attributes is an optional dict to specify attributes of this state. """
|
|
|
|
|
|
|
|
attributes = attributes or {}
|
2013-09-30 07:20:27 +00:00
|
|
|
|
|
|
|
self.lock.acquire()
|
|
|
|
|
2013-10-23 23:08:28 +00:00
|
|
|
# Add category if it does not exist
|
2013-09-30 07:20:27 +00:00
|
|
|
if category not in self.states:
|
2013-10-24 06:57:08 +00:00
|
|
|
self.states[category] = State(new_state, datetime.now(),
|
|
|
|
attributes)
|
2013-09-30 07:20:27 +00:00
|
|
|
|
|
|
|
# Change state and fire listeners
|
|
|
|
else:
|
|
|
|
old_state = self.states[category]
|
|
|
|
|
2013-10-24 06:57:08 +00:00
|
|
|
if old_state.state != new_state or \
|
|
|
|
old_state.attributes != attributes:
|
|
|
|
|
|
|
|
self.states[category] = State(new_state, datetime.now(),
|
|
|
|
attributes)
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2013-10-09 01:50:30 +00:00
|
|
|
self.eventbus.fire(EVENT_STATE_CHANGED,
|
2013-10-08 06:55:19 +00:00
|
|
|
{'category':category,
|
|
|
|
'old_state':old_state,
|
2013-10-09 01:50:30 +00:00
|
|
|
'new_state':self.states[category]})
|
2013-09-30 07:20:27 +00:00
|
|
|
|
|
|
|
self.lock.release()
|
|
|
|
|
|
|
|
def is_state(self, category, state):
|
2013-10-26 21:26:58 +00:00
|
|
|
""" Returns True if category exists and is specified state. """
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2013-10-26 21:26:58 +00:00
|
|
|
state = self.states.get(category, None)
|
|
|
|
|
|
|
|
return state and state.state == state
|
2013-09-30 07:20:27 +00:00
|
|
|
|
|
|
|
def get_state(self, category):
|
2013-10-08 06:55:19 +00:00
|
|
|
""" Returns a tuple (state,last_changed) describing
|
|
|
|
the state of the specified category. """
|
2013-09-30 07:20:27 +00:00
|
|
|
if category not in self.states:
|
2013-10-08 06:55:19 +00:00
|
|
|
raise CategoryDoesNotExistException(
|
|
|
|
"Category {} does not exist.".format(category))
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2013-10-26 21:26:58 +00:00
|
|
|
return self.states[category]
|
|
|
|
|
|
|
|
|
2013-09-30 07:20:27 +00:00
|
|
|
class Timer(threading.Thread):
|
|
|
|
""" Timer will sent out an event every TIMER_INTERVAL seconds. """
|
|
|
|
|
|
|
|
def __init__(self, eventbus):
|
|
|
|
threading.Thread.__init__(self)
|
|
|
|
|
2013-10-09 02:00:10 +00:00
|
|
|
self.daemon = True
|
2013-09-30 07:20:27 +00:00
|
|
|
self.eventbus = eventbus
|
|
|
|
|
2013-10-23 23:29:33 +00:00
|
|
|
eventbus.listen_once(EVENT_START, lambda event: self.start())
|
2013-09-30 07:20:27 +00:00
|
|
|
|
|
|
|
def run(self):
|
|
|
|
""" Start the timer. """
|
|
|
|
|
|
|
|
logging.getLogger(__name__).info("Timer:starting")
|
|
|
|
|
2013-10-24 00:42:16 +00:00
|
|
|
last_fired_on_second = -1
|
|
|
|
|
2013-09-25 01:39:58 +00:00
|
|
|
while True:
|
2013-10-24 00:42:16 +00:00
|
|
|
# Sleep till it is the next time that we have to fire an event.
|
|
|
|
# Aim for halfway through the second that matches TIMER_INTERVAL.
|
|
|
|
# So if TIMER_INTERVAL is 10 fire at .5, 10.5, 20.5, etc seconds.
|
|
|
|
# This will yield the best results because time.sleep() is not
|
|
|
|
# 100% accurate because of non-realtime OS's
|
|
|
|
now = datetime.now()
|
|
|
|
|
|
|
|
if now.second % TIMER_INTERVAL > 0 or \
|
|
|
|
now.second == last_fired_on_second:
|
|
|
|
|
|
|
|
slp_seconds = TIMER_INTERVAL - now.second % TIMER_INTERVAL + \
|
|
|
|
.5 - now.microsecond/1000000.0
|
|
|
|
|
|
|
|
time.sleep(slp_seconds)
|
2013-09-25 01:39:58 +00:00
|
|
|
|
2013-09-30 07:20:27 +00:00
|
|
|
now = datetime.now()
|
|
|
|
|
2013-10-24 00:42:16 +00:00
|
|
|
last_fired_on_second = now.second
|
2013-09-25 01:39:58 +00:00
|
|
|
|
2013-10-09 01:50:30 +00:00
|
|
|
self.eventbus.fire(EVENT_TIME_CHANGED, {'now':now})
|
2013-09-30 07:20:27 +00:00
|
|
|
|
|
|
|
class HomeAssistantException(Exception):
|
|
|
|
""" General Home Assistant exception occured. """
|
2013-09-25 01:39:58 +00:00
|
|
|
|
2013-09-30 07:20:27 +00:00
|
|
|
class CategoryDoesNotExistException(HomeAssistantException):
|
|
|
|
""" Specified category does not exist within the state machine. """
|
2013-09-25 01:39:58 +00:00
|
|
|
|
|
|
|
|