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

578 lines
19 KiB
Python
Raw Normal View History

"""
homeassistant
~~~~~~~~~~~~~
Home Assistant is a Home Automation framework for observing the state
of entities and react to changes.
"""
import time
2013-09-30 09:20:27 +02:00
import logging
import threading
import datetime as dt
import functools as ft
import homeassistant.util as util
2013-09-30 09:20:27 +02:00
MATCH_ALL = '*'
DOMAIN = "homeassistant"
SERVICE_HOMEASSISTANT_STOP = "stop"
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!"
BUS_NUM_THREAD = 4
2014-01-30 07:48:35 +01:00
BUS_REPORT_BUSY_TIMEOUT = dt.timedelta(minutes=1)
PRIO_SERVICE_DEFAULT = 1
PRIO_EVENT_STATE = 2
PRIO_EVENT_TIME = 3
PRIO_EVENT_DEFAULT = 4
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, 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
2014-01-04 22:48:17 +01:00
while not request_shutdown.isSet():
2013-09-30 09:20:27 +02:00
try:
time.sleep(1)
except KeyboardInterrupt:
break
2013-11-11 01:46:48 +01:00
def _process_match_param(parameter):
""" Wraps parameter in a list if it is not one and returns it. """
2014-01-23 04:40:19 +01:00
if not parameter:
return MATCH_ALL
elif isinstance(parameter, list):
return parameter
else:
return [parameter]
2013-09-30 09:20:27 +02:00
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 `MATCH_ALL`.
"""
return MATCH_ALL == pattern or subject in pattern
2013-11-11 01:46:48 +01:00
def track_state_change(bus, entity_id, action, from_state=None, to_state=None):
2013-09-30 09:20:27 +02:00
""" Helper method to track specific state changes. """
from_state = _process_match_param(from_state)
to_state = _process_match_param(to_state)
@ft.wraps(action)
2014-01-30 07:48:35 +01:00
def state_listener(event):
2013-09-30 09:20:27 +02:00
""" State change listener that listens for specific state changes. """
if entity_id == event.data['entity_id'] and \
_matcher(event.data['old_state'].state, from_state) and \
_matcher(event.data['new_state'].state, to_state):
action(event.data['entity_id'],
event.data['old_state'],
event.data['new_state'])
2014-01-30 07:48:35 +01:00
bus.listen_event(EVENT_STATE_CHANGED, state_listener)
2013-11-11 01:46:48 +01:00
def track_point_in_time(bus, action, point_in_time):
""" Adds a listener that will fire once after a spefic point in time. """
@ft.wraps(action)
def point_in_time_listener(event):
""" Listens for matching time_changed events. """
now = event.data['now']
if now > point_in_time and not hasattr(point_in_time_listener, 'run'):
# Set variable so that we will never run twice.
# Because the event bus might have to wait till a thread comes
# available to execute this listener it might occur that the
# listener gets lined up twice to be executed. This will make sure
# the second time it does nothing.
point_in_time_listener.run = True
bus.remove_event_listener(EVENT_TIME_CHANGED,
point_in_time_listener)
action(now)
bus.listen_event(EVENT_TIME_CHANGED, point_in_time_listener)
# pylint: disable=too-many-arguments
def track_time_change(bus, action,
year=None, month=None, day=None,
hour=None, minute=None, second=None):
""" Adds a listener that will fire if time matches a pattern. """
2013-09-30 09:20:27 +02:00
# We do not have to wrap the function with time pattern matching logic if
# no pattern given
if any((val is not None for val in
(year, month, day, hour, minute, second))):
pmp = _process_match_param
year, month, day = pmp(year), pmp(month), pmp(day)
hour, minute, second = pmp(hour), pmp(minute), pmp(second)
@ft.wraps(action)
def time_listener(event):
""" Listens for matching time_changed events. """
now = event.data['now']
2013-09-30 09:20:27 +02:00
mat = _matcher
2013-09-30 09:20:27 +02:00
if mat(now.year, year) and \
mat(now.month, month) and \
mat(now.day, day) and \
mat(now.hour, hour) and \
mat(now.minute, minute) and \
mat(now.second, second):
action(now)
else:
@ft.wraps(action)
def time_listener(event):
""" Fires every time event that comes in. """
action(event.data['now'])
2014-01-30 07:48:35 +01:00
bus.listen_event(EVENT_TIME_CHANGED, time_listener)
2013-09-30 09:20:27 +02:00
def create_bus_job_handler(logger):
""" Creates a job handler that logs errors to supplied `logger`. """
def job_handler(job):
""" Called whenever a job is available to do. """
try:
func, arg = job
func(arg)
except Exception: # pylint: disable=broad-except
# Catch any exception our service/event_listener might throw
# We do not want to crash our ThreadPool
2014-03-12 06:35:51 +01:00
logger.exception(u"BusHandler:Exception doing job")
return job_handler
# pylint: disable=too-few-public-methods
class ServiceCall(object):
""" Represents a call to a service. """
__slots__ = ['domain', 'service', 'data']
def __init__(self, domain, service, data=None):
self.domain = domain
self.service = service
self.data = data or {}
def __repr__(self):
if self.data:
2014-03-12 06:35:51 +01:00
return u"<ServiceCall {}.{}: {}>".format(
self.domain, self.service, util.repr_helper(self.data))
else:
2014-03-12 06:35:51 +01:00
return u"<ServiceCall {}.{}>".format(self.domain, self.service)
# pylint: disable=too-few-public-methods
class Event(object):
""" Represents an event within the Bus. """
__slots__ = ['event_type', 'data']
def __init__(self, event_type, data=None):
self.event_type = event_type
self.data = data or {}
def __repr__(self):
if self.data:
2014-03-12 06:35:51 +01:00
return u"<Event {}: {}>".format(
self.event_type, util.repr_helper(self.data))
else:
2014-03-12 06:35:51 +01:00
return u"<Event {}>".format(self.event_type)
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
# pylint: disable=too-many-instance-attributes
def __init__(self, thread_count=None):
2014-01-30 07:48:35 +01:00
self.thread_count = thread_count or BUS_NUM_THREAD
self._event_listeners = {}
self._services = {}
self.logger = logging.getLogger(__name__)
self.event_lock = threading.Lock()
self.service_lock = threading.Lock()
2014-01-30 07:48:35 +01:00
self.last_busy_notice = dt.datetime.now()
self.pool = util.ThreadPool(self.thread_count,
create_bus_job_handler(self.logger))
@property
def services(self):
""" Dict with per domain a list of available services. """
with self.service_lock:
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.
"""
with self.event_lock:
return {key: len(self._event_listeners[key])
for key in self._event_listeners}
2014-01-24 06:33:54 +01:00
def has_service(self, domain, service):
""" Returns True if specified service exists. """
try:
return service in self._services[domain]
except KeyError: # if key 'domain' does not exist
return False
2014-01-24 06:33:54 +01:00
def call_service(self, domain, service, service_data=None):
""" Calls a service. """
service_call = ServiceCall(domain, service, service_data)
2014-01-24 06:33:54 +01:00
with self.service_lock:
try:
self.pool.add_job(PRIO_SERVICE_DEFAULT,
(self._services[domain][service],
service_call))
2014-01-30 07:48:35 +01:00
self._check_busy()
except KeyError: # if key domain or service does not exist
raise ServiceDoesNotExistError(
2014-03-12 06:35:51 +01:00
u"Service does not exist: {}/{}".format(domain, service))
def register_service(self, domain, service, service_func):
""" Register a service. """
with self.service_lock:
try:
self._services[domain][service] = service_func
except KeyError: # Domain does not exist yet in self._services
self._services[domain] = {service: service_func}
def fire_event(self, event_type, event_data=None):
2013-09-30 09:20:27 +02:00
""" Fire an event. """
with self.event_lock:
# Copy the list of the current listeners because some listeners
# remove themselves as a listener while being executed which
# causes the iterator to be confused.
get = self._event_listeners.get
listeners = get(MATCH_ALL, []) + get(event_type, [])
2013-09-30 09:20:27 +02:00
event = Event(event_type, event_data)
2014-03-12 06:35:51 +01:00
self.logger.info(u"Bus:Handling {}".format(event))
if not listeners:
return
if event_type == EVENT_TIME_CHANGED:
prio = PRIO_EVENT_TIME
elif event_type == EVENT_STATE_CHANGED:
prio = PRIO_EVENT_STATE
else:
prio = PRIO_EVENT_DEFAULT
for func in listeners:
self.pool.add_job(prio, (func, event))
2014-01-30 07:48:35 +01:00
self._check_busy()
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 ``MATCH_ALL``
as event_type.
"""
with self.event_lock:
try:
self._event_listeners[event_type].append(listener)
except KeyError: # event_type did not exist
self._event_listeners[event_type] = [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 ``MATCH_ALL``
2013-10-24 01:29:33 +02:00
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
"""
@ft.wraps(listener)
2013-10-24 01:29:33 +02:00
def onetime_listener(event):
""" Removes listener from eventbus and then fires listener. """
if not hasattr(onetime_listener, 'run'):
# Set variable so that we will never run twice.
# Because the event bus might have to wait till a thread comes
# available to execute this listener it might occur that the
# listener gets lined up twice to be executed.
# This will make sure the second time it does nothing.
onetime_listener.run = True
2013-10-24 01:29:33 +02:00
self.remove_event_listener(event_type, onetime_listener)
2013-10-24 01:29:33 +02:00
listener(event)
2014-01-30 07:48:35 +01:00
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. """
with self.event_lock:
try:
self._event_listeners[event_type].remove(listener)
2013-10-24 01:29:33 +02:00
# delete event_type list if empty
if not self._event_listeners[event_type]:
self._event_listeners.pop(event_type)
2013-10-24 01:29:33 +02:00
except (KeyError, AttributeError):
# KeyError is key event_type listener did not exist
# AttributeError if listener did not exist within event_type
pass
2013-09-30 09:20:27 +02:00
2014-01-30 07:48:35 +01:00
def _check_busy(self):
""" Complain if we have more than twice as many jobs queued as threads
and if we didn't complain about it recently. """
if self.pool.queue.qsize() / self.thread_count >= 2 and \
dt.datetime.now()-self.last_busy_notice > BUS_REPORT_BUSY_TIMEOUT:
self.last_busy_notice = dt.datetime.now()
log_error = self.logger.error
2014-01-30 07:48:35 +01:00
log_error(
2014-03-12 06:35:51 +01:00
u"Bus:All {} threads are busy and {} jobs pending".format(
2014-01-30 07:48:35 +01:00
self.thread_count, self.pool.queue.qsize()))
jobs = self.pool.current_jobs
for start, job in jobs:
2014-03-12 06:35:51 +01:00
log_error(u"Bus:Current job from {}: {}".format(
2014-01-30 07:48:35 +01:00
util.datetime_to_str(start), job))
2013-11-11 01:46:48 +01:00
class State(object):
""" Object to represent a state within the state machine. """
2014-01-23 04:41:51 +01:00
__slots__ = ['entity_id', 'state', 'attributes', 'last_changed']
2014-01-23 04:40:19 +01:00
def __init__(self, entity_id, state, attributes=None, last_changed=None):
self.entity_id = entity_id
self.state = state
self.attributes = attributes or {}
last_changed = last_changed or dt.datetime.now()
# Strip microsecond from last_changed else we cannot guarantee
2014-01-23 04:40:19 +01:00
# state == State.from_dict(state.as_dict())
# This behavior occurs because to_dict uses datetime_to_str
# which strips microseconds
if last_changed.microsecond:
self.last_changed = last_changed - dt.timedelta(
microseconds=last_changed.microsecond)
else:
self.last_changed = last_changed
def copy(self):
""" Creates a copy of itself. """
2014-01-23 04:40:19 +01:00
return State(self.entity_id, self.state,
dict(self.attributes), self.last_changed)
2014-01-23 04:40:19 +01:00
def as_dict(self):
""" Converts State to a dict to be used within JSON.
2014-01-23 04:40:19 +01:00
Ensures: state == State.from_dict(state.as_dict()) """
2014-01-23 04:40:19 +01:00
return {'entity_id': self.entity_id,
'state': self.state,
'attributes': self.attributes,
'last_changed': util.datetime_to_str(self.last_changed)}
@staticmethod
2014-01-23 04:40:19 +01:00
def from_dict(json_dict):
""" Static method to create a state from a dict.
Ensures: state == State.from_json_dict(state.to_json_dict()) """
try:
last_changed = json_dict.get('last_changed')
if last_changed:
last_changed = util.str_to_datetime(last_changed)
2014-01-23 04:40:19 +01:00
return State(json_dict['entity_id'],
json_dict['state'],
json_dict.get('attributes'),
last_changed)
except KeyError: # if key 'entity_id' or 'state' did not exist
return None
def __repr__(self):
if self.attributes:
2014-03-12 06:35:51 +01:00
return u"<state {}:{} @ {}>".format(
self.state, util.repr_helper(self.attributes),
util.datetime_to_str(self.last_changed))
else:
2014-03-12 06:35:51 +01:00
return u"<state {} @ {}>".format(
self.state, util.datetime_to_str(self.last_changed))
2013-09-30 09:20:27 +02:00
class StateMachine(object):
""" Helper class that tracks the state of different entities. """
2013-09-30 09:20:27 +02:00
def __init__(self, bus):
self.states = {}
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 entity_ids(self):
""" List of entitie ids that are being tracked. """
with self.lock:
return self.states.keys()
2013-10-24 01:08:28 +02:00
def remove_entity(self, entity_id):
""" Removes a entity from the state machine.
Returns boolean to indicate if a entity was removed. """
with self.lock:
try:
del self.states[entity_id]
return True
except KeyError:
# if entity does not exist
return False
def set_state(self, entity_id, new_state, attributes=None):
""" Set the state of an entity, add entity 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
with self.lock:
# Change state and fire listeners
try:
old_state = self.states[entity_id]
2013-09-30 09:20:27 +02:00
except KeyError:
# If state did not exist yet
2014-01-23 04:40:19 +01:00
self.states[entity_id] = State(entity_id, new_state,
attributes)
else:
if old_state.state != new_state or \
old_state.attributes != attributes:
2014-01-23 04:40:19 +01:00
state = self.states[entity_id] = \
State(entity_id, new_state, attributes)
self.bus.fire_event(EVENT_STATE_CHANGED,
{'entity_id': entity_id,
'old_state': old_state,
'new_state': state})
def get_state(self, entity_id):
2014-01-23 04:40:19 +01:00
""" Returns the state of the specified entity. """
with self.lock:
try:
# Make a copy so people won't mutate the state
return self.states[entity_id].copy()
2013-09-30 09:20:27 +02:00
except KeyError:
# If entity does not exist
return None
def is_state(self, entity_id, state):
""" Returns True if entity exists and is specified state. """
try:
return self.get_state(entity_id).state == state
except AttributeError:
# get_state returned None
return False
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
calc_now = dt.datetime.now
while True:
now = calc_now()
2014-01-04 22:48:17 +01:00
# First check checks if we are not on a second matching the
# timer interval. Second check checks if we did not already fire
# this interval.
if now.second % TIMER_INTERVAL or \
2013-11-11 01:46:48 +01:00
now.second == last_fired_on_second:
2014-01-04 22:48:17 +01:00
# Sleep till it is the next time that we have to fire an event.
# Aim for halfway through the second that fits TIMER_INTERVAL.
# 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
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)
now = calc_now()
2013-09-30 09:20:27 +02:00
last_fired_on_second = now.second
self.bus.fire_event(EVENT_TIME_CHANGED,
{'now': now})
2013-11-11 01:46:48 +01:00
2013-09-30 09:20:27 +02:00
2014-01-24 06:33:12 +01:00
class HomeAssistantError(Exception):
2013-09-30 09:20:27 +02:00
""" General Home Assistant exception occured. """
2014-01-24 06:33:12 +01:00
class ServiceDoesNotExistError(HomeAssistantError):
""" A service has been referenced that deos not exist. """