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
|
2016-08-09 03:21:40 +00:00
|
|
|
import re
|
2015-09-01 06:12:00 +00:00
|
|
|
import signal
|
2016-09-13 02:16:14 +00:00
|
|
|
import sys
|
2016-09-18 01:28:01 +00:00
|
|
|
import threading
|
2016-09-13 02:16:14 +00:00
|
|
|
|
2016-02-10 07:27:01 +00:00
|
|
|
from types import MappingProxyType
|
2016-08-09 03:21:40 +00:00
|
|
|
from typing import Optional, Any, Callable, List # NOQA
|
2016-08-07 23:26:35 +00:00
|
|
|
|
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-02-08 17:17:52 +00:00
|
|
|
EVENT_TIME_CHANGED, MATCH_ALL, RESTART_EXIT_CODE, __version__)
|
2016-02-19 05:27:50 +00:00
|
|
|
from homeassistant.exceptions import (
|
2016-11-17 20:02:43 +00:00
|
|
|
HomeAssistantError, InvalidEntityFormatError, ShuttingDown)
|
2016-09-13 02:16:14 +00:00
|
|
|
from homeassistant.util.async import (
|
|
|
|
run_coroutine_threadsafe, run_callback_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
|
|
|
|
2016-09-20 07:06:33 +00:00
|
|
|
try:
|
|
|
|
import uvloop
|
|
|
|
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
|
|
|
|
except ImportError:
|
|
|
|
pass
|
|
|
|
|
2017-01-20 07:55:29 +00:00
|
|
|
DOMAIN = 'homeassistant'
|
2014-01-05 01:55:05 +00:00
|
|
|
|
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
|
|
|
|
|
2016-08-09 03:21:40 +00:00
|
|
|
# Pattern for validating entity IDs (format: <domain>.<entity>)
|
|
|
|
ENTITY_ID_PATTERN = re.compile(r"^(\w+)\.(\w+)$")
|
|
|
|
|
2016-11-05 16:27:55 +00:00
|
|
|
# Size of a executor pool
|
2016-11-24 22:56:33 +00:00
|
|
|
EXECUTOR_POOL_SIZE = 10
|
2016-09-20 06:39:49 +00:00
|
|
|
|
2016-12-17 20:21:52 +00:00
|
|
|
# AsyncHandler for logging
|
|
|
|
DATA_ASYNCHANDLER = 'log_asynchandler'
|
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
|
|
|
|
|
|
|
|
|
2016-10-05 03:44:32 +00:00
|
|
|
def callback(func: Callable[..., None]) -> Callable[..., None]:
|
|
|
|
"""Annotation to mark method as safe to call from within the event loop."""
|
|
|
|
# pylint: disable=protected-access
|
|
|
|
func._hass_callback = True
|
|
|
|
return func
|
|
|
|
|
|
|
|
|
|
|
|
def is_callback(func: Callable[..., Any]) -> bool:
|
|
|
|
"""Check if function is safe to be called in the event loop."""
|
|
|
|
return '_hass_callback' in func.__dict__
|
|
|
|
|
|
|
|
|
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()
|
|
|
|
|
2016-11-23 17:52:03 +00:00
|
|
|
self.executor = ThreadPoolExecutor(max_workers=EXECUTOR_POOL_SIZE)
|
2016-10-01 22:43:33 +00:00
|
|
|
self.loop.set_default_executor(self.executor)
|
2016-10-08 00:20:39 +00:00
|
|
|
self.loop.set_exception_handler(self._async_exception_handler)
|
2016-11-08 09:24:50 +00:00
|
|
|
self._pending_tasks = []
|
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
|
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
|
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
|
|
|
|
2016-07-21 05:38:52 +00:00
|
|
|
def start(self) -> None:
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Start home assistant."""
|
2016-09-13 02:16:14 +00:00
|
|
|
# Register the async start
|
|
|
|
self.loop.create_task(self.async_start())
|
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-02-08 17:17:52 +00:00
|
|
|
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()
|
2016-09-13 02:16:14 +00:00
|
|
|
|
|
|
|
@asyncio.coroutine
|
|
|
|
def async_start(self):
|
|
|
|
"""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
|
|
|
|
|
|
|
|
# Setup signal handling
|
|
|
|
if sys.platform != 'win32':
|
2017-02-08 17:17:52 +00:00
|
|
|
def _async_signal_handle(exit_code):
|
|
|
|
"""Wrap signal handling."""
|
|
|
|
self.async_add_job(self.async_stop(exit_code))
|
|
|
|
|
2016-10-29 15:57:59 +00:00
|
|
|
try:
|
|
|
|
self.loop.add_signal_handler(
|
2017-02-08 17:17:52 +00:00
|
|
|
signal.SIGTERM, _async_signal_handle, 0)
|
2016-10-29 15:57:59 +00:00
|
|
|
except ValueError:
|
2017-01-20 07:55:29 +00:00
|
|
|
_LOGGER.warning("Could not bind to SIGTERM")
|
2016-10-29 15:57:59 +00:00
|
|
|
|
|
|
|
try:
|
|
|
|
self.loop.add_signal_handler(
|
2017-02-08 17:17:52 +00:00
|
|
|
signal.SIGHUP, _async_signal_handle, RESTART_EXIT_CODE)
|
2016-10-29 15:57:59 +00:00
|
|
|
except ValueError:
|
2017-01-20 07:55:29 +00:00
|
|
|
_LOGGER.warning("Could not bind to SIGHUP")
|
2016-10-29 15:57:59 +00:00
|
|
|
|
2016-10-02 22:07:23 +00:00
|
|
|
# pylint: disable=protected-access
|
|
|
|
self.loop._thread_ident = threading.get_ident()
|
2016-10-18 02:38:41 +00:00
|
|
|
_async_create_timer(self)
|
2016-09-13 02:16:14 +00:00
|
|
|
self.bus.async_fire(EVENT_HOMEASSISTANT_START)
|
|
|
|
self.state = CoreState.running
|
|
|
|
|
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
|
|
|
|
def _async_add_job(self, target: Callable[..., None], *args: Any) -> None:
|
|
|
|
"""Add a job from within the eventloop.
|
2016-11-09 16:41:17 +00:00
|
|
|
|
2016-11-24 22:49:29 +00:00
|
|
|
This method must be run in the event loop.
|
2016-09-13 02:16:14 +00:00
|
|
|
|
|
|
|
target: target to call.
|
|
|
|
args: parameters for method to call.
|
|
|
|
"""
|
2016-11-24 22:49:29 +00:00
|
|
|
if asyncio.iscoroutine(target):
|
|
|
|
self.loop.create_task(target)
|
|
|
|
elif is_callback(target):
|
|
|
|
self.loop.call_soon(target, *args)
|
|
|
|
elif asyncio.iscoroutinefunction(target):
|
|
|
|
self.loop.create_task(target(*args))
|
|
|
|
else:
|
|
|
|
self.loop.run_in_executor(None, target, *args)
|
|
|
|
|
|
|
|
async_add_job = _async_add_job
|
2016-09-13 02:16:14 +00:00
|
|
|
|
2016-10-18 02:38:41 +00:00
|
|
|
@callback
|
2016-11-24 22:49:29 +00:00
|
|
|
def _async_add_job_tracking(self, target: Callable[..., None],
|
|
|
|
*args: Any) -> None:
|
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)
|
|
|
|
|
|
|
|
# if a task is sheduled
|
|
|
|
if task is not None:
|
2016-11-08 09:24:50 +00:00
|
|
|
self._pending_tasks.append(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."""
|
|
|
|
self.async_add_job = self._async_add_job_tracking
|
|
|
|
|
2016-11-30 21:02:45 +00:00
|
|
|
@asyncio.coroutine
|
|
|
|
def async_stop_track_tasks(self):
|
|
|
|
"""Track tasks so you can wait for all tasks to be done."""
|
|
|
|
yield from self.async_block_till_done()
|
|
|
|
self.async_add_job = self._async_add_job
|
|
|
|
|
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.
|
|
|
|
"""
|
|
|
|
if is_callback(target):
|
|
|
|
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
|
|
|
|
2016-11-05 16:27:55 +00:00
|
|
|
@asyncio.coroutine
|
|
|
|
def async_block_till_done(self):
|
|
|
|
"""Block till all pending work is done."""
|
2016-11-24 22:49:29 +00:00
|
|
|
# To flush out any call_soon_threadsafe
|
|
|
|
yield from asyncio.sleep(0, loop=self.loop)
|
|
|
|
|
|
|
|
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()
|
2016-11-06 16:43:32 +00:00
|
|
|
if len(pending) > 0:
|
|
|
|
yield from asyncio.wait(pending, loop=self.loop)
|
2016-11-24 22:49:29 +00:00
|
|
|
else:
|
|
|
|
yield from 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."""
|
2016-09-13 02:16:14 +00:00
|
|
|
run_coroutine_threadsafe(self.async_stop(), self.loop)
|
|
|
|
|
|
|
|
@asyncio.coroutine
|
2017-02-08 17:17:52 +00:00
|
|
|
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-01-05 22:09:04 +00:00
|
|
|
import homeassistant.helpers.aiohttp_client as aiohttp_client
|
|
|
|
|
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)
|
2016-11-05 16:27:55 +00:00
|
|
|
yield from self.async_block_till_done()
|
2016-10-01 22:43:33 +00:00
|
|
|
self.executor.shutdown()
|
2016-06-30 16:02:12 +00:00
|
|
|
self.state = CoreState.not_running
|
2016-12-17 20:21:52 +00:00
|
|
|
|
2017-01-05 22:09:04 +00:00
|
|
|
# cleanup connector pool from aiohttp
|
|
|
|
yield from aiohttp_client.async_cleanup_websession(self)
|
|
|
|
|
2016-12-17 20:21:52 +00:00
|
|
|
# cleanup async layer from python logging
|
|
|
|
if self.data.get(DATA_ASYNCHANDLER):
|
|
|
|
handler = self.data.pop(DATA_ASYNCHANDLER)
|
2016-12-18 08:14:59 +00:00
|
|
|
logging.getLogger('').removeHandler(handler)
|
|
|
|
yield from handler.async_close(blocking=True)
|
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
|
|
|
|
2016-10-08 00:20:39 +00:00
|
|
|
# pylint: disable=no-self-use
|
2016-10-29 15:57:59 +00:00
|
|
|
@callback
|
2016-10-08 00:20:39 +00:00
|
|
|
def _async_exception_handler(self, loop, context):
|
|
|
|
"""Handle all exception inside the core loop."""
|
2016-11-17 07:01:14 +00:00
|
|
|
kwargs = {}
|
2016-10-08 00:20:39 +00:00
|
|
|
exception = context.get('exception')
|
2016-11-17 07:01:14 +00:00
|
|
|
if exception:
|
2016-11-17 20:02:43 +00:00
|
|
|
# Do not report on shutting down exceptions.
|
|
|
|
if isinstance(exception, ShuttingDown):
|
|
|
|
return
|
|
|
|
|
2016-11-17 07:01:14 +00:00
|
|
|
kwargs['exc_info'] = (type(exception), exception,
|
|
|
|
exception.__traceback__)
|
|
|
|
|
2017-01-20 07:55:29 +00:00
|
|
|
_LOGGER.error("Error doing job: %s", context['message'], **kwargs)
|
2016-10-08 00:20:39 +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):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""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
|
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))
|
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):
|
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):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Allows 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."""
|
2014-04-24 07:40:45 +00:00
|
|
|
self._listeners = {}
|
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):
|
|
|
|
"""Dict with events and the number of listeners.
|
|
|
|
|
|
|
|
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):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Dict 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,
|
|
|
|
origin=EventOrigin.local, wait=False):
|
|
|
|
"""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.
|
|
|
|
"""
|
2016-10-18 02:38:41 +00:00
|
|
|
if event_type != EVENT_HOMEASSISTANT_STOP and \
|
|
|
|
self._hass.state == CoreState.stopping:
|
2017-01-20 07:55:29 +00:00
|
|
|
raise ShuttingDown("Home Assistant is shutting down")
|
2016-10-18 02:38:41 +00:00
|
|
|
|
2016-09-13 02:16:14 +00:00
|
|
|
# Copy the list of the current listeners because some listeners
|
|
|
|
# remove themselves as a listener while being executed which
|
|
|
|
# causes the iterator to be confused.
|
|
|
|
get = self._listeners.get
|
|
|
|
listeners = get(MATCH_ALL, []) + get(event_type, [])
|
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)
|
2016-09-13 02:16:14 +00:00
|
|
|
|
2016-10-18 02:38:41 +00:00
|
|
|
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."""
|
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()
|
2016-02-13 08:08:32 +00:00
|
|
|
self.state = str(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()
|
2014-01-20 03:10:40 +00:00
|
|
|
|
2016-04-16 07:55:35 +00:00
|
|
|
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)
|
2015-02-06 08:17:30 +00:00
|
|
|
|
2016-09-30 19:57:24 +00:00
|
|
|
return state_obj and state_obj.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):
|
2016-09-13 02:16:14 +00:00
|
|
|
"""Test if entity exists and has a state attribute set to value.
|
|
|
|
|
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)
|
2015-12-31 20:58:18 +00:00
|
|
|
|
2016-09-30 19:57:24 +00:00
|
|
|
return state_obj and state_obj.attributes.get(name, None) == value
|
2015-12-31 20:58:18 +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
|
|
|
|
2016-09-13 02:16:14 +00:00
|
|
|
event_data = {
|
|
|
|
'entity_id': entity_id,
|
|
|
|
'old_state': old_state,
|
|
|
|
'new_state': None,
|
|
|
|
}
|
2016-02-14 06:57:40 +00:00
|
|
|
|
2016-09-13 02:16:14 +00:00
|
|
|
self._bus.async_fire(EVENT_STATE_CHANGED, event_data)
|
2016-02-14 06:57:40 +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 {}
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2016-09-13 02:16:14 +00:00
|
|
|
old_state = self._states.get(entity_id)
|
2013-09-30 07:20:27 +00:00
|
|
|
|
2016-09-13 02:16:14 +00:00
|
|
|
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
|
|
|
# If state did not exist or is different, set it
|
|
|
|
last_changed = old_state.last_changed if same_state else None
|
2013-10-24 06:57:08 +00:00
|
|
|
|
2016-09-13 02:16:14 +00:00
|
|
|
state = State(entity_id, new_state, attributes, last_changed)
|
|
|
|
self._states[entity_id] = state
|
2014-01-23 03:40:19 +00:00
|
|
|
|
2016-09-13 02:16:14 +00:00
|
|
|
event_data = {
|
|
|
|
'entity_id': entity_id,
|
|
|
|
'old_state': old_state,
|
|
|
|
'new_state': state,
|
|
|
|
}
|
2014-04-29 07:30:31 +00:00
|
|
|
|
2016-09-13 02:16:14 +00:00
|
|
|
self._bus.async_fire(EVENT_STATE_CHANGED, event_data)
|
2014-04-24 07:40:45 +00:00
|
|
|
|
|
|
|
|
2015-09-27 06:17:04 +00:00
|
|
|
class Service(object):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Represents a callable service."""
|
2015-09-27 06:17:04 +00:00
|
|
|
|
2016-09-30 19:57:24 +00:00
|
|
|
__slots__ = ['func', 'description', 'fields', 'schema',
|
2016-10-05 03:44:32 +00:00
|
|
|
'is_callback', 'is_coroutinefunction']
|
2015-09-27 06:17:04 +00:00
|
|
|
|
2016-03-31 18:36:59 +00:00
|
|
|
def __init__(self, func, description, fields, schema):
|
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 {}
|
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
|
|
|
|
|
|
|
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,
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2014-04-24 07:40:45 +00:00
|
|
|
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
|
|
|
|
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):
|
2016-03-07 23:06:04 +00:00
|
|
|
"""Return the represenation 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))
|
|
|
|
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
|
|
|
|
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
|
2014-12-14 06:40:00 +00:00
|
|
|
self._cur_id = 0
|
2016-10-29 15:57:59 +00:00
|
|
|
self._async_unsub_call_event = None
|
2014-04-24 07:40:45 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def services(self):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Dict 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):
|
2016-10-18 02:38:41 +00:00
|
|
|
"""Dict with per domain a list of available services.
|
|
|
|
|
|
|
|
This method must be run in the event loop.
|
|
|
|
"""
|
2016-09-13 02:16:14 +00:00
|
|
|
return {domain: {key: value.as_dict() for key, value
|
|
|
|
in self._services[domain].items()}
|
|
|
|
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
|
|
|
|
2016-03-31 18:36:59 +00:00
|
|
|
def register(self, domain, service, service_func, description=None,
|
|
|
|
schema=None):
|
2015-09-27 06:17:04 +00:00
|
|
|
"""
|
|
|
|
Register a service.
|
|
|
|
|
|
|
|
Description is a dict containing key 'description' to describe
|
|
|
|
the service and a key 'fields' to describe the fields.
|
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,
|
2016-09-13 02:16:14 +00:00
|
|
|
self.async_register, domain, service, service_func, description,
|
|
|
|
schema
|
|
|
|
).result()
|
|
|
|
|
2016-10-18 02:38:41 +00:00
|
|
|
@callback
|
2016-09-13 02:16:14 +00:00
|
|
|
def async_register(self, domain, service, service_func, description=None,
|
|
|
|
schema=None):
|
|
|
|
"""
|
|
|
|
Register a service.
|
|
|
|
|
|
|
|
Description is a dict containing key 'description' to describe
|
|
|
|
the service and a key 'fields' to describe the fields.
|
|
|
|
|
|
|
|
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()
|
2015-09-27 06:17:04 +00:00
|
|
|
description = description or {}
|
|
|
|
service_obj = Service(service_func, description.get('description'),
|
2016-03-31 18:36:59 +00:00
|
|
|
description.get('fields', {}), 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
|
|
|
|
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.
|
|
|
|
"""
|
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()
|
|
|
|
|
2016-10-18 02:38:41 +00:00
|
|
|
@asyncio.coroutine
|
2016-09-13 02:16:14 +00:00
|
|
|
def async_call(self, domain, service, service_data=None, blocking=False):
|
|
|
|
"""
|
|
|
|
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
|
|
|
|
succesfully within SERVICE_CALL_LIMIT.
|
|
|
|
|
|
|
|
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):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Callback method that is called when service is executed."""
|
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:
|
2017-01-20 07:55:29 +00:00
|
|
|
done, _ = yield from asyncio.wait(
|
|
|
|
[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
|
|
|
|
2016-09-30 19:57:24 +00:00
|
|
|
@asyncio.coroutine
|
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."""
|
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
|
|
|
|
2016-10-05 03:44:32 +00:00
|
|
|
if service_handler.is_callback:
|
|
|
|
service_handler.func(service_call)
|
|
|
|
fire_service_executed()
|
|
|
|
elif service_handler.is_coroutinefunction:
|
|
|
|
yield from service_handler.func(service_call)
|
|
|
|
fire_service_executed()
|
|
|
|
else:
|
2016-09-30 19:57:24 +00:00
|
|
|
def execute_service():
|
|
|
|
"""Execute a service and fires a SERVICE_EXECUTED event."""
|
|
|
|
service_handler.func(service_call)
|
|
|
|
fire_service_executed()
|
2014-12-14 06:40:00 +00:00
|
|
|
|
2016-11-24 22:02:39 +00:00
|
|
|
self._hass.async_add_job(execute_service)
|
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
|
2017-01-20 07:55:29 +00:00
|
|
|
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
|
|
|
|
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
|
|
|
|
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
|
2016-08-09 03:21:40 +00:00
|
|
|
self.config_dir = None
|
2015-08-30 01:11:24 +00:00
|
|
|
|
2016-07-31 20:24:49 +00:00
|
|
|
def distance(self: object, 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):
|
2016-10-18 02:38:41 +00:00
|
|
|
"""Generate path to the file within the config dir.
|
|
|
|
|
|
|
|
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
|
|
|
|
2015-05-02 01:24:32 +00:00
|
|
|
def as_dict(self):
|
2016-10-18 02:38:41 +00:00
|
|
|
"""Create a dict representation of this dict.
|
|
|
|
|
|
|
|
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,
|
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
|
|
|
|
2016-10-18 02:38:41 +00:00
|
|
|
def _async_create_timer(hass, interval=TIMER_INTERVAL):
|
2015-12-28 05:14:35 +00:00
|
|
|
"""Create a timer that will start on HOMEASSISTANT_START."""
|
2016-09-13 02:16:14 +00:00
|
|
|
stop_event = asyncio.Event(loop=hass.loop)
|
2015-07-26 08:45:49 +00:00
|
|
|
|
2016-09-13 02:16:14 +00:00
|
|
|
# Setting the Event inside the loop by marking it as a coroutine
|
2016-10-05 03:44:32 +00:00
|
|
|
@callback
|
2016-09-13 02:16:14 +00:00
|
|
|
def stop_timer(event):
|
|
|
|
"""Stop the timer."""
|
|
|
|
stop_event.set()
|
2015-07-26 08:45:49 +00:00
|
|
|
|
2016-09-13 02:16:14 +00:00
|
|
|
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, stop_timer)
|
2015-07-26 08:45:49 +00:00
|
|
|
|
2016-09-13 02:16:14 +00:00
|
|
|
@asyncio.coroutine
|
|
|
|
def timer(interval, stop_event):
|
|
|
|
"""Create an async timer."""
|
2015-07-26 08:45:49 +00:00
|
|
|
_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
|
|
|
|
2016-07-28 03:33:49 +00:00
|
|
|
while not stop_event.is_set():
|
2015-07-26 08:45:49 +00:00
|
|
|
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
|
|
|
|
|
2016-09-13 02:16:14 +00:00
|
|
|
yield from asyncio.sleep(slp_seconds, loop=hass.loop)
|
2015-07-26 08:45:49 +00:00
|
|
|
|
|
|
|
now = calc_now()
|
|
|
|
|
|
|
|
last_fired_on_second = now.second
|
|
|
|
|
|
|
|
# Event might have been set while sleeping
|
2016-07-28 03:33:49 +00:00
|
|
|
if not stop_event.is_set():
|
2015-07-26 08:45:49 +00:00
|
|
|
try:
|
2016-09-13 02:16:14 +00:00
|
|
|
# Schedule the bus event
|
|
|
|
hass.loop.call_soon(
|
|
|
|
hass.bus.async_fire,
|
|
|
|
EVENT_TIME_CHANGED,
|
|
|
|
{ATTR_NOW: now}
|
|
|
|
)
|
2016-11-17 20:02:43 +00:00
|
|
|
except ShuttingDown:
|
2015-07-26 08:45:49 +00:00
|
|
|
# HA raises error if firing event after it has shut down
|
|
|
|
break
|
|
|
|
|
2016-09-13 02:16:14 +00:00
|
|
|
@asyncio.coroutine
|
2015-07-26 08:45:49 +00:00
|
|
|
def start_timer(event):
|
2016-09-13 02:16:14 +00:00
|
|
|
"""Start our async timer."""
|
|
|
|
hass.loop.create_task(timer(interval, stop_event))
|
2015-07-26 08:45:49 +00:00
|
|
|
|
2016-09-13 02:16:14 +00:00
|
|
|
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, start_timer)
|