1
mirror of https://github.com/home-assistant/core synced 2024-08-02 23:40:32 +02:00
ha-core/homeassistant/__init__.py

425 lines
13 KiB
Python
Raw Normal View History

"""
homeassistant
~~~~~~~~~~~~~
Module to control the lights based on devices at home and the state of the sun.
"""
import time
2013-09-30 09:20:27 +02:00
import logging
import threading
from collections import defaultdict, namedtuple
from datetime import datetime
2013-10-09 03:50:30 +02:00
logging.basicConfig(level=logging.INFO)
2013-09-30 09:20:27 +02:00
ALL_EVENTS = '*'
DOMAIN_HOMEASSISTANT = "homeassistant"
SERVICE_TURN_ON = "turn_on"
SERVICE_TURN_OFF = "turn_off"
SERVICE_HOMEASSISTANT_STOP = "stop"
2013-11-11 23:58:57 +01:00
EVENT_HOMEASSISTANT_START = "homeassistant.start"
2013-09-30 09:20:27 +02:00
EVENT_STATE_CHANGED = "state_changed"
EVENT_TIME_CHANGED = "time_changed"
2013-11-11 01:46:48 +01:00
TIMER_INTERVAL = 10 # seconds
2013-09-30 09:20:27 +02:00
# 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!"
DATE_STR_FORMAT = "%H:%M:%S %d-%m-%Y"
2013-09-30 09:20:27 +02:00
2013-11-11 01:46:48 +01:00
def start_home_assistant(bus):
2013-09-30 09:20:27 +02:00
""" Start home assistant. """
2013-11-11 23:58:57 +01:00
request_shutdown = threading.Event()
bus.register_service(DOMAIN_HOMEASSISTANT, SERVICE_HOMEASSISTANT_STOP,
lambda service: request_shutdown.set())
2013-11-11 23:58:57 +01:00
Timer(bus)
2013-09-30 09:20:27 +02:00
bus.fire_event(EVENT_HOMEASSISTANT_START)
2013-09-30 09:20:27 +02:00
while True:
try:
time.sleep(1)
2013-11-11 23:58:57 +01:00
if request_shutdown.isSet():
break
2013-09-30 09:20:27 +02:00
except KeyboardInterrupt:
break
2013-11-11 01:46:48 +01:00
def datetime_to_str(dattim):
2013-11-10 18:31:34 +01:00
""" Converts datetime to a string format.
@rtype : str
"""
return dattim.strftime(DATE_STR_FORMAT)
2013-11-11 01:46:48 +01:00
def str_to_datetime(dt_str):
2013-11-10 18:31:34 +01:00
""" Converts a string to a datetime object.
@rtype: datetime
"""
return datetime.strptime(dt_str, DATE_STR_FORMAT)
2013-11-11 01:46:48 +01:00
def _ensure_list(parameter):
2013-11-10 18:31:34 +01:00
""" Wraps parameter in a list if it is not one and returns it.
@rtype : list
"""
2013-09-30 09:20:27 +02:00
return parameter if isinstance(parameter, list) else [parameter]
2013-11-11 01:46:48 +01:00
def _matcher(subject, pattern):
2013-09-30 09:20:27 +02:00
""" Returns True if subject matches the pattern.
Pattern is either a list of allowed subjects or a '*'.
2013-11-10 18:31:34 +01:00
@rtype : bool
"""
2013-09-30 09:20:27 +02:00
return '*' in pattern or subject in pattern
2013-11-11 01:46:48 +01:00
def get_grouped_state_cats(statemachine, cat_format_string, strip_prefix):
""" Get states that are part of a group of states.
Example category_format_string can be "devices.{}"
If input states are devices, devices.paulus and devices.paulus.charging
then the output will be paulus if strip_prefix is True, else devices.paulus
"""
group_prefix = cat_format_string.format("")
if strip_prefix:
id_part = slice(len(group_prefix), None)
return [cat[id_part] for cat in statemachine.categories
if cat.startswith(group_prefix) and cat.count(".") == 1]
else:
return [cat for cat in statemachine.categories
if cat.startswith(group_prefix) and cat.count(".") == 1]
def create_state(state, attributes=None, last_changed=None):
""" Creates a new state and initializes defaults where necessary. """
attributes = attributes or {}
last_changed = last_changed or datetime.now()
return {'state': state,
'attributes': attributes,
'last_changed': datetime_to_str(last_changed)}
2013-11-11 01:46:48 +01:00
def track_state_change(bus, category, from_state, to_state, action):
2013-09-30 09:20:27 +02:00
""" Helper method to track specific state changes. """
from_state = _ensure_list(from_state)
to_state = _ensure_list(to_state)
2013-09-30 09:20:27 +02: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):
action(event.data['category'],
event.data['old_state'],
event.data['new_state'])
bus.listen_event(EVENT_STATE_CHANGED, listener)
2013-11-11 01:46:48 +01:00
# pylint: disable=too-many-arguments
def track_time_change(bus, action,
year='*', month='*', day='*',
hour='*', minute='*', second='*',
point_in_time=None, listen_once=False):
2013-09-30 09:20:27 +02:00
""" Adds a listener that will listen for a specified or matching time. """
year, month = _ensure_list(year), _ensure_list(month)
day = _ensure_list(day)
hour, minute = _ensure_list(hour), _ensure_list(minute)
second = _ensure_list(second)
2013-09-30 09:20:27 +02:00
def listener(event):
""" Listens for matching time_changed events. """
now = str_to_datetime(event.data['now'])
2013-11-10 18:31:34 +01:00
if (point_in_time and now > point_in_time) or \
2013-11-11 01:46:48 +01:00
(not point_in_time and
_matcher(now.year, year) and
_matcher(now.month, month) and
_matcher(now.day, day) and
_matcher(now.hour, hour) and
_matcher(now.minute, minute) and
_matcher(now.second, second)):
2013-09-30 09:20:27 +02:00
# point_in_time are exact points in time
# so we always remove it after fire
2013-10-09 03:50:30 +02:00
if listen_once or point_in_time:
event.bus.remove_event_listener(EVENT_TIME_CHANGED, listener)
2013-09-30 09:20:27 +02:00
action(now)
2013-09-30 09:20:27 +02:00
bus.listen_event(EVENT_TIME_CHANGED, listener)
2013-09-30 09:20:27 +02:00
ServiceCall = namedtuple("ServiceCall", ["bus", "domain", "service", "data"])
Event = namedtuple("Event", ["bus", "event_type", "data"])
2013-11-11 01:46:48 +01:00
2013-10-09 03:50:30 +02:00
class Bus(object):
""" Class that allows different components to communicate via services
and events.
"""
2013-09-30 09:20:27 +02:00
def __init__(self):
self._event_listeners = defaultdict(list)
self._services = {}
self.logger = logging.getLogger(__name__)
@property
def services(self):
""" Dict with per domain a list of available services. """
return {domain: self._services[domain].keys()
for domain in self._services}
@property
def event_listeners(self):
""" Dict with events that is being listened for and the number
of listeners.
"""
return {key: len(self._event_listeners[key])
for key in self._event_listeners.keys()
if len(self._event_listeners[key]) > 0}
def call_service(self, domain, service, service_data=None):
""" Calls a service. """
try:
self._services[domain][service]
except KeyError:
# Domain or Service does not exist
raise ServiceDoesNotExistException(
"Service does not exist: {}/{}".format(domain, service))
if not service_data:
service_data = {}
def run():
""" Executes a service. """
service_call = ServiceCall(self, domain, service, service_data)
try:
self._services[domain][service](service_call)
except Exception: # pylint: disable=broad-except
self.logger.exception("Bus:Exception in service {}/{}".format(
domain, service))
# We dont want the eventbus to be blocking - run in a thread.
threading.Thread(target=run).start()
def register_service(self, domain, service, service_callback):
""" Register a service. """
try:
self._services[domain][service] = service_callback
except KeyError:
# Domain does not exist yet
self._services[domain] = {service: service_callback}
def fire_event(self, event_type, event_data=None):
2013-09-30 09:20:27 +02:00
""" Fire an event. """
2013-10-09 03:50:30 +02:00
if not event_data:
event_data = {}
2013-09-30 09:20:27 +02:00
self.logger.info("Bus:Event {}: {}".format(
2013-11-11 01:46:48 +01:00
event_type, event_data))
2013-09-30 09:20:27 +02:00
2013-10-09 03:50:30 +02:00
def run():
""" Fire listeners for event. """
event = Event(self, event_type, event_data)
2013-10-24 01:29:33 +02: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._event_listeners[ALL_EVENTS] + \
self._event_listeners[event.event_type]:
try:
2013-10-09 03:50:30 +02:00
listener(event)
2013-11-11 01:46:48 +01:00
except Exception: # pylint: disable=broad-except
self.logger.exception("Bus:Exception in event listener")
2013-09-30 09:20:27 +02:00
# We dont want the bus to be blocking - run in a thread.
2013-09-30 09:20:27 +02:00
threading.Thread(target=run).start()
def listen_event(self, event_type, listener):
2013-09-30 09:20:27 +02:00
""" Listen for all events or events of a specific type.
To listen to all events specify the constant ``ALL_EVENTS``
as event_type.
"""
self._event_listeners[event_type].append(listener)
def listen_once_event(self, event_type, listener):
2013-10-24 01:29:33 +02:00
""" Listen once for event of a specific type.
To listen to all events specify the constant ``ALL_EVENTS``
as event_type.
2013-10-25 12:05:34 +02:00
Note: at the moment it is impossible to remove a one time listener.
2013-10-24 01:29:33 +02:00
"""
def onetime_listener(event):
""" Removes listener from eventbus and then fires listener. """
self.remove_event_listener(event_type, onetime_listener)
2013-10-24 01:29:33 +02:00
listener(event)
self.listen_event(event_type, onetime_listener)
2013-10-24 01:29:33 +02:00
def remove_event_listener(self, event_type, listener):
2013-10-09 03:50:30 +02:00
""" Removes a listener of a specific event_type. """
try:
self._event_listeners[event_type].remove(listener)
2013-10-24 01:29:33 +02:00
if len(self._event_listeners[event_type]) == 0:
del self._event_listeners[event_type]
2013-10-24 01:29:33 +02:00
2013-10-09 03:50:30 +02:00
except ValueError:
pass
2013-09-30 09:20:27 +02:00
2013-11-11 01:46:48 +01:00
2013-09-30 09:20:27 +02:00
class StateMachine(object):
2013-10-24 01:08:28 +02:00
""" Helper class that tracks the state of different categories. """
2013-09-30 09:20:27 +02:00
def __init__(self, bus):
2013-09-30 09:20:27 +02:00
self.states = dict()
self.bus = bus
2013-10-09 03:50:30 +02:00
self.lock = threading.Lock()
2013-09-30 09:20:27 +02:00
2013-10-24 01:08:28 +02:00
@property
def categories(self):
""" List of categories which states are being tracked. """
return self.states.keys()
def remove_category(self, category):
""" Removes a category from the state machine.
Returns boolean to indicate if a category was removed. """
try:
del self.states[category]
return True
except KeyError:
# if category does not exist
return False
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 09:20:27 +02:00
self.lock.acquire()
2013-10-24 01:08:28 +02:00
# Add category if it does not exist
2013-09-30 09:20:27 +02:00
if category not in self.states:
self.states[category] = create_state(new_state, attributes)
2013-09-30 09:20:27 +02:00
# Change state and fire listeners
else:
old_state = self.states[category]
if old_state['state'] != new_state or \
2013-11-11 01:46:48 +01:00
old_state['attributes'] != attributes:
self.states[category] = create_state(new_state, attributes)
2013-09-30 09:20:27 +02:00
self.bus.fire_event(EVENT_STATE_CHANGED,
{'category': category,
'old_state': old_state,
'new_state': self.states[category]})
2013-09-30 09:20:27 +02:00
self.lock.release()
def get_state(self, category):
""" Returns a dict (state,last_changed, attributes) describing
the state of the specified category. """
try:
# Make a copy so people won't accidently mutate the state
return dict(self.states[category])
2013-09-30 09:20:27 +02:00
except KeyError:
# If category does not exist
return None
def is_state(self, category, state):
""" Returns True if category exists and is specified state. """
cur_state = self.get_state(category)
return cur_state and cur_state['state'] == state
2013-11-11 01:46:48 +01:00
2013-09-30 09:20:27 +02:00
class Timer(threading.Thread):
""" Timer will sent out an event every TIMER_INTERVAL seconds. """
def __init__(self, bus):
2013-09-30 09:20:27 +02:00
threading.Thread.__init__(self)
self.daemon = True
self.bus = bus
2013-09-30 09:20:27 +02:00
bus.listen_once_event(EVENT_HOMEASSISTANT_START,
lambda event: self.start())
2013-09-30 09:20:27 +02:00
def run(self):
""" Start the timer. """
logging.getLogger(__name__).info("Timer:starting")
last_fired_on_second = -1
while True:
# 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 \
2013-11-11 01:46:48 +01:00
now.second == last_fired_on_second:
slp_seconds = TIMER_INTERVAL - now.second % TIMER_INTERVAL + \
2013-11-11 01:46:48 +01:00
.5 - now.microsecond/1000000.0
time.sleep(slp_seconds)
2013-09-30 09:20:27 +02:00
now = datetime.now()
last_fired_on_second = now.second
self.bus.fire_event(EVENT_TIME_CHANGED,
{'now': datetime_to_str(now)})
2013-11-11 01:46:48 +01:00
2013-09-30 09:20:27 +02:00
class HomeAssistantException(Exception):
""" General Home Assistant exception occured. """
class ServiceDoesNotExistException(HomeAssistantException):
""" A service has been referenced that deos not exist. """