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
|
|
|
"""
|
2016-09-13 02:16:14 +00:00
|
|
|
# pylint: disable=unused-import, too-many-lines
|
|
|
|
import asyncio
|
2016-09-18 01:28:01 +00:00
|
|
|
from concurrent.futures import ThreadPoolExecutor
|
2016-02-19 05:27:50 +00:00
|
|
|
import enum
|
2013-09-30 07:20:27 +00:00
|
|
|
import logging
|
2016-02-19 05:27:50 +00:00
|
|
|
import os
|
2017-06-25 22:10:30 +00:00
|
|
|
import pathlib
|
2016-08-09 03:21:40 +00:00
|
|
|
import re
|
2016-09-13 02:16:14 +00:00
|
|
|
import sys
|
2016-09-18 01:28:01 +00:00
|
|
|
import threading
|
2017-02-10 17:00:17 +00:00
|
|
|
from time import monotonic
|
2016-09-13 02:16:14 +00:00
|
|
|
|
2016-02-10 07:27:01 +00:00
|
|
|
from types import MappingProxyType
|
2018-05-12 21:44:53 +00:00
|
|
|
from typing import Optional, Any, Callable, List, TypeVar, Dict # NOQA
|
2016-08-07 23:26:35 +00:00
|
|
|
|
2017-04-08 21:53:32 +00:00
|
|
|
from async_timeout import timeout
|
2016-03-31 18:36:59 +00:00
|
|
|
import voluptuous as vol
|
2016-08-10 03:58:08 +00:00
|
|
|
from voluptuous.humanize import humanize_error
|
2016-03-31 18:36:59 +00:00
|
|
|
|
2016-02-19 05:27:50 +00:00
|
|
|
from homeassistant.const import (
|
|
|
|
ATTR_DOMAIN, ATTR_FRIENDLY_NAME, ATTR_NOW, ATTR_SERVICE,
|
|
|
|
ATTR_SERVICE_CALL_ID, ATTR_SERVICE_DATA, EVENT_CALL_SERVICE,
|
|
|
|
EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP,
|
|
|
|
EVENT_SERVICE_EXECUTED, EVENT_SERVICE_REGISTERED, EVENT_STATE_CHANGED,
|
2017-03-08 06:51:34 +00:00
|
|
|
EVENT_TIME_CHANGED, MATCH_ALL, EVENT_HOMEASSISTANT_CLOSE,
|
|
|
|
EVENT_SERVICE_REMOVED, __version__)
|
2017-10-08 15:17:54 +00:00
|
|
|
from homeassistant import loader
|
2016-02-19 05:27:50 +00:00
|
|
|
from homeassistant.exceptions import (
|
2017-10-25 16:05:30 +00:00
|
|
|
HomeAssistantError, InvalidEntityFormatError, InvalidStateError)
|
2018-03-11 17:01:12 +00:00
|
|
|
from homeassistant.util.async_ import (
|
2017-04-07 04:00:58 +00:00
|
|
|
run_coroutine_threadsafe, run_callback_threadsafe,
|
|
|
|
fire_coroutine_threadsafe)
|
2016-08-09 03:21:40 +00:00
|
|
|
import homeassistant.util as util
|
|
|
|
import homeassistant.util.dt as dt_util
|
|
|
|
import homeassistant.util.location as location
|
2016-08-09 03:42:25 +00:00
|
|
|
from homeassistant.util.unit_system import UnitSystem, METRIC_SYSTEM # NOQA
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2018-05-12 21:44:53 +00:00
|
|
|
T = TypeVar('T')
|
|
|
|
|
2017-01-20 07:55:29 +00:00
|
|
|
DOMAIN = 'homeassistant'
|
2014-01-05 01:55:05 +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
|
|
|
|
|
2016-08-09 03:21:40 +00:00
|
|
|
# Pattern for validating entity IDs (format: <domain>.<entity>)
|
|
|
|
ENTITY_ID_PATTERN = re.compile(r"^(\w+)\.(\w+)$")
|
|
|
|
|
2017-04-08 21:53:32 +00:00
|
|
|
# How long to wait till things that run on startup have to finish.
|
|
|
|
TIMEOUT_EVENT_START = 15
|
2016-11-09 16:41:17 +00:00
|
|
|
|
2014-11-08 21:57:08 +00:00
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
2013-11-11 22:58:57 +00:00
|
|
|
|
2016-08-09 03:21:40 +00:00
|
|
|
def split_entity_id(entity_id: str) -> List[str]:
|
|
|
|
"""Split a state entity_id into domain, object_id."""
|
|
|
|
return entity_id.split(".", 1)
|
|
|
|
|
|
|
|
|
|
|
|
def valid_entity_id(entity_id: str) -> bool:
|
|
|
|
"""Test if an entity ID is a valid format."""
|
|
|
|
return ENTITY_ID_PATTERN.match(entity_id) is not None
|
|
|
|
|
|
|
|
|
2017-10-25 16:05:30 +00:00
|
|
|
def valid_state(state: str) -> bool:
|
2018-01-27 19:58:27 +00:00
|
|
|
"""Test if a state is valid."""
|
2017-10-25 16:05:30 +00:00
|
|
|
return len(state) < 256
|
|
|
|
|
|
|
|
|
2018-05-12 21:44:53 +00:00
|
|
|
def callback(func: Callable[..., T]) -> Callable[..., T]:
|
2016-10-05 03:44:32 +00:00
|
|
|
"""Annotation to mark method as safe to call from within the event loop."""
|
2018-05-12 21:44:53 +00:00
|
|
|
setattr(func, '_hass_callback', True)
|
2016-10-05 03:44:32 +00:00
|
|
|
return func
|
|
|
|
|
|
|
|
|
|
|
|
def is_callback(func: Callable[..., Any]) -> bool:
|
|
|
|
"""Check if function is safe to be called in the event loop."""
|
2018-05-12 21:44:53 +00:00
|
|
|
return getattr(func, '_hass_callback', False) is True
|
2016-10-05 03:44:32 +00:00
|
|
|
|
|
|
|
|
2017-02-10 17:00:17 +00:00
|
|
|
@callback
|
|
|
|
def async_loop_exception_handler(loop, context):
|
|
|
|
"""Handle all exception inside the core loop."""
|
|
|
|
kwargs = {}
|
|
|
|
exception = context.get('exception')
|
|
|
|
if exception:
|
|
|
|
kwargs['exc_info'] = (type(exception), exception,
|
|
|
|
exception.__traceback__)
|
|
|
|
|
|
|
|
_LOGGER.error("Error doing job: %s", context['message'], **kwargs)
|
|
|
|
|
|
|
|
|
2016-06-30 16:02:12 +00:00
|
|
|
class CoreState(enum.Enum):
|
|
|
|
"""Represent the current state of Home Assistant."""
|
|
|
|
|
2017-01-20 07:55:29 +00:00
|
|
|
not_running = 'NOT_RUNNING'
|
|
|
|
starting = 'STARTING'
|
|
|
|
running = 'RUNNING'
|
|
|
|
stopping = 'STOPPING'
|
2016-06-30 16:02:12 +00:00
|
|
|
|
2016-07-21 05:38:52 +00:00
|
|
|
def __str__(self) -> str:
|
2016-06-30 16:02:12 +00:00
|
|
|
"""Return the event."""
|
|
|
|
return self.value
|
|
|
|
|
|
|
|
|
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
|
|
|
|
2016-09-13 02:16:14 +00:00
|
|
|
def __init__(self, loop=None):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Initialize new Home Assistant object."""
|
2017-01-20 07:55:29 +00:00
|
|
|
if sys.platform == 'win32':
|
2016-11-02 20:53:52 +00:00
|
|
|
self.loop = loop or asyncio.ProactorEventLoop()
|
|
|
|
else:
|
|
|
|
self.loop = loop or asyncio.get_event_loop()
|
|
|
|
|
2018-03-15 11:10:54 +00:00
|
|
|
executor_opts = {'max_workers': None}
|
2017-06-09 10:38:40 +00:00
|
|
|
if sys.version_info[:2] >= (3, 6):
|
|
|
|
executor_opts['thread_name_prefix'] = 'SyncWorker'
|
|
|
|
|
|
|
|
self.executor = ThreadPoolExecutor(**executor_opts)
|
2016-10-01 22:43:33 +00:00
|
|
|
self.loop.set_default_executor(self.executor)
|
2017-02-10 17:00:17 +00:00
|
|
|
self.loop.set_exception_handler(async_loop_exception_handler)
|
2016-11-08 09:24:50 +00:00
|
|
|
self._pending_tasks = []
|
2017-04-06 06:23:02 +00:00
|
|
|
self._track_task = True
|
2016-10-18 02:38:41 +00:00
|
|
|
self.bus = EventBus(self)
|
2016-11-24 22:02:39 +00:00
|
|
|
self.services = ServiceRegistry(self)
|
2016-09-13 02:16:14 +00:00
|
|
|
self.states = StateMachine(self.bus, self.loop)
|
2016-07-31 20:24:49 +00:00
|
|
|
self.config = Config() # type: Config
|
2017-10-08 15:17:54 +00:00
|
|
|
self.components = loader.Components(self)
|
|
|
|
self.helpers = loader.Helpers(self)
|
2016-10-29 21:51:17 +00:00
|
|
|
# This is a dictionary that any component can store any data on.
|
|
|
|
self.data = {}
|
2016-06-30 16:02:12 +00:00
|
|
|
self.state = CoreState.not_running
|
2016-09-13 02:16:14 +00:00
|
|
|
self.exit_code = None
|
2018-05-12 21:44:53 +00:00
|
|
|
self.config_entries = None
|
2016-06-30 16:02:12 +00:00
|
|
|
|
|
|
|
@property
|
2016-07-21 05:38:52 +00:00
|
|
|
def is_running(self) -> bool:
|
2016-06-30 16:02:12 +00:00
|
|
|
"""Return if Home Assistant is running."""
|
2016-08-18 01:58:00 +00:00
|
|
|
return self.state in (CoreState.starting, CoreState.running)
|
2015-01-18 05:13:02 +00:00
|
|
|
|
2018-05-12 21:44:53 +00:00
|
|
|
def start(self) -> int:
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Start home assistant."""
|
2016-09-13 02:16:14 +00:00
|
|
|
# Register the async start
|
2017-04-07 04:00:58 +00:00
|
|
|
fire_coroutine_threadsafe(self.async_start(), self.loop)
|
2013-10-08 06:55:19 +00:00
|
|
|
|
2016-09-13 02:16:14 +00:00
|
|
|
# Run forever and catch keyboard interrupt
|
2016-05-20 06:20:59 +00:00
|
|
|
try:
|
2016-09-13 02:16:14 +00:00
|
|
|
# Block until stopped
|
|
|
|
_LOGGER.info("Starting Home Assistant core loop")
|
|
|
|
self.loop.run_forever()
|
2016-05-20 06:20:59 +00:00
|
|
|
except KeyboardInterrupt:
|
2017-04-07 19:02:49 +00:00
|
|
|
self.loop.call_soon_threadsafe(
|
|
|
|
self.loop.create_task, self.async_stop())
|
2016-09-13 02:16:14 +00:00
|
|
|
self.loop.run_forever()
|
2016-10-08 16:56:36 +00:00
|
|
|
finally:
|
|
|
|
self.loop.close()
|
2018-05-12 21:44:53 +00:00
|
|
|
return self.exit_code
|
2016-09-13 02:16:14 +00:00
|
|
|
|
2018-02-23 07:22:27 +00:00
|
|
|
async def async_start(self):
|
2016-09-13 02:16:14 +00:00
|
|
|
"""Finalize startup from inside the event loop.
|
|
|
|
|
|
|
|
This method is a coroutine.
|
|
|
|
"""
|
2016-10-31 15:47:29 +00:00
|
|
|
_LOGGER.info("Starting Home Assistant")
|
2016-10-29 15:57:59 +00:00
|
|
|
self.state = CoreState.starting
|
|
|
|
|
2016-10-02 22:07:23 +00:00
|
|
|
# pylint: disable=protected-access
|
|
|
|
self.loop._thread_ident = threading.get_ident()
|
2016-09-13 02:16:14 +00:00
|
|
|
self.bus.async_fire(EVENT_HOMEASSISTANT_START)
|
2017-04-08 21:53:32 +00:00
|
|
|
|
|
|
|
try:
|
2017-04-30 05:04:49 +00:00
|
|
|
# Only block for EVENT_HOMEASSISTANT_START listener
|
2017-04-11 16:09:31 +00:00
|
|
|
self.async_stop_track_tasks()
|
2017-04-08 21:53:32 +00:00
|
|
|
with timeout(TIMEOUT_EVENT_START, loop=self.loop):
|
2018-02-23 07:22:27 +00:00
|
|
|
await self.async_block_till_done()
|
2017-04-08 21:53:32 +00:00
|
|
|
except asyncio.TimeoutError:
|
|
|
|
_LOGGER.warning(
|
|
|
|
'Something is blocking Home Assistant from wrapping up the '
|
|
|
|
'start up phase. We\'re going to continue anyway. Please '
|
|
|
|
'report the following info at http://bit.ly/2ogP58T : %s',
|
|
|
|
', '.join(self.config.components))
|
|
|
|
|
2017-06-27 08:36:00 +00:00
|
|
|
# Allow automations to set up the start triggers before changing state
|
2018-02-23 07:22:27 +00:00
|
|
|
await asyncio.sleep(0, loop=self.loop)
|
2016-09-13 02:16:14 +00:00
|
|
|
self.state = CoreState.running
|
2017-04-06 06:23:02 +00:00
|
|
|
_async_create_timer(self)
|
2016-09-13 02:16:14 +00:00
|
|
|
|
2016-11-24 22:49:29 +00:00
|
|
|
def add_job(self, target: Callable[..., None], *args: Any) -> None:
|
|
|
|
"""Add job to the executor pool.
|
2016-11-09 16:41:17 +00:00
|
|
|
|
2016-11-24 22:49:29 +00:00
|
|
|
target: target to call.
|
|
|
|
args: parameters for method to call.
|
2016-11-09 16:41:17 +00:00
|
|
|
"""
|
2016-12-16 05:30:09 +00:00
|
|
|
if target is None:
|
2017-01-20 07:55:29 +00:00
|
|
|
raise ValueError("Don't call add_job with None")
|
2016-11-24 22:49:29 +00:00
|
|
|
self.loop.call_soon_threadsafe(self.async_add_job, target, *args)
|
2016-11-09 16:41:17 +00:00
|
|
|
|
2016-11-24 22:49:29 +00:00
|
|
|
@callback
|
2018-05-12 21:44:53 +00:00
|
|
|
def async_add_job(
|
|
|
|
self,
|
|
|
|
target: Callable[..., Any],
|
|
|
|
*args: Any) -> Optional[asyncio.tasks.Task]:
|
2016-09-18 01:28:01 +00:00
|
|
|
"""Add a job from within the eventloop.
|
|
|
|
|
2016-10-18 02:38:41 +00:00
|
|
|
This method must be run in the event loop.
|
|
|
|
|
2016-09-18 01:28:01 +00:00
|
|
|
target: target to call.
|
|
|
|
args: parameters for method to call.
|
|
|
|
"""
|
2016-11-05 16:27:55 +00:00
|
|
|
task = None
|
|
|
|
|
2016-11-06 17:26:40 +00:00
|
|
|
if asyncio.iscoroutine(target):
|
|
|
|
task = self.loop.create_task(target)
|
|
|
|
elif is_callback(target):
|
2016-10-05 03:44:32 +00:00
|
|
|
self.loop.call_soon(target, *args)
|
|
|
|
elif asyncio.iscoroutinefunction(target):
|
2016-11-05 16:27:55 +00:00
|
|
|
task = self.loop.create_task(target(*args))
|
2016-09-18 01:28:01 +00:00
|
|
|
else:
|
2016-11-05 16:27:55 +00:00
|
|
|
task = self.loop.run_in_executor(None, target, *args)
|
|
|
|
|
2017-09-23 15:15:46 +00:00
|
|
|
# If a task is scheduled
|
2017-03-01 04:33:19 +00:00
|
|
|
if self._track_task and task is not None:
|
2016-11-08 09:24:50 +00:00
|
|
|
self._pending_tasks.append(task)
|
|
|
|
|
2017-03-01 04:33:19 +00:00
|
|
|
return task
|
|
|
|
|
2016-11-24 22:49:29 +00:00
|
|
|
@callback
|
|
|
|
def async_track_tasks(self):
|
|
|
|
"""Track tasks so you can wait for all tasks to be done."""
|
2017-03-01 04:33:19 +00:00
|
|
|
self._track_task = True
|
2016-11-24 22:49:29 +00:00
|
|
|
|
2017-04-11 16:09:31 +00:00
|
|
|
@callback
|
2016-11-30 21:02:45 +00:00
|
|
|
def async_stop_track_tasks(self):
|
2017-04-11 16:09:31 +00:00
|
|
|
"""Stop track tasks so you can't wait for all tasks to be done."""
|
2017-03-01 04:33:19 +00:00
|
|
|
self._track_task = False
|
2016-11-30 21:02:45 +00:00
|
|
|
|
2016-10-18 02:38:41 +00:00
|
|
|
@callback
|
2016-10-31 15:47:29 +00:00
|
|
|
def async_run_job(self, target: Callable[..., None], *args: Any) -> None:
|
2016-10-05 03:44:32 +00:00
|
|
|
"""Run a job from within the event loop.
|
|
|
|
|
2016-10-18 02:38:41 +00:00
|
|
|
This method must be run in the event loop.
|
|
|
|
|
2016-10-05 03:44:32 +00:00
|
|
|
target: target to call.
|
|
|
|
args: parameters for method to call.
|
|
|
|
"""
|
2017-06-26 16:41:48 +00:00
|
|
|
if not asyncio.iscoroutine(target) and is_callback(target):
|
2016-10-05 03:44:32 +00:00
|
|
|
target(*args)
|
|
|
|
else:
|
|
|
|
self.async_add_job(target, *args)
|
|
|
|
|
2016-10-31 15:47:29 +00:00
|
|
|
def block_till_done(self) -> None:
|
2016-09-13 02:16:14 +00:00
|
|
|
"""Block till all pending work is done."""
|
2016-11-05 16:27:55 +00:00
|
|
|
run_coroutine_threadsafe(
|
|
|
|
self.async_block_till_done(), loop=self.loop).result()
|
2016-09-13 02:16:14 +00:00
|
|
|
|
2018-02-23 07:22:27 +00:00
|
|
|
async def async_block_till_done(self):
|
2016-11-05 16:27:55 +00:00
|
|
|
"""Block till all pending work is done."""
|
2016-11-24 22:49:29 +00:00
|
|
|
# To flush out any call_soon_threadsafe
|
2018-02-23 07:22:27 +00:00
|
|
|
await asyncio.sleep(0, loop=self.loop)
|
2016-11-24 22:49:29 +00:00
|
|
|
|
|
|
|
while self._pending_tasks:
|
2016-11-08 09:24:50 +00:00
|
|
|
pending = [task for task in self._pending_tasks
|
|
|
|
if not task.done()]
|
|
|
|
self._pending_tasks.clear()
|
2017-04-24 03:41:09 +00:00
|
|
|
if pending:
|
2018-02-23 07:22:27 +00:00
|
|
|
await asyncio.wait(pending, loop=self.loop)
|
2016-11-24 22:49:29 +00:00
|
|
|
else:
|
2018-02-23 07:22:27 +00:00
|
|
|
await asyncio.sleep(0, loop=self.loop)
|
2014-11-23 17:51:16 +00:00
|
|
|
|
2016-07-21 05:38:52 +00:00
|
|
|
def stop(self) -> None:
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Stop Home Assistant and shuts down all threads."""
|
2017-04-07 04:00:58 +00:00
|
|
|
fire_coroutine_threadsafe(self.async_stop(), self.loop)
|
2016-09-13 02:16:14 +00:00
|
|
|
|
2018-02-23 07:22:27 +00:00
|
|
|
async def async_stop(self, exit_code=0) -> None:
|
2016-09-13 02:16:14 +00:00
|
|
|
"""Stop Home Assistant and shuts down all threads.
|
|
|
|
|
|
|
|
This method is a coroutine.
|
|
|
|
"""
|
2017-02-13 05:24:07 +00:00
|
|
|
# stage 1
|
2016-06-30 16:02:12 +00:00
|
|
|
self.state = CoreState.stopping
|
2016-11-24 22:49:29 +00:00
|
|
|
self.async_track_tasks()
|
2016-09-13 02:16:14 +00:00
|
|
|
self.bus.async_fire(EVENT_HOMEASSISTANT_STOP)
|
2018-02-23 07:22:27 +00:00
|
|
|
await self.async_block_till_done()
|
2017-01-05 22:09:04 +00:00
|
|
|
|
2017-02-13 05:24:07 +00:00
|
|
|
# stage 2
|
|
|
|
self.state = CoreState.not_running
|
|
|
|
self.bus.async_fire(EVENT_HOMEASSISTANT_CLOSE)
|
2018-02-23 07:22:27 +00:00
|
|
|
await self.async_block_till_done()
|
2017-02-13 05:24:07 +00:00
|
|
|
self.executor.shutdown()
|
2016-12-17 20:21:52 +00:00
|
|
|
|
2017-02-08 17:17:52 +00:00
|
|
|
self.exit_code = exit_code
|
2016-09-13 02:16:14 +00:00
|
|
|
self.loop.stop()
|
2014-11-23 17:51:16 +00:00
|
|
|
|
2014-01-27 02:44:36 +00:00
|
|
|
|
2014-04-29 07:30:31 +00:00
|
|
|
class EventOrigin(enum.Enum):
|
2016-03-07 23:06:04 +00:00
|
|
|
"""Represent the origin of an event."""
|
2014-04-29 07:30:31 +00:00
|
|
|
|
2017-01-20 07:55:29 +00:00
|
|
|
local = 'LOCAL'
|
|
|
|
remote = 'REMOTE'
|
2014-04-29 07:30:31 +00:00
|
|
|
|
|
|
|
def __str__(self):
|
2016-03-07 23:06:04 +00:00
|
|
|
"""Return the event."""
|
2014-04-29 07:30:31 +00:00
|
|
|
return self.value
|
|
|
|
|
|
|
|
|
2014-01-27 02:44:36 +00:00
|
|
|
class Event(object):
|
2017-04-30 05:04:49 +00:00
|
|
|
"""Representation of 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
|
2016-04-16 07:55:35 +00:00
|
|
|
self.time_fired = 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):
|
2016-10-18 02:38:41 +00:00
|
|
|
"""Create a dict representation of this Event.
|
|
|
|
|
|
|
|
Async friendly.
|
|
|
|
"""
|
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),
|
2016-04-16 07:55:35 +00:00
|
|
|
'time_fired': self.time_fired,
|
2015-01-28 08:22:09 +00:00
|
|
|
}
|
|
|
|
|
2014-01-27 02:44:36 +00:00
|
|
|
def __repr__(self):
|
2016-03-07 23:06:04 +00:00
|
|
|
"""Return the representation."""
|
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))
|
2017-07-06 03:02:16 +00:00
|
|
|
|
|
|
|
return "<Event {}[{}]>".format(self.event_type,
|
|
|
|
str(self.origin)[0])
|
2013-11-11 00:46:48 +00:00
|
|
|
|
2015-04-30 06:21:31 +00:00
|
|
|
def __eq__(self, other):
|
2016-03-07 23:06:04 +00:00
|
|
|
"""Return the comparison."""
|
2015-04-30 06:21:31 +00:00
|
|
|
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):
|
2017-04-30 05:04:49 +00:00
|
|
|
"""Allow the firing of and listening for events."""
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2016-10-18 02:38:41 +00:00
|
|
|
def __init__(self, hass: HomeAssistant) -> None:
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Initialize a new event bus."""
|
2018-05-12 21:44:53 +00:00
|
|
|
self._listeners = {} # type: Dict[str, List[Callable]]
|
2016-10-18 02:38:41 +00:00
|
|
|
self._hass = hass
|
2016-09-13 02:16:14 +00:00
|
|
|
|
2016-10-18 02:38:41 +00:00
|
|
|
@callback
|
2016-09-13 02:16:14 +00:00
|
|
|
def async_listeners(self):
|
2017-05-02 20:47:20 +00:00
|
|
|
"""Return dictionary with events and the number of listeners.
|
2016-09-13 02:16:14 +00:00
|
|
|
|
|
|
|
This method must be run in the event loop.
|
|
|
|
"""
|
|
|
|
return {key: len(self._listeners[key])
|
|
|
|
for key in self._listeners}
|
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):
|
2017-05-02 20:47:20 +00:00
|
|
|
"""Return dictionary with events and the number of listeners."""
|
2016-09-13 02:16:14 +00:00
|
|
|
return run_callback_threadsafe(
|
2016-10-18 02:38:41 +00:00
|
|
|
self._hass.loop, self.async_listeners
|
2016-09-13 02:16:14 +00:00
|
|
|
).result()
|
2014-01-30 06:48:35 +00:00
|
|
|
|
2016-07-26 05:49:10 +00:00
|
|
|
def fire(self, event_type: str, event_data=None, origin=EventOrigin.local):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Fire an event."""
|
2017-01-20 07:55:29 +00:00
|
|
|
self._hass.loop.call_soon_threadsafe(
|
|
|
|
self.async_fire, event_type, event_data, origin)
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2016-10-18 02:38:41 +00:00
|
|
|
@callback
|
2016-09-13 02:16:14 +00:00
|
|
|
def async_fire(self, event_type: str, event_data=None,
|
2017-11-03 13:19:36 +00:00
|
|
|
origin=EventOrigin.local):
|
2016-09-13 02:16:14 +00:00
|
|
|
"""Fire an event.
|
2014-01-27 02:44:36 +00:00
|
|
|
|
2016-09-13 02:16:14 +00:00
|
|
|
This method must be run in the event loop.
|
|
|
|
"""
|
2017-02-13 05:24:07 +00:00
|
|
|
listeners = self._listeners.get(event_type, [])
|
|
|
|
|
|
|
|
# EVENT_HOMEASSISTANT_CLOSE should go only to his listeners
|
2017-11-03 13:19:36 +00:00
|
|
|
match_all_listeners = self._listeners.get(MATCH_ALL)
|
|
|
|
if (match_all_listeners is not None and
|
|
|
|
event_type != EVENT_HOMEASSISTANT_CLOSE):
|
|
|
|
listeners = match_all_listeners + listeners
|
2014-01-24 00:49:43 +00:00
|
|
|
|
2016-09-13 02:16:14 +00:00
|
|
|
event = Event(event_type, event_data, origin)
|
|
|
|
|
|
|
|
if event_type != EVENT_TIME_CHANGED:
|
|
|
|
_LOGGER.info("Bus:Handling %s", event)
|
2014-01-20 03:10:40 +00:00
|
|
|
|
2016-09-13 02:16:14 +00:00
|
|
|
if not listeners:
|
|
|
|
return
|
|
|
|
|
|
|
|
for func in listeners:
|
2016-10-18 02:38:41 +00:00
|
|
|
self._hass.async_add_job(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.
|
|
|
|
"""
|
2016-10-18 02:38:41 +00:00
|
|
|
async_remove_listener = run_callback_threadsafe(
|
|
|
|
self._hass.loop, self.async_listen, event_type, listener).result()
|
2014-01-20 03:10:40 +00:00
|
|
|
|
2016-08-26 06:25:35 +00:00
|
|
|
def remove_listener():
|
|
|
|
"""Remove the listener."""
|
2016-10-18 02:38:41 +00:00
|
|
|
run_callback_threadsafe(
|
|
|
|
self._hass.loop, async_remove_listener).result()
|
2016-08-26 06:25:35 +00:00
|
|
|
|
|
|
|
return remove_listener
|
|
|
|
|
2016-10-18 02:38:41 +00:00
|
|
|
@callback
|
2016-09-13 02:16:14 +00:00
|
|
|
def async_listen(self, event_type, listener):
|
|
|
|
"""Listen for all events or events of a specific type.
|
|
|
|
|
|
|
|
To listen to all events specify the constant ``MATCH_ALL``
|
|
|
|
as event_type.
|
|
|
|
|
|
|
|
This method must be run in the event loop.
|
|
|
|
"""
|
|
|
|
if event_type in self._listeners:
|
|
|
|
self._listeners[event_type].append(listener)
|
|
|
|
else:
|
|
|
|
self._listeners[event_type] = [listener]
|
|
|
|
|
|
|
|
def remove_listener():
|
|
|
|
"""Remove the listener."""
|
2016-10-18 02:38:41 +00:00
|
|
|
self._async_remove_listener(event_type, listener)
|
2016-09-13 02:16:14 +00:00
|
|
|
|
|
|
|
return remove_listener
|
|
|
|
|
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.
|
|
|
|
|
2016-09-07 13:59:59 +00:00
|
|
|
Returns function to unsubscribe the listener.
|
2014-11-29 07:19:59 +00:00
|
|
|
"""
|
2016-10-18 02:38:41 +00:00
|
|
|
async_remove_listener = run_callback_threadsafe(
|
|
|
|
self._hass.loop, self.async_listen_once, event_type, listener,
|
|
|
|
).result()
|
2014-11-29 07:19:59 +00:00
|
|
|
|
2016-10-18 02:38:41 +00:00
|
|
|
def remove_listener():
|
|
|
|
"""Remove the listener."""
|
|
|
|
run_callback_threadsafe(
|
|
|
|
self._hass.loop, async_remove_listener).result()
|
2014-11-29 07:19:59 +00:00
|
|
|
|
2016-09-07 13:59:59 +00:00
|
|
|
return remove_listener
|
2015-07-26 08:45:49 +00:00
|
|
|
|
2016-10-18 02:38:41 +00:00
|
|
|
@callback
|
2016-09-13 02:16:14 +00:00
|
|
|
def async_listen_once(self, event_type, listener):
|
|
|
|
"""Listen once for event of a specific type.
|
|
|
|
|
|
|
|
To listen to all events specify the constant ``MATCH_ALL``
|
|
|
|
as event_type.
|
|
|
|
|
|
|
|
Returns registered listener that can be used with remove_listener.
|
|
|
|
|
|
|
|
This method must be run in the event loop.
|
|
|
|
"""
|
2016-10-18 02:38:41 +00:00
|
|
|
@callback
|
2016-09-13 02:16:14 +00:00
|
|
|
def onetime_listener(event):
|
|
|
|
"""Remove listener from eventbus and then fire listener."""
|
|
|
|
if hasattr(onetime_listener, 'run'):
|
|
|
|
return
|
|
|
|
# Set variable so that we will never run twice.
|
|
|
|
# Because the event bus loop might have async_fire queued multiple
|
|
|
|
# times, its possible this listener may already be lined up
|
|
|
|
# multiple times as well.
|
|
|
|
# This will make sure the second time it does nothing.
|
|
|
|
setattr(onetime_listener, 'run', True)
|
2016-10-18 02:38:41 +00:00
|
|
|
self._async_remove_listener(event_type, onetime_listener)
|
|
|
|
self._hass.async_run_job(listener, event)
|
2016-09-13 02:16:14 +00:00
|
|
|
|
2016-10-18 02:38:41 +00:00
|
|
|
return self.async_listen(event_type, onetime_listener)
|
2016-09-07 13:59:59 +00:00
|
|
|
|
2016-10-18 02:38:41 +00:00
|
|
|
@callback
|
|
|
|
def _async_remove_listener(self, event_type, listener):
|
2016-09-13 02:16:14 +00:00
|
|
|
"""Remove a listener of a specific event_type.
|
|
|
|
|
|
|
|
This method must be run in the event loop.
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
self._listeners[event_type].remove(listener)
|
2013-10-23 23:29:33 +00:00
|
|
|
|
2016-09-13 02:16:14 +00:00
|
|
|
# delete event_type list if empty
|
|
|
|
if not self._listeners[event_type]:
|
|
|
|
self._listeners.pop(event_type)
|
|
|
|
except (KeyError, ValueError):
|
|
|
|
# KeyError is key event_type listener did not exist
|
|
|
|
# ValueError if listener did not exist within event_type
|
2017-01-20 07:55:29 +00:00
|
|
|
_LOGGER.warning("Unable to remove unknown listener %s", listener)
|
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):
|
2016-03-07 23:06:04 +00:00
|
|
|
"""Object to represent a state within the state machine.
|
2015-01-02 16:48:20 +00:00
|
|
|
|
|
|
|
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 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."""
|
2017-10-25 16:05:30 +00:00
|
|
|
state = str(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
|
|
|
|
2017-10-25 16:05:30 +00:00
|
|
|
if not valid_state(state):
|
|
|
|
raise InvalidStateError((
|
|
|
|
"Invalid state encountered for entity id: {}. "
|
|
|
|
"State max length is 255 characters.").format(entity_id))
|
|
|
|
|
2015-02-06 08:00:39 +00:00
|
|
|
self.entity_id = entity_id.lower()
|
2017-10-25 16:05:30 +00:00
|
|
|
self.state = state
|
2016-02-10 07:27:01 +00:00
|
|
|
self.attributes = MappingProxyType(attributes or {})
|
2016-04-16 07:55:35 +00:00
|
|
|
self.last_updated = last_updated or dt_util.utcnow()
|
|
|
|
self.last_changed = 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-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
|
|
|
|
2016-10-18 02:38:41 +00:00
|
|
|
Async friendly.
|
|
|
|
|
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,
|
2016-02-10 07:27:01 +00:00
|
|
|
'attributes': dict(self.attributes),
|
2016-04-16 07:55:35 +00:00
|
|
|
'last_changed': self.last_changed,
|
|
|
|
'last_updated': 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
|
|
|
|
2016-10-18 02:38:41 +00:00
|
|
|
Async friendly.
|
|
|
|
|
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
|
|
|
|
2016-04-16 07:55:35 +00:00
|
|
|
if isinstance(last_changed, str):
|
|
|
|
last_changed = dt_util.parse_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')
|
|
|
|
|
2016-04-16 07:55:35 +00:00
|
|
|
if isinstance(last_updated, str):
|
|
|
|
last_updated = dt_util.parse_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):
|
2016-03-07 23:06:04 +00:00
|
|
|
"""Return the comparison of the state."""
|
2014-04-24 07:40:45 +00:00
|
|
|
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):
|
2016-03-07 23:06:04 +00:00
|
|
|
"""Return the representation of the states."""
|
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,
|
2016-04-16 07:55:35 +00:00
|
|
|
dt_util.as_local(self.last_changed).isoformat())
|
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
|
|
|
|
2016-09-13 02:16:14 +00:00
|
|
|
def __init__(self, bus, loop):
|
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
|
2016-09-13 02:16:14 +00:00
|
|
|
self._loop = loop
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2014-11-29 07:19:59 +00:00
|
|
|
def entity_ids(self, domain_filter=None):
|
2016-09-13 02:16:14 +00:00
|
|
|
"""List of entity ids that are being tracked."""
|
|
|
|
future = run_callback_threadsafe(
|
|
|
|
self._loop, self.async_entity_ids, domain_filter
|
|
|
|
)
|
|
|
|
return future.result()
|
|
|
|
|
2016-10-18 02:38:41 +00:00
|
|
|
@callback
|
2016-09-13 02:16:14 +00:00
|
|
|
def async_entity_ids(self, domain_filter=None):
|
2016-10-18 02:38:41 +00:00
|
|
|
"""List of entity ids that are being tracked.
|
|
|
|
|
|
|
|
This method must be run in the event loop.
|
|
|
|
"""
|
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()
|
|
|
|
|
2016-09-13 02:16:14 +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."""
|
2016-09-13 02:16:14 +00:00
|
|
|
return run_callback_threadsafe(self._loop, self.async_all).result()
|
|
|
|
|
2016-10-18 02:38:41 +00:00
|
|
|
@callback
|
2016-09-13 02:16:14 +00:00
|
|
|
def async_all(self):
|
|
|
|
"""Create a list of all states.
|
|
|
|
|
|
|
|
This method must be run in the event loop.
|
|
|
|
"""
|
|
|
|
return list(self._states.values())
|
2014-04-29 07:30:31 +00:00
|
|
|
|
2014-04-24 07:40:45 +00:00
|
|
|
def get(self, entity_id):
|
2016-09-30 19:57:24 +00:00
|
|
|
"""Retrieve state of entity_id or None if not found.
|
|
|
|
|
|
|
|
Async friendly.
|
|
|
|
"""
|
2016-02-10 07:27:01 +00:00
|
|
|
return self._states.get(entity_id.lower())
|
2014-04-15 06:48:00 +00:00
|
|
|
|
|
|
|
def is_state(self, entity_id, state):
|
2016-09-13 02:16:14 +00:00
|
|
|
"""Test if entity exists and is specified state.
|
|
|
|
|
2016-09-30 19:57:24 +00:00
|
|
|
Async friendly.
|
2016-09-13 02:16:14 +00:00
|
|
|
"""
|
2016-09-30 19:57:24 +00:00
|
|
|
state_obj = self.get(entity_id)
|
2017-04-16 23:36:15 +00:00
|
|
|
return state_obj is not None and state_obj.state == state
|
2013-10-23 23:08:28 +00:00
|
|
|
|
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.
|
|
|
|
"""
|
2016-09-13 02:16:14 +00:00
|
|
|
return run_callback_threadsafe(
|
|
|
|
self._loop, self.async_remove, entity_id).result()
|
|
|
|
|
2016-10-18 02:38:41 +00:00
|
|
|
@callback
|
2016-09-13 02:16:14 +00:00
|
|
|
def async_remove(self, entity_id):
|
|
|
|
"""Remove the state of an entity.
|
|
|
|
|
|
|
|
Returns boolean to indicate if an entity was removed.
|
|
|
|
|
|
|
|
This method must be run in the event loop.
|
|
|
|
"""
|
2015-02-06 08:17:30 +00:00
|
|
|
entity_id = entity_id.lower()
|
2016-09-13 02:16:14 +00:00
|
|
|
old_state = self._states.pop(entity_id, None)
|
2016-02-14 06:57:40 +00:00
|
|
|
|
2016-09-13 02:16:14 +00:00
|
|
|
if old_state is None:
|
|
|
|
return False
|
2016-02-14 06:57:40 +00:00
|
|
|
|
2017-02-10 17:00:17 +00:00
|
|
|
self._bus.async_fire(EVENT_STATE_CHANGED, {
|
2016-09-13 02:16:14 +00:00
|
|
|
'entity_id': entity_id,
|
|
|
|
'old_state': old_state,
|
|
|
|
'new_state': None,
|
2017-02-10 17:00:17 +00:00
|
|
|
})
|
2016-09-13 02:16:14 +00:00
|
|
|
return True
|
2013-11-19 06:45:19 +00:00
|
|
|
|
2016-06-26 07:33:23 +00:00
|
|
|
def set(self, entity_id, new_state, attributes=None, force_update=False):
|
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.
|
|
|
|
"""
|
2016-09-13 02:16:14 +00:00
|
|
|
run_callback_threadsafe(
|
|
|
|
self._loop,
|
|
|
|
self.async_set, entity_id, new_state, attributes, force_update,
|
|
|
|
).result()
|
|
|
|
|
2016-10-18 02:38:41 +00:00
|
|
|
@callback
|
2016-09-13 02:16:14 +00:00
|
|
|
def async_set(self, entity_id, new_state, attributes=None,
|
|
|
|
force_update=False):
|
|
|
|
"""Set the state of an entity, add entity if it does not exist.
|
|
|
|
|
|
|
|
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.
|
|
|
|
|
|
|
|
This method must be run in the event loop.
|
|
|
|
"""
|
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 {}
|
2016-09-13 02:16:14 +00:00
|
|
|
old_state = self._states.get(entity_id)
|
|
|
|
is_existing = old_state is not None
|
|
|
|
same_state = (is_existing and old_state.state == new_state and
|
|
|
|
not force_update)
|
|
|
|
same_attr = is_existing and old_state.attributes == attributes
|
2015-01-02 16:48:20 +00:00
|
|
|
|
2016-09-13 02:16:14 +00:00
|
|
|
if same_state and same_attr:
|
|
|
|
return
|
2015-07-26 08:45:49 +00:00
|
|
|
|
2016-09-13 02:16:14 +00:00
|
|
|
last_changed = old_state.last_changed if same_state else None
|
|
|
|
state = State(entity_id, new_state, attributes, last_changed)
|
|
|
|
self._states[entity_id] = state
|
2017-02-10 17:00:17 +00:00
|
|
|
self._bus.async_fire(EVENT_STATE_CHANGED, {
|
2016-09-13 02:16:14 +00:00
|
|
|
'entity_id': entity_id,
|
|
|
|
'old_state': old_state,
|
|
|
|
'new_state': state,
|
2017-02-10 17:00:17 +00:00
|
|
|
})
|
2014-04-24 07:40:45 +00:00
|
|
|
|
|
|
|
|
2015-09-27 06:17:04 +00:00
|
|
|
class Service(object):
|
2017-04-30 05:04:49 +00:00
|
|
|
"""Representation of a callable service."""
|
2015-09-27 06:17:04 +00:00
|
|
|
|
2018-01-07 22:54:16 +00:00
|
|
|
__slots__ = ['func', 'schema', 'is_callback', 'is_coroutinefunction']
|
2015-09-27 06:17:04 +00:00
|
|
|
|
2018-01-07 22:54:16 +00:00
|
|
|
def __init__(self, func, schema):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Initialize a service."""
|
2015-09-27 06:17:04 +00:00
|
|
|
self.func = func
|
2016-03-31 18:36:59 +00:00
|
|
|
self.schema = schema
|
2016-10-05 03:44:32 +00:00
|
|
|
self.is_callback = is_callback(func)
|
|
|
|
self.is_coroutinefunction = asyncio.iscoroutinefunction(func)
|
2015-09-27 06:17:04 +00:00
|
|
|
|
|
|
|
|
2014-04-24 07:40:45 +00:00
|
|
|
class ServiceCall(object):
|
2017-04-30 05:04:49 +00:00
|
|
|
"""Representation of a call to a service."""
|
2014-04-24 07:40:45 +00:00
|
|
|
|
2016-01-30 23:16:31 +00:00
|
|
|
__slots__ = ['domain', 'service', 'data', 'call_id']
|
2014-04-24 07:40:45 +00:00
|
|
|
|
2016-01-30 23:16:31 +00:00
|
|
|
def __init__(self, domain, service, data=None, call_id=None):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Initialize a service call."""
|
2016-08-10 02:41:45 +00:00
|
|
|
self.domain = domain.lower()
|
|
|
|
self.service = service.lower()
|
2016-09-30 19:57:24 +00:00
|
|
|
self.data = MappingProxyType(data or {})
|
2016-01-30 23:16:31 +00:00
|
|
|
self.call_id = call_id
|
2014-04-24 07:40:45 +00:00
|
|
|
|
|
|
|
def __repr__(self):
|
2018-01-27 19:58:27 +00:00
|
|
|
"""Return the representation of the service."""
|
2014-04-24 07:40:45 +00:00
|
|
|
if self.data:
|
|
|
|
return "<ServiceCall {}.{}: {}>".format(
|
|
|
|
self.domain, self.service, util.repr_helper(self.data))
|
2017-07-06 03:02:16 +00:00
|
|
|
|
|
|
|
return "<ServiceCall {}.{}>".format(self.domain, self.service)
|
2014-04-24 07:40:45 +00:00
|
|
|
|
|
|
|
|
|
|
|
class ServiceRegistry(object):
|
2017-04-30 05:04:49 +00:00
|
|
|
"""Offer the services over the eventbus."""
|
2014-04-24 07:40:45 +00:00
|
|
|
|
2016-11-24 22:02:39 +00:00
|
|
|
def __init__(self, hass):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Initialize a service registry."""
|
2014-04-24 07:40:45 +00:00
|
|
|
self._services = {}
|
2016-11-24 22:02:39 +00:00
|
|
|
self._hass = hass
|
2016-10-29 15:57:59 +00:00
|
|
|
self._async_unsub_call_event = None
|
2014-04-24 07:40:45 +00:00
|
|
|
|
2017-02-10 17:00:17 +00:00
|
|
|
def _gen_unique_id():
|
|
|
|
cur_id = 1
|
|
|
|
while True:
|
|
|
|
yield '{}-{}'.format(id(self), cur_id)
|
|
|
|
cur_id += 1
|
|
|
|
|
|
|
|
gen = _gen_unique_id()
|
|
|
|
self._generate_unique_id = lambda: next(gen)
|
|
|
|
|
2014-04-24 07:40:45 +00:00
|
|
|
@property
|
|
|
|
def services(self):
|
2017-05-02 20:47:20 +00:00
|
|
|
"""Return dictionary with per domain a list of available services."""
|
2016-09-13 02:16:14 +00:00
|
|
|
return run_callback_threadsafe(
|
2016-11-24 22:02:39 +00:00
|
|
|
self._hass.loop, self.async_services,
|
2016-09-13 02:16:14 +00:00
|
|
|
).result()
|
|
|
|
|
2016-10-18 02:38:41 +00:00
|
|
|
@callback
|
2016-09-13 02:16:14 +00:00
|
|
|
def async_services(self):
|
2017-05-02 20:47:20 +00:00
|
|
|
"""Return dictionary with per domain a list of available services.
|
2016-10-18 02:38:41 +00:00
|
|
|
|
|
|
|
This method must be run in the event loop.
|
|
|
|
"""
|
2018-01-07 22:54:16 +00:00
|
|
|
return {domain: self._services[domain].copy()
|
2016-09-13 02:16:14 +00:00
|
|
|
for domain in self._services}
|
2014-04-24 07:40:45 +00:00
|
|
|
|
|
|
|
def has_service(self, domain, service):
|
2016-10-18 02:38:41 +00:00
|
|
|
"""Test if specified service exists.
|
|
|
|
|
|
|
|
Async friendly.
|
|
|
|
"""
|
2016-08-10 02:41:45 +00:00
|
|
|
return service.lower() in self._services.get(domain.lower(), [])
|
2014-04-24 07:40:45 +00:00
|
|
|
|
2018-01-07 22:54:16 +00:00
|
|
|
def register(self, domain, service, service_func, schema=None):
|
2015-09-27 06:17:04 +00:00
|
|
|
"""
|
|
|
|
Register a service.
|
|
|
|
|
2016-03-31 18:36:59 +00:00
|
|
|
Schema is called to coerce and validate the service data.
|
2015-09-27 06:17:04 +00:00
|
|
|
"""
|
2016-09-13 02:16:14 +00:00
|
|
|
run_callback_threadsafe(
|
2016-11-24 22:02:39 +00:00
|
|
|
self._hass.loop,
|
2018-01-07 22:54:16 +00:00
|
|
|
self.async_register, domain, service, service_func, schema
|
2016-09-13 02:16:14 +00:00
|
|
|
).result()
|
|
|
|
|
2016-10-18 02:38:41 +00:00
|
|
|
@callback
|
2018-01-07 22:54:16 +00:00
|
|
|
def async_register(self, domain, service, service_func, schema=None):
|
2016-09-13 02:16:14 +00:00
|
|
|
"""
|
|
|
|
Register a service.
|
|
|
|
|
|
|
|
Schema is called to coerce and validate the service data.
|
|
|
|
|
|
|
|
This method must be run in the event loop.
|
|
|
|
"""
|
2016-08-10 02:41:45 +00:00
|
|
|
domain = domain.lower()
|
|
|
|
service = service.lower()
|
2018-01-07 22:54:16 +00:00
|
|
|
service_obj = Service(service_func, schema)
|
2014-04-24 07:40:45 +00:00
|
|
|
|
2016-09-13 02:16:14 +00:00
|
|
|
if domain in self._services:
|
|
|
|
self._services[domain][service] = service_obj
|
|
|
|
else:
|
|
|
|
self._services[domain] = {service: service_obj}
|
|
|
|
|
2016-10-29 15:57:59 +00:00
|
|
|
if self._async_unsub_call_event is None:
|
2016-11-24 22:02:39 +00:00
|
|
|
self._async_unsub_call_event = self._hass.bus.async_listen(
|
2016-10-29 15:57:59 +00:00
|
|
|
EVENT_CALL_SERVICE, self._event_to_service_call)
|
|
|
|
|
2016-11-24 22:02:39 +00:00
|
|
|
self._hass.bus.async_fire(
|
2016-09-13 02:16:14 +00:00
|
|
|
EVENT_SERVICE_REGISTERED,
|
|
|
|
{ATTR_DOMAIN: domain, ATTR_SERVICE: service}
|
|
|
|
)
|
2015-02-14 06:49:56 +00:00
|
|
|
|
2017-03-08 06:51:34 +00:00
|
|
|
def remove(self, domain, service):
|
|
|
|
"""Remove a registered service from service handler."""
|
|
|
|
run_callback_threadsafe(
|
|
|
|
self._hass.loop, self.async_remove, domain, service).result()
|
|
|
|
|
|
|
|
@callback
|
|
|
|
def async_remove(self, domain, service):
|
|
|
|
"""Remove a registered service from service handler.
|
|
|
|
|
|
|
|
This method must be run in the event loop.
|
|
|
|
"""
|
|
|
|
domain = domain.lower()
|
|
|
|
service = service.lower()
|
|
|
|
|
|
|
|
if service not in self._services.get(domain, {}):
|
|
|
|
_LOGGER.warning(
|
|
|
|
"Unable to remove unknown service %s/%s.", domain, service)
|
|
|
|
return
|
|
|
|
|
|
|
|
self._services[domain].pop(service)
|
|
|
|
|
|
|
|
self._hass.bus.async_fire(
|
|
|
|
EVENT_SERVICE_REMOVED,
|
|
|
|
{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
|
2017-09-23 15:15:46 +00:00
|
|
|
successfully 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.
|
|
|
|
"""
|
2016-09-13 02:16:14 +00:00
|
|
|
return run_coroutine_threadsafe(
|
|
|
|
self.async_call(domain, service, service_data, blocking),
|
2016-11-24 22:02:39 +00:00
|
|
|
self._hass.loop
|
2016-09-13 02:16:14 +00:00
|
|
|
).result()
|
|
|
|
|
2018-02-23 07:22:27 +00:00
|
|
|
async def async_call(self, domain, service, service_data=None,
|
|
|
|
blocking=False):
|
2016-09-13 02:16:14 +00:00
|
|
|
"""
|
|
|
|
Call a service.
|
|
|
|
|
|
|
|
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
|
2017-09-23 15:15:46 +00:00
|
|
|
successfully within SERVICE_CALL_LIMIT.
|
2016-09-13 02:16:14 +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.
|
|
|
|
|
|
|
|
This method is a coroutine.
|
|
|
|
"""
|
2014-12-14 06:40:00 +00:00
|
|
|
call_id = self._generate_unique_id()
|
2016-01-30 23:16:31 +00:00
|
|
|
|
|
|
|
event_data = {
|
2016-08-10 02:41:45 +00:00
|
|
|
ATTR_DOMAIN: domain.lower(),
|
|
|
|
ATTR_SERVICE: service.lower(),
|
2016-01-30 23:16:31 +00:00
|
|
|
ATTR_SERVICE_DATA: service_data,
|
|
|
|
ATTR_SERVICE_CALL_ID: call_id,
|
|
|
|
}
|
2014-12-14 06:40:00 +00:00
|
|
|
|
|
|
|
if blocking:
|
2016-11-24 22:02:39 +00:00
|
|
|
fut = asyncio.Future(loop=self._hass.loop)
|
2014-12-14 06:40:00 +00:00
|
|
|
|
2016-10-05 03:44:32 +00:00
|
|
|
@callback
|
2016-09-30 19:57:24 +00:00
|
|
|
def service_executed(event):
|
2017-05-02 20:47:20 +00:00
|
|
|
"""Handle an executed service."""
|
2016-09-30 19:57:24 +00:00
|
|
|
if event.data[ATTR_SERVICE_CALL_ID] == call_id:
|
2016-09-13 02:16:14 +00:00
|
|
|
fut.set_result(True)
|
2014-12-14 06:40:00 +00:00
|
|
|
|
2017-01-20 07:55:29 +00:00
|
|
|
unsub = self._hass.bus.async_listen(
|
|
|
|
EVENT_SERVICE_EXECUTED, service_executed)
|
2014-12-01 02:42:52 +00:00
|
|
|
|
2016-11-24 22:02:39 +00:00
|
|
|
self._hass.bus.async_fire(EVENT_CALL_SERVICE, event_data)
|
2014-12-01 02:42:52 +00:00
|
|
|
|
2014-12-14 06:40:00 +00:00
|
|
|
if blocking:
|
2018-02-23 07:22:27 +00:00
|
|
|
done, _ = await asyncio.wait(
|
2017-01-20 07:55:29 +00:00
|
|
|
[fut], loop=self._hass.loop, timeout=SERVICE_CALL_LIMIT)
|
2016-09-13 02:16:14 +00:00
|
|
|
success = bool(done)
|
2016-09-07 13:59:59 +00:00
|
|
|
unsub()
|
2015-08-04 16:13:55 +00:00
|
|
|
return success
|
2014-12-14 06:40:00 +00:00
|
|
|
|
2018-02-23 07:22:27 +00:00
|
|
|
async def _event_to_service_call(self, event):
|
2017-05-02 20:47:20 +00:00
|
|
|
"""Handle the SERVICE_CALLED events from the EventBus."""
|
2016-09-30 19:57:24 +00:00
|
|
|
service_data = event.data.get(ATTR_SERVICE_DATA) or {}
|
2016-08-10 02:41:45 +00:00
|
|
|
domain = event.data.get(ATTR_DOMAIN).lower()
|
|
|
|
service = event.data.get(ATTR_SERVICE).lower()
|
2016-01-30 23:16:31 +00:00
|
|
|
call_id = event.data.get(ATTR_SERVICE_CALL_ID)
|
2014-04-24 07:40:45 +00:00
|
|
|
|
2015-07-26 08:45:49 +00:00
|
|
|
if not self.has_service(domain, service):
|
2016-08-10 02:41:45 +00:00
|
|
|
if event.origin == EventOrigin.local:
|
2017-01-20 07:55:29 +00:00
|
|
|
_LOGGER.warning("Unable to find service %s/%s",
|
2016-08-10 02:41:45 +00:00
|
|
|
domain, service)
|
2015-07-26 08:45:49 +00:00
|
|
|
return
|
|
|
|
|
|
|
|
service_handler = self._services[domain][service]
|
2016-09-30 19:57:24 +00:00
|
|
|
|
|
|
|
def fire_service_executed():
|
|
|
|
"""Fire service executed event."""
|
|
|
|
if not call_id:
|
|
|
|
return
|
|
|
|
|
|
|
|
data = {ATTR_SERVICE_CALL_ID: call_id}
|
|
|
|
|
2016-10-05 03:44:32 +00:00
|
|
|
if (service_handler.is_coroutinefunction or
|
|
|
|
service_handler.is_callback):
|
2016-11-24 22:02:39 +00:00
|
|
|
self._hass.bus.async_fire(EVENT_SERVICE_EXECUTED, data)
|
2016-09-30 19:57:24 +00:00
|
|
|
else:
|
2016-11-24 22:02:39 +00:00
|
|
|
self._hass.bus.fire(EVENT_SERVICE_EXECUTED, data)
|
2016-09-30 19:57:24 +00:00
|
|
|
|
|
|
|
try:
|
|
|
|
if service_handler.schema:
|
|
|
|
service_data = service_handler.schema(service_data)
|
|
|
|
except vol.Invalid as ex:
|
2017-01-20 07:55:29 +00:00
|
|
|
_LOGGER.error("Invalid service data for %s.%s: %s",
|
2016-09-30 19:57:24 +00:00
|
|
|
domain, service, humanize_error(service_data, ex))
|
|
|
|
fire_service_executed()
|
|
|
|
return
|
|
|
|
|
2016-01-30 23:16:31 +00:00
|
|
|
service_call = ServiceCall(domain, service, service_data, call_id)
|
2014-04-24 07:40:45 +00:00
|
|
|
|
2018-01-01 23:32:39 +00:00
|
|
|
try:
|
|
|
|
if service_handler.is_callback:
|
2016-09-30 19:57:24 +00:00
|
|
|
service_handler.func(service_call)
|
|
|
|
fire_service_executed()
|
2018-01-01 23:32:39 +00:00
|
|
|
elif service_handler.is_coroutinefunction:
|
2018-02-23 07:22:27 +00:00
|
|
|
await service_handler.func(service_call)
|
2018-01-01 23:32:39 +00:00
|
|
|
fire_service_executed()
|
|
|
|
else:
|
|
|
|
def execute_service():
|
|
|
|
"""Execute a service and fires a SERVICE_EXECUTED event."""
|
|
|
|
service_handler.func(service_call)
|
|
|
|
fire_service_executed()
|
|
|
|
|
2018-02-23 07:22:27 +00:00
|
|
|
await self._hass.async_add_job(execute_service)
|
2018-01-01 23:32:39 +00:00
|
|
|
except Exception: # pylint: disable=broad-except
|
|
|
|
_LOGGER.exception('Error executing service %s', service_call)
|
2014-12-14 06:40:00 +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
|
|
|
|
2015-03-19 06:02:58 +00:00
|
|
|
def __init__(self):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Initialize a new config object."""
|
2016-08-07 23:26:35 +00:00
|
|
|
self.latitude = None # type: Optional[float]
|
|
|
|
self.longitude = None # type: Optional[float]
|
|
|
|
self.elevation = None # type: Optional[int]
|
|
|
|
self.location_name = None # type: Optional[str]
|
|
|
|
self.time_zone = None # type: Optional[str]
|
2016-08-09 03:42:25 +00:00
|
|
|
self.units = METRIC_SYSTEM # type: UnitSystem
|
2015-03-19 06:02:58 +00:00
|
|
|
|
2015-09-04 21:50:57 +00:00
|
|
|
# If True, pip install is skipped for requirements on startup
|
2016-08-07 23:26:35 +00:00
|
|
|
self.skip_pip = False # type: bool
|
2015-09-04 21:50:57 +00:00
|
|
|
|
2015-03-22 04:10:46 +00:00
|
|
|
# List of loaded components
|
2017-02-09 18:21:57 +00:00
|
|
|
self.components = set()
|
2015-03-22 04:10:46 +00:00
|
|
|
|
|
|
|
# Remote.API object pointing at local API
|
|
|
|
self.api = None
|
|
|
|
|
2015-03-19 06:02:58 +00:00
|
|
|
# Directory that holds the configuration
|
2016-08-09 03:21:40 +00:00
|
|
|
self.config_dir = None
|
2015-08-30 01:11:24 +00:00
|
|
|
|
2017-06-25 22:10:30 +00:00
|
|
|
# List of allowed external dirs to access
|
|
|
|
self.whitelist_external_dirs = set()
|
|
|
|
|
2018-05-12 21:44:53 +00:00
|
|
|
def distance(self, lat: float, lon: float) -> float:
|
2016-10-18 02:38:41 +00:00
|
|
|
"""Calculate distance from Home Assistant.
|
|
|
|
|
|
|
|
Async friendly.
|
|
|
|
"""
|
2016-07-31 20:24:49 +00:00
|
|
|
return self.units.length(
|
|
|
|
location.distance(self.latitude, self.longitude, lat, lon), 'm')
|
2015-09-20 16:35:03 +00:00
|
|
|
|
2015-05-11 06:05:02 +00:00
|
|
|
def path(self, *path):
|
2017-04-30 05:04:49 +00:00
|
|
|
"""Generate path to the file within the configuration directory.
|
2016-10-18 02:38:41 +00:00
|
|
|
|
|
|
|
Async friendly.
|
|
|
|
"""
|
2016-08-09 03:21:40 +00:00
|
|
|
if self.config_dir is None:
|
|
|
|
raise HomeAssistantError("config_dir is not set")
|
2015-05-11 06:05:02 +00:00
|
|
|
return os.path.join(self.config_dir, *path)
|
2015-03-19 19:27:56 +00:00
|
|
|
|
2017-06-25 22:10:30 +00:00
|
|
|
def is_allowed_path(self, path: str) -> bool:
|
|
|
|
"""Check if the path is valid for access from outside."""
|
2017-08-15 13:41:37 +00:00
|
|
|
assert path is not None
|
|
|
|
|
2018-03-30 02:57:19 +00:00
|
|
|
thepath = pathlib.Path(path)
|
2017-06-25 22:10:30 +00:00
|
|
|
try:
|
2018-03-30 02:57:19 +00:00
|
|
|
# The file path does not have to exist (it's parent should)
|
|
|
|
if thepath.exists():
|
|
|
|
thepath = thepath.resolve()
|
|
|
|
else:
|
|
|
|
thepath = thepath.parent.resolve()
|
2017-06-25 22:10:30 +00:00
|
|
|
except (FileNotFoundError, RuntimeError, PermissionError):
|
|
|
|
return False
|
|
|
|
|
|
|
|
for whitelisted_path in self.whitelist_external_dirs:
|
|
|
|
try:
|
2018-03-30 02:57:19 +00:00
|
|
|
thepath.relative_to(whitelisted_path)
|
2017-06-25 22:10:30 +00:00
|
|
|
return True
|
|
|
|
except ValueError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
return False
|
|
|
|
|
2015-05-02 01:24:32 +00:00
|
|
|
def as_dict(self):
|
2017-04-30 05:04:49 +00:00
|
|
|
"""Create a dictionary representation of this dict.
|
2016-10-18 02:38:41 +00:00
|
|
|
|
|
|
|
Async friendly.
|
|
|
|
"""
|
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,
|
2017-01-20 07:55:29 +00:00
|
|
|
'elevation': self.elevation,
|
2016-07-31 20:24:49 +00:00
|
|
|
'unit_system': self.units.as_dict(),
|
2015-05-02 01:24:32 +00:00
|
|
|
'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,
|
2016-10-03 07:04:43 +00:00
|
|
|
'config_dir': self.config_dir,
|
2017-06-25 22:10:30 +00:00
|
|
|
'whitelist_external_dirs': self.whitelist_external_dirs,
|
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
|
|
|
|
2017-02-10 17:00:17 +00:00
|
|
|
def _async_create_timer(hass):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Create a timer that will start on HOMEASSISTANT_START."""
|
2017-02-10 17:00:17 +00:00
|
|
|
handle = None
|
2015-07-26 08:45:49 +00:00
|
|
|
|
2016-10-05 03:44:32 +00:00
|
|
|
@callback
|
2017-02-10 17:00:17 +00:00
|
|
|
def fire_time_event(nxt):
|
|
|
|
"""Fire next time event."""
|
|
|
|
nonlocal handle
|
2015-07-26 08:45:49 +00:00
|
|
|
|
2017-02-10 17:00:17 +00:00
|
|
|
hass.bus.async_fire(EVENT_TIME_CHANGED,
|
|
|
|
{ATTR_NOW: dt_util.utcnow()})
|
|
|
|
nxt += 1
|
|
|
|
slp_seconds = nxt - monotonic()
|
2015-07-26 08:45:49 +00:00
|
|
|
|
2017-02-10 17:00:17 +00:00
|
|
|
if slp_seconds < 0:
|
|
|
|
_LOGGER.error('Timer got out of sync. Resetting')
|
|
|
|
nxt = monotonic() + 1
|
|
|
|
slp_seconds = 1
|
2015-07-26 08:45:49 +00:00
|
|
|
|
2017-02-10 17:00:17 +00:00
|
|
|
handle = hass.loop.call_later(slp_seconds, fire_time_event, nxt)
|
2015-07-26 08:45:49 +00:00
|
|
|
|
2017-02-10 17:00:17 +00:00
|
|
|
@callback
|
|
|
|
def stop_timer(event):
|
|
|
|
"""Stop the timer."""
|
|
|
|
if handle is not None:
|
|
|
|
handle.cancel()
|
2015-07-26 08:45:49 +00:00
|
|
|
|
2017-04-07 04:00:58 +00:00
|
|
|
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, stop_timer)
|
|
|
|
|
|
|
|
_LOGGER.info("Timer:starting")
|
|
|
|
fire_time_event(monotonic())
|