2013-09-25 01:39:58 +00:00
|
|
|
"""
|
2015-12-28 05:14:35 +00:00
|
|
|
Core components of Home Assistant.
|
2013-09-25 01:39:58 +00:00
|
|
|
|
2014-01-20 03:10:40 +00:00
|
|
|
Home Assistant is a Home Automation framework for observing the state
|
2014-01-20 07:37:40 +00:00
|
|
|
of entities and react to changes.
|
2013-09-25 01:39:58 +00:00
|
|
|
"""
|
|
|
|
|
2014-09-21 02:19:39 +00:00
|
|
|
import os
|
2013-09-25 01:39:58 +00:00
|
|
|
import time
|
2013-09-30 07:20:27 +00:00
|
|
|
import logging
|
2015-09-01 06:12:00 +00:00
|
|
|
import signal
|
2013-09-30 07:20:27 +00:00
|
|
|
import threading
|
2014-04-29 07:30:31 +00:00
|
|
|
import enum
|
2014-02-14 19:34:09 +00:00
|
|
|
import functools as ft
|
2015-07-26 08:45:49 +00:00
|
|
|
from collections import namedtuple
|
2014-01-20 03:10:40 +00:00
|
|
|
|
2014-12-07 07:57:02 +00:00
|
|
|
from homeassistant.const import (
|
2015-10-26 04:00:22 +00:00
|
|
|
__version__, EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP,
|
2014-12-07 07:57:02 +00:00
|
|
|
SERVICE_HOMEASSISTANT_STOP, EVENT_TIME_CHANGED, EVENT_STATE_CHANGED,
|
2014-12-14 06:40:00 +00:00
|
|
|
EVENT_CALL_SERVICE, ATTR_NOW, ATTR_DOMAIN, ATTR_SERVICE, MATCH_ALL,
|
2015-03-19 06:02:58 +00:00
|
|
|
EVENT_SERVICE_EXECUTED, ATTR_SERVICE_CALL_ID, EVENT_SERVICE_REGISTERED,
|
2015-03-29 21:39:47 +00:00
|
|
|
TEMP_CELCIUS, TEMP_FAHRENHEIT, ATTR_FRIENDLY_NAME)
|
2015-08-30 01:11:24 +00:00
|
|
|
from homeassistant.exceptions import (
|
2015-08-30 02:34:35 +00:00
|
|
|
HomeAssistantError, InvalidEntityFormatError)
|
2014-01-20 03:10:40 +00:00
|
|
|
import homeassistant.util as util
|
2015-12-06 17:12:19 +00:00
|
|
|
import homeassistant.util.dt as dt_util
|
2015-09-20 16:35:03 +00:00
|
|
|
import homeassistant.util.location as location
|
2016-01-24 06:49:49 +00:00
|
|
|
from homeassistant.helpers.entity import valid_entity_id, split_entity_id
|
2015-08-17 05:06:01 +00:00
|
|
|
import homeassistant.helpers.temperature as temp_helper
|
2015-08-30 01:11:24 +00:00
|
|
|
from homeassistant.config import get_default_config_dir
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2014-01-05 01:55:05 +00:00
|
|
|
DOMAIN = "homeassistant"
|
|
|
|
|
2014-04-24 07:40:45 +00:00
|
|
|
# How often time_changed event should fire
|
2015-01-25 02:04:19 +00:00
|
|
|
TIMER_INTERVAL = 1 # seconds
|
2014-02-14 19:34:09 +00:00
|
|
|
|
2014-12-14 06:40:00 +00:00
|
|
|
# How long we wait for the result of a service call
|
|
|
|
SERVICE_CALL_LIMIT = 10 # seconds
|
|
|
|
|
2014-12-17 05:46:02 +00:00
|
|
|
# Define number of MINIMUM worker threads.
|
2015-08-03 15:05:33 +00:00
|
|
|
# During bootstrap of HA (see bootstrap._setup_component()) worker threads
|
2014-12-17 05:46:02 +00:00
|
|
|
# will be added for each component that polls devices.
|
|
|
|
MIN_WORKER_THREAD = 2
|
2013-11-11 22:58:57 +00:00
|
|
|
|
2014-11-08 21:57:08 +00:00
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
2015-08-03 15:05:33 +00:00
|
|
|
# Temporary to support deprecated methods
|
2015-07-26 08:45:49 +00:00
|
|
|
_MockHA = namedtuple("MockHomeAssistant", ['bus'])
|
|
|
|
|
2013-11-11 22:58:57 +00:00
|
|
|
|
2014-04-24 07:40:45 +00:00
|
|
|
class HomeAssistant(object):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Root object of the Home Assistant home automation."""
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2014-04-24 07:40:45 +00:00
|
|
|
def __init__(self):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Initialize new Home Assistant object."""
|
2014-12-17 05:46:02 +00:00
|
|
|
self.pool = pool = create_worker_pool()
|
2014-04-24 07:40:45 +00:00
|
|
|
self.bus = EventBus(pool)
|
|
|
|
self.services = ServiceRegistry(self.bus, pool)
|
2014-04-29 07:30:31 +00:00
|
|
|
self.states = StateMachine(self.bus)
|
2015-03-19 06:02:58 +00:00
|
|
|
self.config = Config()
|
2015-01-18 05:13:02 +00:00
|
|
|
|
2014-04-29 07:30:31 +00:00
|
|
|
def start(self):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Start home assistant."""
|
2014-12-17 05:46:02 +00:00
|
|
|
_LOGGER.info(
|
|
|
|
"Starting Home Assistant (%d threads)", self.pool.worker_count)
|
|
|
|
|
2015-07-26 08:45:49 +00:00
|
|
|
create_timer(self)
|
2014-04-24 07:40:45 +00:00
|
|
|
self.bus.fire(EVENT_HOMEASSISTANT_START)
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2014-04-29 07:30:31 +00:00
|
|
|
def block_till_stopped(self):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Register service homeassistant/stop and will block until called."""
|
2014-04-24 07:40:45 +00:00
|
|
|
request_shutdown = threading.Event()
|
2013-10-08 06:55:19 +00:00
|
|
|
|
2015-09-01 06:12:00 +00:00
|
|
|
def stop_homeassistant(*args):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Stop Home Assistant."""
|
2015-08-03 15:05:33 +00:00
|
|
|
request_shutdown.set()
|
|
|
|
|
|
|
|
self.services.register(
|
|
|
|
DOMAIN, SERVICE_HOMEASSISTANT_STOP, stop_homeassistant)
|
2013-09-25 01:39:58 +00:00
|
|
|
|
2015-09-01 06:12:00 +00:00
|
|
|
if os.name != "nt":
|
2015-09-01 08:03:51 +00:00
|
|
|
try:
|
2015-11-15 22:43:38 +00:00
|
|
|
signal.signal(signal.SIGTERM, stop_homeassistant)
|
2015-09-01 08:03:51 +00:00
|
|
|
except ValueError:
|
|
|
|
_LOGGER.warning(
|
|
|
|
'Could not bind to SIGQUIT. Are you running in a thread?')
|
2015-09-01 06:12:00 +00:00
|
|
|
|
2014-04-24 07:40:45 +00:00
|
|
|
while not request_shutdown.isSet():
|
|
|
|
try:
|
|
|
|
time.sleep(1)
|
|
|
|
except KeyboardInterrupt:
|
|
|
|
break
|
2013-09-25 01:39:58 +00:00
|
|
|
|
2014-11-23 17:51:16 +00:00
|
|
|
self.stop()
|
|
|
|
|
|
|
|
def stop(self):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Stop Home Assistant and shuts down all threads."""
|
2014-11-23 17:51:16 +00:00
|
|
|
_LOGGER.info("Stopping")
|
|
|
|
|
2014-11-23 20:57:29 +00:00
|
|
|
self.bus.fire(EVENT_HOMEASSISTANT_STOP)
|
2014-11-23 17:51:16 +00:00
|
|
|
|
2014-11-23 20:57:29 +00:00
|
|
|
# Wait till all responses to homeassistant_stop are done
|
2014-12-17 05:46:02 +00:00
|
|
|
self.pool.block_till_done()
|
2014-11-23 17:51:16 +00:00
|
|
|
|
2014-12-17 05:46:02 +00:00
|
|
|
self.pool.stop()
|
2014-11-23 17:51:16 +00:00
|
|
|
|
2015-07-26 08:45:49 +00:00
|
|
|
def track_point_in_time(self, action, point_in_time):
|
2015-08-04 20:21:09 +00:00
|
|
|
"""Deprecated method as of 8/4/2015 to track point in time."""
|
2014-11-29 07:19:59 +00:00
|
|
|
_LOGGER.warning(
|
2015-07-26 08:45:49 +00:00
|
|
|
'hass.track_point_in_time is deprecated. '
|
|
|
|
'Please use homeassistant.helpers.event.track_point_in_time')
|
|
|
|
import homeassistant.helpers.event as helper
|
|
|
|
helper.track_point_in_time(self, action, point_in_time)
|
2014-11-29 07:19:59 +00:00
|
|
|
|
2015-07-26 08:45:49 +00:00
|
|
|
def track_point_in_utc_time(self, action, point_in_time):
|
2015-08-04 20:21:09 +00:00
|
|
|
"""Deprecated method as of 8/4/2015 to track point in UTC time."""
|
2014-11-29 07:19:59 +00:00
|
|
|
_LOGGER.warning(
|
2015-07-26 08:45:49 +00:00
|
|
|
'hass.track_point_in_utc_time is deprecated. '
|
|
|
|
'Please use homeassistant.helpers.event.track_point_in_utc_time')
|
|
|
|
import homeassistant.helpers.event as helper
|
|
|
|
helper.track_point_in_utc_time(self, action, point_in_time)
|
2014-11-29 07:19:59 +00:00
|
|
|
|
2015-07-26 08:45:49 +00:00
|
|
|
def track_utc_time_change(self, action,
|
|
|
|
year=None, month=None, day=None,
|
|
|
|
hour=None, minute=None, second=None):
|
2015-08-04 20:21:09 +00:00
|
|
|
"""Deprecated method as of 8/4/2015 to track UTC time change."""
|
2015-07-26 08:45:49 +00:00
|
|
|
# pylint: disable=too-many-arguments
|
|
|
|
_LOGGER.warning(
|
|
|
|
'hass.track_utc_time_change is deprecated. '
|
|
|
|
'Please use homeassistant.helpers.event.track_utc_time_change')
|
|
|
|
import homeassistant.helpers.event as helper
|
|
|
|
helper.track_utc_time_change(self, action, year, month, day, hour,
|
|
|
|
minute, second)
|
2014-01-27 02:44:36 +00:00
|
|
|
|
2015-07-26 08:45:49 +00:00
|
|
|
def track_time_change(self, action,
|
|
|
|
year=None, month=None, day=None,
|
|
|
|
hour=None, minute=None, second=None, utc=False):
|
2015-08-04 20:21:09 +00:00
|
|
|
"""Deprecated method as of 8/4/2015 to track time change."""
|
2015-07-26 08:45:49 +00:00
|
|
|
# pylint: disable=too-many-arguments
|
|
|
|
_LOGGER.warning(
|
|
|
|
'hass.track_time_change is deprecated. '
|
|
|
|
'Please use homeassistant.helpers.event.track_time_change')
|
|
|
|
import homeassistant.helpers.event as helper
|
|
|
|
helper.track_time_change(self, action, year, month, day, hour,
|
|
|
|
minute, second)
|
2014-01-27 02:44:36 +00:00
|
|
|
|
|
|
|
|
2014-04-24 07:40:45 +00:00
|
|
|
class JobPriority(util.OrderedEnum):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Provides job priorities for event bus jobs."""
|
2014-04-15 06:48:00 +00:00
|
|
|
|
2014-12-14 06:40:00 +00:00
|
|
|
EVENT_CALLBACK = 0
|
2014-04-24 07:40:45 +00:00
|
|
|
EVENT_SERVICE = 1
|
2014-04-15 06:48:00 +00:00
|
|
|
EVENT_STATE = 2
|
|
|
|
EVENT_TIME = 3
|
|
|
|
EVENT_DEFAULT = 4
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def from_event_type(event_type):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Return a priority based on event type."""
|
2014-04-15 06:48:00 +00:00
|
|
|
if event_type == EVENT_TIME_CHANGED:
|
2014-04-24 07:40:45 +00:00
|
|
|
return JobPriority.EVENT_TIME
|
2014-04-15 06:48:00 +00:00
|
|
|
elif event_type == EVENT_STATE_CHANGED:
|
2014-04-24 07:40:45 +00:00
|
|
|
return JobPriority.EVENT_STATE
|
|
|
|
elif event_type == EVENT_CALL_SERVICE:
|
|
|
|
return JobPriority.EVENT_SERVICE
|
2014-12-14 06:40:00 +00:00
|
|
|
elif event_type == EVENT_SERVICE_EXECUTED:
|
|
|
|
return JobPriority.EVENT_CALLBACK
|
2014-04-15 06:48:00 +00:00
|
|
|
else:
|
2014-04-24 07:40:45 +00:00
|
|
|
return JobPriority.EVENT_DEFAULT
|
2014-04-15 06:48:00 +00:00
|
|
|
|
|
|
|
|
2014-04-29 07:30:31 +00:00
|
|
|
class EventOrigin(enum.Enum):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Represents origin of an event."""
|
2014-04-29 07:30:31 +00:00
|
|
|
|
|
|
|
local = "LOCAL"
|
|
|
|
remote = "REMOTE"
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return self.value
|
|
|
|
|
|
|
|
|
2014-01-27 02:44:36 +00:00
|
|
|
class Event(object):
|
2015-12-28 05:14:35 +00:00
|
|
|
# pylint: disable=too-few-public-methods
|
|
|
|
"""Represents an event within the Bus."""
|
2014-01-27 02:44:36 +00:00
|
|
|
|
2015-03-29 21:39:47 +00:00
|
|
|
__slots__ = ['event_type', 'data', 'origin', 'time_fired']
|
2014-01-27 02:44:36 +00:00
|
|
|
|
2015-03-29 21:39:47 +00:00
|
|
|
def __init__(self, event_type, data=None, origin=EventOrigin.local,
|
|
|
|
time_fired=None):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Initialize a new event."""
|
2014-01-27 02:44:36 +00:00
|
|
|
self.event_type = event_type
|
|
|
|
self.data = data or {}
|
2014-04-29 07:30:31 +00:00
|
|
|
self.origin = origin
|
2015-12-06 17:12:19 +00:00
|
|
|
self.time_fired = dt_util.strip_microseconds(
|
|
|
|
time_fired or dt_util.utcnow())
|
2014-01-27 02:44:36 +00:00
|
|
|
|
2015-01-28 08:22:09 +00:00
|
|
|
def as_dict(self):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Create a dict representation of this Event."""
|
2015-01-28 08:22:09 +00:00
|
|
|
return {
|
|
|
|
'event_type': self.event_type,
|
|
|
|
'data': dict(self.data),
|
2015-03-29 21:39:47 +00:00
|
|
|
'origin': str(self.origin),
|
2015-12-06 17:12:19 +00:00
|
|
|
'time_fired': dt_util.datetime_to_str(self.time_fired),
|
2015-01-28 08:22:09 +00:00
|
|
|
}
|
|
|
|
|
2014-01-27 02:44:36 +00:00
|
|
|
def __repr__(self):
|
2014-04-29 07:30:31 +00:00
|
|
|
# pylint: disable=maybe-no-member
|
2014-01-27 02:44:36 +00:00
|
|
|
if self.data:
|
2014-04-29 07:30:31 +00:00
|
|
|
return "<Event {}[{}]: {}>".format(
|
2014-11-23 06:37:53 +00:00
|
|
|
self.event_type, str(self.origin)[0],
|
2014-04-29 07:30:31 +00:00
|
|
|
util.repr_helper(self.data))
|
2014-01-27 02:44:36 +00:00
|
|
|
else:
|
2014-04-29 07:30:31 +00:00
|
|
|
return "<Event {}[{}]>".format(self.event_type,
|
2014-11-23 06:37:53 +00:00
|
|
|
str(self.origin)[0])
|
2013-11-11 00:46:48 +00:00
|
|
|
|
2015-04-30 06:21:31 +00:00
|
|
|
def __eq__(self, other):
|
|
|
|
return (self.__class__ == other.__class__ and
|
|
|
|
self.event_type == other.event_type and
|
|
|
|
self.data == other.data and
|
|
|
|
self.origin == other.origin and
|
|
|
|
self.time_fired == other.time_fired)
|
|
|
|
|
2013-10-09 01:50:30 +00:00
|
|
|
|
2014-04-24 07:40:45 +00:00
|
|
|
class EventBus(object):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Allows firing of and listening for events."""
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2014-04-24 07:40:45 +00:00
|
|
|
def __init__(self, pool=None):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Initialize a new event bus."""
|
2014-04-24 07:40:45 +00:00
|
|
|
self._listeners = {}
|
|
|
|
self._lock = threading.Lock()
|
2014-04-29 07:30:31 +00:00
|
|
|
self._pool = pool or create_worker_pool()
|
2013-09-25 01:39:58 +00:00
|
|
|
|
2013-11-01 19:28:18 +00:00
|
|
|
@property
|
2014-04-24 07:40:45 +00:00
|
|
|
def listeners(self):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Dict with events and the number of listeners."""
|
2014-04-24 07:40:45 +00:00
|
|
|
with self._lock:
|
|
|
|
return {key: len(self._listeners[key])
|
|
|
|
for key in self._listeners}
|
2014-01-30 06:48:35 +00:00
|
|
|
|
2014-04-29 07:30:31 +00:00
|
|
|
def fire(self, event_type, event_data=None, origin=EventOrigin.local):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Fire an event."""
|
2015-04-30 06:21:31 +00:00
|
|
|
if not self._pool.running:
|
|
|
|
raise HomeAssistantError('Home Assistant has shut down.')
|
|
|
|
|
2014-04-24 07:40:45 +00:00
|
|
|
with self._lock:
|
2014-01-20 05:39:57 +00:00
|
|
|
# Copy the list of the current listeners because some listeners
|
2014-01-27 02:44:36 +00:00
|
|
|
# remove themselves as a listener while being executed which
|
|
|
|
# causes the iterator to be confused.
|
2014-04-24 07:40:45 +00:00
|
|
|
get = self._listeners.get
|
2014-01-20 05:39:57 +00:00
|
|
|
listeners = get(MATCH_ALL, []) + get(event_type, [])
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2014-04-29 07:30:31 +00:00
|
|
|
event = Event(event_type, event_data, origin)
|
2014-01-27 02:44:36 +00:00
|
|
|
|
2015-01-28 08:22:09 +00:00
|
|
|
if event_type != EVENT_TIME_CHANGED:
|
|
|
|
_LOGGER.info("Bus:Handling %s", event)
|
2014-01-24 00:49:43 +00:00
|
|
|
|
2014-01-20 05:39:57 +00:00
|
|
|
if not listeners:
|
|
|
|
return
|
2014-01-20 03:10:40 +00:00
|
|
|
|
2014-12-15 02:28:11 +00:00
|
|
|
job_priority = JobPriority.from_event_type(event_type)
|
|
|
|
|
2014-01-27 02:44:36 +00:00
|
|
|
for func in listeners:
|
2014-12-15 02:28:11 +00:00
|
|
|
self._pool.add_job(job_priority, (func, event))
|
2013-09-25 01:39:58 +00:00
|
|
|
|
2014-04-24 07:40:45 +00:00
|
|
|
def listen(self, event_type, listener):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Listen for all events or events of a specific type.
|
2013-09-25 01:39:58 +00:00
|
|
|
|
2014-01-20 03:10:40 +00:00
|
|
|
To listen to all events specify the constant ``MATCH_ALL``
|
2013-10-08 06:55:19 +00:00
|
|
|
as event_type.
|
|
|
|
"""
|
2014-04-24 07:40:45 +00:00
|
|
|
with self._lock:
|
|
|
|
if event_type in self._listeners:
|
|
|
|
self._listeners[event_type].append(listener)
|
2014-04-15 06:48:00 +00:00
|
|
|
else:
|
2014-04-24 07:40:45 +00:00
|
|
|
self._listeners[event_type] = [listener]
|
2014-01-20 03:10:40 +00:00
|
|
|
|
2014-11-29 07:19:59 +00:00
|
|
|
def listen_once(self, event_type, listener):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Listen once for event of a specific type.
|
2014-11-29 07:19:59 +00:00
|
|
|
|
|
|
|
To listen to all events specify the constant ``MATCH_ALL``
|
|
|
|
as event_type.
|
|
|
|
|
2015-07-26 08:45:49 +00:00
|
|
|
Returns registered listener that can be used with remove_listener.
|
2014-11-29 07:19:59 +00:00
|
|
|
"""
|
|
|
|
@ft.wraps(listener)
|
|
|
|
def onetime_listener(event):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Remove listener from eventbus and then fires listener."""
|
2015-07-26 08:45:49 +00:00
|
|
|
if hasattr(onetime_listener, 'run'):
|
|
|
|
return
|
|
|
|
# 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
|
2014-11-29 07:19:59 +00:00
|
|
|
|
2015-07-26 08:45:49 +00:00
|
|
|
self.remove_listener(event_type, onetime_listener)
|
2014-11-29 07:19:59 +00:00
|
|
|
|
2015-07-26 08:45:49 +00:00
|
|
|
listener(event)
|
2014-11-29 07:19:59 +00:00
|
|
|
|
|
|
|
self.listen(event_type, onetime_listener)
|
|
|
|
|
2015-07-26 08:45:49 +00:00
|
|
|
return onetime_listener
|
|
|
|
|
2014-04-24 07:40:45 +00:00
|
|
|
def remove_listener(self, event_type, listener):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Remove a listener of a specific event_type."""
|
2014-04-24 07:40:45 +00:00
|
|
|
with self._lock:
|
2014-01-20 05:39:57 +00:00
|
|
|
try:
|
2014-04-24 07:40:45 +00:00
|
|
|
self._listeners[event_type].remove(listener)
|
2013-10-23 23:29:33 +00:00
|
|
|
|
2014-01-20 05:39:57 +00:00
|
|
|
# delete event_type list if empty
|
2014-04-24 07:40:45 +00:00
|
|
|
if not self._listeners[event_type]:
|
|
|
|
self._listeners.pop(event_type)
|
2013-10-23 23:29:33 +00:00
|
|
|
|
2014-11-23 06:37:53 +00:00
|
|
|
except (KeyError, ValueError):
|
2014-01-27 02:44:36 +00:00
|
|
|
# KeyError is key event_type listener did not exist
|
2014-11-23 06:37:53 +00:00
|
|
|
# ValueError if listener did not exist within event_type
|
2014-01-20 05:39:57 +00:00
|
|
|
pass
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2013-11-11 00:46:48 +00:00
|
|
|
|
2014-01-20 03:10:40 +00:00
|
|
|
class State(object):
|
2015-01-02 16:48:20 +00:00
|
|
|
"""
|
|
|
|
Object to represent a state within the state machine.
|
|
|
|
|
|
|
|
entity_id: the entity that is represented.
|
|
|
|
state: the state of the entity
|
|
|
|
attributes: extra information on entity and state
|
|
|
|
last_changed: last time the state was changed, not the attributes.
|
2015-01-19 08:00:01 +00:00
|
|
|
last_updated: last time this object was updated.
|
2015-01-02 16:48:20 +00:00
|
|
|
"""
|
2014-01-20 03:10:40 +00:00
|
|
|
|
2015-01-19 08:00:01 +00:00
|
|
|
__slots__ = ['entity_id', 'state', 'attributes',
|
|
|
|
'last_changed', 'last_updated']
|
2014-01-23 03:40:19 +00:00
|
|
|
|
2015-04-01 14:18:03 +00:00
|
|
|
# pylint: disable=too-many-arguments
|
2015-04-01 06:08:38 +00:00
|
|
|
def __init__(self, entity_id, state, attributes=None, last_changed=None,
|
|
|
|
last_updated=None):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Initialize a new state."""
|
2016-01-24 06:37:15 +00:00
|
|
|
if not valid_entity_id(entity_id):
|
2014-11-05 03:59:22 +00:00
|
|
|
raise InvalidEntityFormatError((
|
|
|
|
"Invalid entity id encountered: {}. "
|
2015-01-02 16:48:20 +00:00
|
|
|
"Format should be <domain>.<object_id>").format(entity_id))
|
2014-11-05 03:59:22 +00:00
|
|
|
|
2015-02-06 08:00:39 +00:00
|
|
|
self.entity_id = entity_id.lower()
|
2014-01-20 03:10:40 +00:00
|
|
|
self.state = state
|
|
|
|
self.attributes = attributes or {}
|
2015-12-06 17:12:19 +00:00
|
|
|
self.last_updated = dt_util.strip_microseconds(
|
|
|
|
last_updated or dt_util.utcnow())
|
2014-01-20 03:10:40 +00:00
|
|
|
|
|
|
|
# Strip microsecond from last_changed else we cannot guarantee
|
2014-01-23 03:40:19 +00:00
|
|
|
# state == State.from_dict(state.as_dict())
|
|
|
|
# This behavior occurs because to_dict uses datetime_to_str
|
2014-12-14 08:32:20 +00:00
|
|
|
# which does not preserve microseconds
|
2015-12-06 17:12:19 +00:00
|
|
|
self.last_changed = dt_util.strip_microseconds(
|
2015-01-19 08:00:01 +00:00
|
|
|
last_changed or self.last_updated)
|
2014-01-20 03:10:40 +00:00
|
|
|
|
2015-03-17 06:32:18 +00:00
|
|
|
@property
|
|
|
|
def domain(self):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Domain of this state."""
|
2016-01-24 06:49:49 +00:00
|
|
|
return split_entity_id(self.entity_id)[0]
|
2015-03-17 06:32:18 +00:00
|
|
|
|
2015-03-29 21:39:47 +00:00
|
|
|
@property
|
|
|
|
def object_id(self):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Object id of this state."""
|
2016-01-24 06:49:49 +00:00
|
|
|
return split_entity_id(self.entity_id)[1]
|
2015-03-29 21:39:47 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def name(self):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Name of this state."""
|
2015-03-29 21:39:47 +00:00
|
|
|
return (
|
|
|
|
self.attributes.get(ATTR_FRIENDLY_NAME) or
|
|
|
|
self.object_id.replace('_', ' '))
|
|
|
|
|
2014-01-20 07:37:40 +00:00
|
|
|
def copy(self):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Return a copy of the state."""
|
2014-01-23 03:40:19 +00:00
|
|
|
return State(self.entity_id, self.state,
|
2015-12-06 17:09:18 +00:00
|
|
|
dict(self.attributes), self.last_changed,
|
|
|
|
self.last_updated)
|
2014-01-20 07:37:40 +00:00
|
|
|
|
2014-01-23 03:40:19 +00:00
|
|
|
def as_dict(self):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Return a dict representation of the State.
|
2014-01-20 03:10:40 +00:00
|
|
|
|
2015-12-28 05:14:35 +00:00
|
|
|
To be used for JSON serialization.
|
|
|
|
Ensures: state == State.from_dict(state.as_dict())
|
|
|
|
"""
|
2014-01-23 03:40:19 +00:00
|
|
|
return {'entity_id': self.entity_id,
|
|
|
|
'state': self.state,
|
|
|
|
'attributes': self.attributes,
|
2015-12-06 17:12:19 +00:00
|
|
|
'last_changed': dt_util.datetime_to_str(self.last_changed),
|
|
|
|
'last_updated': dt_util.datetime_to_str(self.last_updated)}
|
2014-01-20 03:10:40 +00:00
|
|
|
|
2014-04-15 06:48:00 +00:00
|
|
|
@classmethod
|
|
|
|
def from_dict(cls, json_dict):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Initialize a state from a dict.
|
2014-01-20 03:10:40 +00:00
|
|
|
|
2015-12-28 05:14:35 +00:00
|
|
|
Ensures: state == State.from_json_dict(state.to_json_dict())
|
|
|
|
"""
|
|
|
|
if not (json_dict and 'entity_id' in json_dict and
|
2014-04-29 07:30:31 +00:00
|
|
|
'state' in json_dict):
|
2014-04-15 06:48:00 +00:00
|
|
|
return None
|
2014-01-20 03:10:40 +00:00
|
|
|
|
2014-04-15 06:48:00 +00:00
|
|
|
last_changed = json_dict.get('last_changed')
|
2014-01-20 03:10:40 +00:00
|
|
|
|
2014-04-15 06:48:00 +00:00
|
|
|
if last_changed:
|
2015-12-06 17:12:19 +00:00
|
|
|
last_changed = dt_util.str_to_datetime(last_changed)
|
2014-04-15 06:48:00 +00:00
|
|
|
|
2015-04-01 06:08:38 +00:00
|
|
|
last_updated = json_dict.get('last_updated')
|
|
|
|
|
|
|
|
if last_updated:
|
2015-12-06 17:12:19 +00:00
|
|
|
last_updated = dt_util.str_to_datetime(last_updated)
|
2015-04-01 06:08:38 +00:00
|
|
|
|
2014-04-15 06:48:00 +00:00
|
|
|
return cls(json_dict['entity_id'], json_dict['state'],
|
2015-04-01 06:08:38 +00:00
|
|
|
json_dict.get('attributes'), last_changed, last_updated)
|
2014-01-20 03:10:40 +00:00
|
|
|
|
2014-04-24 07:40:45 +00:00
|
|
|
def __eq__(self, other):
|
|
|
|
return (self.__class__ == other.__class__ and
|
2015-01-02 16:48:20 +00:00
|
|
|
self.entity_id == other.entity_id and
|
2014-04-24 07:40:45 +00:00
|
|
|
self.state == other.state and
|
|
|
|
self.attributes == other.attributes)
|
|
|
|
|
2014-01-20 03:10:40 +00:00
|
|
|
def __repr__(self):
|
2015-01-02 16:48:20 +00:00
|
|
|
attr = "; {}".format(util.repr_helper(self.attributes)) \
|
|
|
|
if self.attributes else ""
|
|
|
|
|
|
|
|
return "<state {}={}{} @ {}>".format(
|
|
|
|
self.entity_id, self.state, attr,
|
2015-12-06 17:12:19 +00:00
|
|
|
dt_util.datetime_to_local_str(self.last_changed))
|
2014-01-20 03:10:40 +00:00
|
|
|
|
|
|
|
|
2013-09-30 07:20:27 +00:00
|
|
|
class StateMachine(object):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Helper class that tracks the state of different entities."""
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2013-11-20 07:48:08 +00:00
|
|
|
def __init__(self, bus):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Initialize state machine."""
|
2015-02-06 08:17:30 +00:00
|
|
|
self._states = {}
|
2014-04-24 07:40:45 +00:00
|
|
|
self._bus = bus
|
|
|
|
self._lock = threading.Lock()
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2014-11-29 07:19:59 +00:00
|
|
|
def entity_ids(self, domain_filter=None):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""List of entity ids that are being tracked."""
|
2015-07-26 08:45:49 +00:00
|
|
|
if domain_filter is None:
|
2014-11-29 07:19:59 +00:00
|
|
|
return list(self._states.keys())
|
2014-04-15 06:48:00 +00:00
|
|
|
|
2015-07-26 08:45:49 +00:00
|
|
|
domain_filter = domain_filter.lower()
|
|
|
|
|
2015-09-29 06:13:13 +00:00
|
|
|
return [state.entity_id for state in self._states.values()
|
|
|
|
if state.domain == domain_filter]
|
2015-07-26 08:45:49 +00:00
|
|
|
|
2014-04-29 07:30:31 +00:00
|
|
|
def all(self):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Create a list of all states."""
|
2015-07-26 08:45:49 +00:00
|
|
|
with self._lock:
|
|
|
|
return [state.copy() for state in self._states.values()]
|
2014-04-29 07:30:31 +00:00
|
|
|
|
2014-04-24 07:40:45 +00:00
|
|
|
def get(self, entity_id):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Retrieve state of entity_id or None if not found."""
|
2015-02-06 08:17:30 +00:00
|
|
|
state = self._states.get(entity_id.lower())
|
2014-04-15 06:48:00 +00:00
|
|
|
|
|
|
|
# Make a copy so people won't mutate the state
|
|
|
|
return state.copy() if state else None
|
|
|
|
|
|
|
|
def is_state(self, entity_id, state):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Test if entity exists and is specified state."""
|
2015-02-06 08:17:30 +00:00
|
|
|
entity_id = entity_id.lower()
|
|
|
|
|
2014-04-24 07:40:45 +00:00
|
|
|
return (entity_id in self._states and
|
|
|
|
self._states[entity_id].state == state)
|
2013-10-23 23:08:28 +00:00
|
|
|
|
2015-12-31 20:58:18 +00:00
|
|
|
def is_state_attr(self, entity_id, name, value):
|
|
|
|
"""Test if entity exists and has a state attribute set to value."""
|
|
|
|
entity_id = entity_id.lower()
|
|
|
|
|
|
|
|
return (entity_id in self._states and
|
|
|
|
self._states[entity_id].attributes.get(name, None) == value)
|
|
|
|
|
2014-04-24 07:40:45 +00:00
|
|
|
def remove(self, entity_id):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Remove the state of an entity.
|
2013-11-19 06:45:19 +00:00
|
|
|
|
2015-12-28 05:14:35 +00:00
|
|
|
Returns boolean to indicate if an entity was removed.
|
|
|
|
"""
|
2015-02-06 08:17:30 +00:00
|
|
|
entity_id = entity_id.lower()
|
|
|
|
|
2014-04-24 07:40:45 +00:00
|
|
|
with self._lock:
|
|
|
|
return self._states.pop(entity_id, None) is not None
|
2013-11-19 06:45:19 +00:00
|
|
|
|
2014-04-24 07:40:45 +00:00
|
|
|
def set(self, entity_id, new_state, attributes=None):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Set the state of an entity, add entity if it does not exist.
|
2013-10-24 06:57:08 +00:00
|
|
|
|
2015-01-02 16:48:20 +00:00
|
|
|
Attributes is an optional dict to specify attributes of this state.
|
|
|
|
|
|
|
|
If you just update the attributes and not the state, last changed will
|
|
|
|
not be affected.
|
|
|
|
"""
|
2015-02-06 08:17:30 +00:00
|
|
|
entity_id = entity_id.lower()
|
2015-01-13 07:31:31 +00:00
|
|
|
new_state = str(new_state)
|
2013-10-24 06:57:08 +00:00
|
|
|
attributes = attributes or {}
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2014-04-24 07:40:45 +00:00
|
|
|
with self._lock:
|
2014-04-29 07:30:31 +00:00
|
|
|
old_state = self._states.get(entity_id)
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2015-01-02 16:48:20 +00:00
|
|
|
is_existing = old_state is not None
|
|
|
|
same_state = is_existing and old_state.state == new_state
|
|
|
|
same_attr = is_existing and old_state.attributes == attributes
|
|
|
|
|
2015-07-26 08:45:49 +00:00
|
|
|
if same_state and same_attr:
|
|
|
|
return
|
|
|
|
|
2014-04-29 07:30:31 +00:00
|
|
|
# If state did not exist or is different, set it
|
2015-07-26 08:45:49 +00:00
|
|
|
last_changed = old_state.last_changed if same_state else None
|
2013-10-24 06:57:08 +00:00
|
|
|
|
2015-07-26 08:45:49 +00:00
|
|
|
state = State(entity_id, new_state, attributes, last_changed)
|
|
|
|
self._states[entity_id] = state
|
2014-01-23 03:40:19 +00:00
|
|
|
|
2015-07-26 08:45:49 +00:00
|
|
|
event_data = {'entity_id': entity_id, 'new_state': state}
|
2014-01-21 06:58:23 +00:00
|
|
|
|
2015-07-26 08:45:49 +00:00
|
|
|
if old_state:
|
|
|
|
event_data['old_state'] = old_state
|
2014-04-29 07:30:31 +00:00
|
|
|
|
2015-07-26 08:45:49 +00:00
|
|
|
self._bus.fire(EVENT_STATE_CHANGED, event_data)
|
2014-04-24 07:40:45 +00:00
|
|
|
|
2014-12-01 02:42:52 +00:00
|
|
|
def track_change(self, entity_ids, action, from_state=None, to_state=None):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""DEPRECATED AS OF 8/4/2015."""
|
2015-07-26 08:45:49 +00:00
|
|
|
_LOGGER.warning(
|
|
|
|
'hass.states.track_change is deprecated. '
|
|
|
|
'Use homeassistant.helpers.event.track_state_change instead.')
|
|
|
|
import homeassistant.helpers.event as helper
|
|
|
|
helper.track_state_change(_MockHA(self._bus), entity_ids, action,
|
|
|
|
from_state, to_state)
|
2014-12-03 05:53:00 +00:00
|
|
|
|
2014-04-24 07:40:45 +00:00
|
|
|
|
2015-09-27 06:17:04 +00:00
|
|
|
# pylint: disable=too-few-public-methods
|
|
|
|
class Service(object):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Represents a callable service."""
|
2015-09-27 06:17:04 +00:00
|
|
|
|
|
|
|
__slots__ = ['func', 'description', 'fields']
|
|
|
|
|
|
|
|
def __init__(self, func, description, fields):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Initialize a service."""
|
2015-09-27 06:17:04 +00:00
|
|
|
self.func = func
|
|
|
|
self.description = description or ''
|
|
|
|
self.fields = fields or {}
|
|
|
|
|
|
|
|
def as_dict(self):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Return dictionary representation of this service."""
|
2015-09-27 06:17:04 +00:00
|
|
|
return {
|
|
|
|
'description': self.description,
|
|
|
|
'fields': self.fields,
|
|
|
|
}
|
|
|
|
|
|
|
|
def __call__(self, call):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Execute the service."""
|
2015-09-27 06:17:04 +00:00
|
|
|
self.func(call)
|
|
|
|
|
|
|
|
|
2014-04-24 07:40:45 +00:00
|
|
|
# pylint: disable=too-few-public-methods
|
|
|
|
class ServiceCall(object):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Represents a call to a service."""
|
2014-04-24 07:40:45 +00:00
|
|
|
|
|
|
|
__slots__ = ['domain', 'service', 'data']
|
|
|
|
|
|
|
|
def __init__(self, domain, service, data=None):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Initialize a service call."""
|
2014-04-24 07:40:45 +00:00
|
|
|
self.domain = domain
|
|
|
|
self.service = service
|
|
|
|
self.data = data or {}
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
if self.data:
|
|
|
|
return "<ServiceCall {}.{}: {}>".format(
|
|
|
|
self.domain, self.service, util.repr_helper(self.data))
|
|
|
|
else:
|
|
|
|
return "<ServiceCall {}.{}>".format(self.domain, self.service)
|
|
|
|
|
|
|
|
|
|
|
|
class ServiceRegistry(object):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Offers services over the eventbus."""
|
2014-04-24 07:40:45 +00:00
|
|
|
|
|
|
|
def __init__(self, bus, pool=None):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Initialize a service registry."""
|
2014-04-24 07:40:45 +00:00
|
|
|
self._services = {}
|
|
|
|
self._lock = threading.Lock()
|
2014-04-29 07:30:31 +00:00
|
|
|
self._pool = pool or create_worker_pool()
|
2014-12-01 02:42:52 +00:00
|
|
|
self._bus = bus
|
2014-12-14 06:40:00 +00:00
|
|
|
self._cur_id = 0
|
2014-04-24 07:40:45 +00:00
|
|
|
bus.listen(EVENT_CALL_SERVICE, self._event_to_service_call)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def services(self):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Dict with per domain a list of available services."""
|
2014-04-24 07:40:45 +00:00
|
|
|
with self._lock:
|
2015-09-27 06:17:04 +00:00
|
|
|
return {domain: {key: value.as_dict() for key, value
|
|
|
|
in self._services[domain].items()}
|
2014-04-24 07:40:45 +00:00
|
|
|
for domain in self._services}
|
|
|
|
|
|
|
|
def has_service(self, domain, service):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Test if specified service exists."""
|
2014-04-24 07:40:45 +00:00
|
|
|
return service in self._services.get(domain, [])
|
|
|
|
|
2015-09-27 06:17:04 +00:00
|
|
|
def register(self, domain, service, service_func, description=None):
|
|
|
|
"""
|
|
|
|
Register a service.
|
|
|
|
|
|
|
|
Description is a dict containing key 'description' to describe
|
|
|
|
the service and a key 'fields' to describe the fields.
|
|
|
|
"""
|
|
|
|
description = description or {}
|
|
|
|
service_obj = Service(service_func, description.get('description'),
|
|
|
|
description.get('fields', {}))
|
2014-04-24 07:40:45 +00:00
|
|
|
with self._lock:
|
|
|
|
if domain in self._services:
|
2015-09-27 06:17:04 +00:00
|
|
|
self._services[domain][service] = service_obj
|
2014-04-24 07:40:45 +00:00
|
|
|
else:
|
2015-09-27 06:17:04 +00:00
|
|
|
self._services[domain] = {service: service_obj}
|
2014-04-24 07:40:45 +00:00
|
|
|
|
2015-02-14 06:49:56 +00:00
|
|
|
self._bus.fire(
|
|
|
|
EVENT_SERVICE_REGISTERED,
|
|
|
|
{ATTR_DOMAIN: domain, ATTR_SERVICE: service})
|
|
|
|
|
2014-12-14 06:40:00 +00:00
|
|
|
def call(self, domain, service, service_data=None, blocking=False):
|
2014-12-01 02:42:52 +00:00
|
|
|
"""
|
2015-12-28 05:14:35 +00:00
|
|
|
Call a service.
|
|
|
|
|
2014-12-14 06:40:00 +00:00
|
|
|
Specify blocking=True to wait till service is executed.
|
|
|
|
Waits a maximum of SERVICE_CALL_LIMIT.
|
|
|
|
|
|
|
|
If blocking = True, will return boolean if service executed
|
|
|
|
succesfully within SERVICE_CALL_LIMIT.
|
2014-12-01 02:42:52 +00:00
|
|
|
|
|
|
|
This method will fire an event to call the service.
|
|
|
|
This event will be picked up by this ServiceRegistry and any
|
|
|
|
other ServiceRegistry that is listening on the EventBus.
|
|
|
|
|
|
|
|
Because the service is sent as an event you are not allowed to use
|
|
|
|
the keys ATTR_DOMAIN and ATTR_SERVICE in your service_data.
|
|
|
|
"""
|
2014-12-14 06:40:00 +00:00
|
|
|
call_id = self._generate_unique_id()
|
2014-12-01 02:42:52 +00:00
|
|
|
event_data = service_data or {}
|
|
|
|
event_data[ATTR_DOMAIN] = domain
|
|
|
|
event_data[ATTR_SERVICE] = service
|
2014-12-14 06:40:00 +00:00
|
|
|
event_data[ATTR_SERVICE_CALL_ID] = call_id
|
|
|
|
|
|
|
|
if blocking:
|
|
|
|
executed_event = threading.Event()
|
|
|
|
|
|
|
|
def service_executed(call):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Callback method that is called when service is executed."""
|
2014-12-14 06:40:00 +00:00
|
|
|
if call.data[ATTR_SERVICE_CALL_ID] == call_id:
|
|
|
|
executed_event.set()
|
|
|
|
|
|
|
|
self._bus.listen(EVENT_SERVICE_EXECUTED, service_executed)
|
2014-12-01 02:42:52 +00:00
|
|
|
|
|
|
|
self._bus.fire(EVENT_CALL_SERVICE, event_data)
|
|
|
|
|
2014-12-14 06:40:00 +00:00
|
|
|
if blocking:
|
2015-08-04 16:13:55 +00:00
|
|
|
success = executed_event.wait(SERVICE_CALL_LIMIT)
|
|
|
|
self._bus.remove_listener(
|
|
|
|
EVENT_SERVICE_EXECUTED, service_executed)
|
|
|
|
return success
|
2014-12-14 06:40:00 +00:00
|
|
|
|
2014-04-24 07:40:45 +00:00
|
|
|
def _event_to_service_call(self, event):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Callback for SERVICE_CALLED events from the event bus."""
|
2014-04-24 07:40:45 +00:00
|
|
|
service_data = dict(event.data)
|
|
|
|
domain = service_data.pop(ATTR_DOMAIN, None)
|
|
|
|
service = service_data.pop(ATTR_SERVICE, None)
|
|
|
|
|
2015-07-26 08:45:49 +00:00
|
|
|
if not self.has_service(domain, service):
|
|
|
|
return
|
|
|
|
|
|
|
|
service_handler = self._services[domain][service]
|
|
|
|
service_call = ServiceCall(domain, service, service_data)
|
2014-04-24 07:40:45 +00:00
|
|
|
|
2015-07-26 08:45:49 +00:00
|
|
|
# Add a job to the pool that calls _execute_service
|
|
|
|
self._pool.add_job(JobPriority.EVENT_SERVICE,
|
|
|
|
(self._execute_service,
|
|
|
|
(service_handler, service_call)))
|
2014-12-14 06:40:00 +00:00
|
|
|
|
|
|
|
def _execute_service(self, service_and_call):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Execute a service and fires a SERVICE_EXECUTED event."""
|
2014-12-14 06:40:00 +00:00
|
|
|
service, call = service_and_call
|
|
|
|
service(call)
|
|
|
|
|
2015-08-11 06:34:58 +00:00
|
|
|
if ATTR_SERVICE_CALL_ID in call.data:
|
|
|
|
self._bus.fire(
|
|
|
|
EVENT_SERVICE_EXECUTED,
|
|
|
|
{ATTR_SERVICE_CALL_ID: call.data[ATTR_SERVICE_CALL_ID]})
|
2014-12-14 06:40:00 +00:00
|
|
|
|
|
|
|
def _generate_unique_id(self):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Generate a unique service call id."""
|
2014-12-14 06:40:00 +00:00
|
|
|
self._cur_id += 1
|
|
|
|
return "{}-{}".format(id(self), self._cur_id)
|
2013-10-26 21:26:58 +00:00
|
|
|
|
2013-11-11 00:46:48 +00:00
|
|
|
|
2015-03-19 06:02:58 +00:00
|
|
|
class Config(object):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Configuration settings for Home Assistant."""
|
2015-03-22 04:10:46 +00:00
|
|
|
|
|
|
|
# pylint: disable=too-many-instance-attributes
|
2015-03-19 06:02:58 +00:00
|
|
|
def __init__(self):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Initialize a new config object."""
|
2015-03-19 06:02:58 +00:00
|
|
|
self.latitude = None
|
|
|
|
self.longitude = None
|
|
|
|
self.temperature_unit = None
|
|
|
|
self.location_name = None
|
|
|
|
self.time_zone = None
|
|
|
|
|
2015-09-04 21:50:57 +00:00
|
|
|
# If True, pip install is skipped for requirements on startup
|
|
|
|
self.skip_pip = False
|
|
|
|
|
2015-03-22 04:10:46 +00:00
|
|
|
# List of loaded components
|
|
|
|
self.components = []
|
|
|
|
|
|
|
|
# Remote.API object pointing at local API
|
|
|
|
self.api = None
|
|
|
|
|
2015-03-19 06:02:58 +00:00
|
|
|
# Directory that holds the configuration
|
2015-08-30 01:11:24 +00:00
|
|
|
self.config_dir = get_default_config_dir()
|
|
|
|
|
2015-09-20 16:35:03 +00:00
|
|
|
def distance(self, lat, lon):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Calculate distance from Home Assistant in meters."""
|
2015-09-20 16:35:03 +00:00
|
|
|
return location.distance(self.latitude, self.longitude, lat, lon)
|
|
|
|
|
2015-05-11 06:05:02 +00:00
|
|
|
def path(self, *path):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Generate path to the file within the config dir."""
|
2015-05-11 06:05:02 +00:00
|
|
|
return os.path.join(self.config_dir, *path)
|
2015-03-19 19:27:56 +00:00
|
|
|
|
2015-03-19 06:02:58 +00:00
|
|
|
def temperature(self, value, unit):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Convert temperature to user preferred unit if set."""
|
2015-08-04 16:13:55 +00:00
|
|
|
if not (unit in (TEMP_CELCIUS, TEMP_FAHRENHEIT) and
|
|
|
|
self.temperature_unit and unit != self.temperature_unit):
|
2015-03-19 06:02:58 +00:00
|
|
|
return value, unit
|
|
|
|
|
|
|
|
try:
|
2015-08-17 05:06:01 +00:00
|
|
|
temp = float(value)
|
|
|
|
except ValueError: # Could not convert value to float
|
2015-03-19 06:02:58 +00:00
|
|
|
return value, unit
|
|
|
|
|
2015-08-17 05:06:01 +00:00
|
|
|
return (
|
|
|
|
round(temp_helper.convert(temp, unit, self.temperature_unit), 1),
|
|
|
|
self.temperature_unit)
|
|
|
|
|
2015-05-02 01:24:32 +00:00
|
|
|
def as_dict(self):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Create a dict representation of this dict."""
|
2015-12-06 17:12:19 +00:00
|
|
|
time_zone = self.time_zone or dt_util.UTC
|
2015-05-16 06:28:11 +00:00
|
|
|
|
2015-05-02 01:24:32 +00:00
|
|
|
return {
|
|
|
|
'latitude': self.latitude,
|
|
|
|
'longitude': self.longitude,
|
|
|
|
'temperature_unit': self.temperature_unit,
|
|
|
|
'location_name': self.location_name,
|
2015-05-16 06:28:11 +00:00
|
|
|
'time_zone': time_zone.zone,
|
2015-05-02 01:24:32 +00:00
|
|
|
'components': self.components,
|
2015-10-26 04:00:22 +00:00
|
|
|
'version': __version__
|
2015-05-02 01:24:32 +00:00
|
|
|
}
|
|
|
|
|
2015-03-19 06:02:58 +00:00
|
|
|
|
2015-07-26 08:45:49 +00:00
|
|
|
def create_timer(hass, interval=TIMER_INTERVAL):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Create a timer that will start on HOMEASSISTANT_START."""
|
2015-07-26 08:45:49 +00: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 % interval == 0, "60 % TIMER_INTERVAL should be 0!"
|
|
|
|
|
|
|
|
def timer():
|
|
|
|
"""Send an EVENT_TIME_CHANGED on interval."""
|
|
|
|
stop_event = threading.Event()
|
|
|
|
|
|
|
|
def stop_timer(event):
|
|
|
|
"""Stop the timer."""
|
|
|
|
stop_event.set()
|
|
|
|
|
|
|
|
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_timer)
|
|
|
|
|
|
|
|
_LOGGER.info("Timer:starting")
|
|
|
|
|
|
|
|
last_fired_on_second = -1
|
|
|
|
|
2015-12-06 17:12:19 +00:00
|
|
|
calc_now = dt_util.utcnow
|
2015-07-26 08:45:49 +00:00
|
|
|
|
|
|
|
while not stop_event.isSet():
|
|
|
|
now = calc_now()
|
|
|
|
|
|
|
|
# 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 % interval or \
|
|
|
|
now.second == last_fired_on_second:
|
|
|
|
|
|
|
|
# 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 = interval - now.second % interval + \
|
|
|
|
.5 - now.microsecond/1000000.0
|
|
|
|
|
|
|
|
time.sleep(slp_seconds)
|
|
|
|
|
|
|
|
now = calc_now()
|
|
|
|
|
|
|
|
last_fired_on_second = now.second
|
|
|
|
|
|
|
|
# Event might have been set while sleeping
|
|
|
|
if not stop_event.isSet():
|
|
|
|
try:
|
|
|
|
hass.bus.fire(EVENT_TIME_CHANGED, {ATTR_NOW: now})
|
|
|
|
except HomeAssistantError:
|
|
|
|
# HA raises error if firing event after it has shut down
|
|
|
|
break
|
|
|
|
|
|
|
|
def start_timer(event):
|
|
|
|
"""Start the timer."""
|
|
|
|
thread = threading.Thread(target=timer)
|
|
|
|
thread.daemon = True
|
|
|
|
thread.start()
|
|
|
|
|
|
|
|
hass.bus.listen_once(EVENT_HOMEASSISTANT_START, start_timer)
|
|
|
|
|
|
|
|
|
2015-09-01 07:18:26 +00:00
|
|
|
def create_worker_pool(worker_count=None):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Create a worker pool."""
|
2015-09-01 07:18:26 +00:00
|
|
|
if worker_count is None:
|
|
|
|
worker_count = MIN_WORKER_THREAD
|
2015-07-26 08:45:49 +00:00
|
|
|
|
|
|
|
def job_handler(job):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Called whenever a job is available to do."""
|
2015-07-26 08:45:49 +00:00
|
|
|
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
|
|
|
|
_LOGGER.exception("BusHandler:Exception doing job")
|
|
|
|
|
|
|
|
def busy_callback(worker_count, current_jobs, pending_jobs_count):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Callback to be called when the pool queue gets too big."""
|
2015-07-26 08:45:49 +00:00
|
|
|
_LOGGER.warning(
|
|
|
|
"WorkerPool:All %d threads are busy and %d jobs pending",
|
|
|
|
worker_count, pending_jobs_count)
|
|
|
|
|
|
|
|
for start, job in current_jobs:
|
|
|
|
_LOGGER.warning("WorkerPool:Current job from %s: %s",
|
2015-12-06 17:12:19 +00:00
|
|
|
dt_util.datetime_to_local_str(start), job)
|
2015-07-26 08:45:49 +00:00
|
|
|
|
2015-08-04 16:13:55 +00:00
|
|
|
return util.ThreadPool(job_handler, worker_count, busy_callback)
|