Spread async love (#3575)
* Convert Entity.update_ha_state to be async * Make Service.call async * Update entity.py * Add Entity.async_update * Make automation zone trigger async * Fix linting * Reduce flakiness in hass.block_till_done * Make automation.numeric_state async * Make mqtt.subscribe async * Make automation.mqtt async * Make automation.time async * Make automation.sun async * Add async_track_point_in_utc_time * Make helpers.track_sunrise/set async * Add async_track_state_change * Make automation.state async * Clean up helpers/entity.py tests * Lint * Lint * Core.is_state and Core.is_state_attr are async friendly * Lint * Lint
This commit is contained in:
1 parent
7e50ccd32a
commit
b650b2b0db
17 files changed
+323
-151
No files matched your search
@@ -84,6 +84,15 @@ def or_from_config(config: ConfigType, config_validation: bool=True):
|
||||
def numeric_state(hass: HomeAssistant, entity, below=None, above=None,
|
||||
value_template=None, variables=None):
|
||||
"""Test a numeric state condition."""
|
||||
return run_callback_threadsafe(
|
||||
hass.loop, async_numeric_state, hass, entity, below, above,
|
||||
value_template, variables,
|
||||
).result()
|
||||
|
||||
|
||||
def async_numeric_state(hass: HomeAssistant, entity, below=None, above=None,
|
||||
value_template=None, variables=None):
|
||||
"""Test a numeric state condition."""
|
||||
if isinstance(entity, str):
|
||||
entity = hass.states.get(entity)
|
||||
|
||||
@@ -96,7 +105,7 @@ def numeric_state(hass: HomeAssistant, entity, below=None, above=None,
|
||||
variables = dict(variables or {})
|
||||
variables['state'] = entity
|
||||
try:
|
||||
value = value_template.render(variables)
|
||||
value = value_template.async_render(variables)
|
||||
except TemplateError as ex:
|
||||
_LOGGER.error("Template error: %s", ex)
|
||||
return False
|
||||
@@ -290,7 +299,10 @@ def time_from_config(config, config_validation=True):
|
||||
|
||||
|
||||
def zone(hass, zone_ent, entity):
|
||||
"""Test if zone-condition matches."""
|
||||
"""Test if zone-condition matches.
|
||||
|
||||
Can be run async.
|
||||
"""
|
||||
if isinstance(zone_ent, str):
|
||||
zone_ent = hass.states.get(zone_ent)
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""An abstract class for entities."""
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
from typing import Any, Optional, List, Dict
|
||||
@@ -11,6 +12,7 @@ from homeassistant.const import (
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import NoEntitySpecifiedError
|
||||
from homeassistant.util import ensure_unique_string, slugify
|
||||
from homeassistant.util.async import run_coroutine_threadsafe
|
||||
|
||||
# Entity attributes that we will overwrite
|
||||
_OVERWRITE = {} # type: Dict[str, Any]
|
||||
@@ -143,6 +145,23 @@ class Entity(object):
|
||||
|
||||
If force_refresh == True will update entity before setting state.
|
||||
"""
|
||||
# We're already in a thread, do the force refresh here.
|
||||
if force_refresh and not hasattr(self, 'async_update'):
|
||||
self.update()
|
||||
force_refresh = False
|
||||
|
||||
run_coroutine_threadsafe(
|
||||
self.async_update_ha_state(force_refresh), self.hass.loop
|
||||
).result()
|
||||
|
||||
@asyncio.coroutine
|
||||
def async_update_ha_state(self, force_refresh=False):
|
||||
"""Update Home Assistant with current state of entity.
|
||||
|
||||
If force_refresh == True will update entity before setting state.
|
||||
|
||||
This method must be run in the event loop.
|
||||
"""
|
||||
if self.hass is None:
|
||||
raise RuntimeError("Attribute hass is None for {}".format(self))
|
||||
|
||||
@@ -151,7 +170,13 @@ class Entity(object):
|
||||
"No entity id specified for entity {}".format(self.name))
|
||||
|
||||
if force_refresh:
|
||||
self.update()
|
||||
if hasattr(self, 'async_update'):
|
||||
# pylint: disable=no-member
|
||||
self.async_update()
|
||||
else:
|
||||
# PS: Run this in our own thread pool once we have
|
||||
# future support?
|
||||
yield from self.hass.loop.run_in_executor(None, self.update)
|
||||
|
||||
state = STATE_UNKNOWN if self.state is None else str(self.state)
|
||||
attr = self.state_attributes or {}
|
||||
@@ -192,7 +217,7 @@ class Entity(object):
|
||||
# Could not convert state to float
|
||||
pass
|
||||
|
||||
return self.hass.states.set(
|
||||
self.hass.states.async_set(
|
||||
self.entity_id, state, attr, self.force_update)
|
||||
|
||||
def remove(self) -> None:
|
||||
|
||||
@@ -18,6 +18,28 @@ def track_state_change(hass, entity_ids, action, from_state=None,
|
||||
|
||||
Returns a function that can be called to remove the listener.
|
||||
"""
|
||||
async_unsub = run_callback_threadsafe(
|
||||
hass.loop, async_track_state_change, hass, entity_ids, action,
|
||||
from_state, to_state).result()
|
||||
|
||||
def remove():
|
||||
"""Remove listener."""
|
||||
run_callback_threadsafe(hass.loop, async_unsub).result()
|
||||
|
||||
return remove
|
||||
|
||||
|
||||
def async_track_state_change(hass, entity_ids, action, from_state=None,
|
||||
to_state=None):
|
||||
"""Track specific state changes.
|
||||
|
||||
entity_ids, from_state and to_state can be string or list.
|
||||
Use list to match multiple.
|
||||
|
||||
Returns a function that can be called to remove the listener.
|
||||
|
||||
Must be run within the event loop.
|
||||
"""
|
||||
from_state = _process_state_match(from_state)
|
||||
to_state = _process_state_match(to_state)
|
||||
|
||||
@@ -52,7 +74,7 @@ def track_state_change(hass, entity_ids, action, from_state=None,
|
||||
event.data.get('old_state'),
|
||||
event.data.get('new_state'))
|
||||
|
||||
return hass.bus.listen(EVENT_STATE_CHANGED, state_change_listener)
|
||||
return hass.bus.async_listen(EVENT_STATE_CHANGED, state_change_listener)
|
||||
|
||||
|
||||
def track_point_in_time(hass, action, point_in_time):
|
||||
@@ -69,6 +91,19 @@ def track_point_in_time(hass, action, point_in_time):
|
||||
|
||||
|
||||
def track_point_in_utc_time(hass, action, point_in_time):
|
||||
"""Add a listener that fires once after a specific point in UTC time."""
|
||||
async_unsub = run_callback_threadsafe(
|
||||
hass.loop, async_track_point_in_utc_time, hass, action, point_in_time
|
||||
).result()
|
||||
|
||||
def remove():
|
||||
"""Remove listener."""
|
||||
run_callback_threadsafe(hass.loop, async_unsub).result()
|
||||
|
||||
return remove
|
||||
|
||||
|
||||
def async_track_point_in_utc_time(hass, action, point_in_time):
|
||||
"""Add a listener that fires once after a specific point in UTC time."""
|
||||
# Ensure point_in_time is UTC
|
||||
point_in_time = dt_util.as_utc(point_in_time)
|
||||
@@ -88,20 +123,14 @@ def track_point_in_utc_time(hass, action, point_in_time):
|
||||
# listener gets lined up twice to be executed. This will make
|
||||
# sure the second time it does nothing.
|
||||
point_in_time_listener.run = True
|
||||
async_remove()
|
||||
async_unsub()
|
||||
|
||||
hass.async_add_job(action, now)
|
||||
|
||||
future = run_callback_threadsafe(
|
||||
hass.loop, hass.bus.async_listen, EVENT_TIME_CHANGED,
|
||||
point_in_time_listener)
|
||||
async_remove = future.result()
|
||||
async_unsub = hass.bus.async_listen(EVENT_TIME_CHANGED,
|
||||
point_in_time_listener)
|
||||
|
||||
def remove():
|
||||
"""Remove listener."""
|
||||
run_callback_threadsafe(hass.loop, async_remove).result()
|
||||
|
||||
return remove
|
||||
return async_unsub
|
||||
|
||||
|
||||
def track_sunrise(hass, action, offset=None):
|
||||
@@ -118,19 +147,21 @@ def track_sunrise(hass, action, offset=None):
|
||||
|
||||
return next_time
|
||||
|
||||
@asyncio.coroutine
|
||||
def sunrise_automation_listener(now):
|
||||
"""Called when it's time for action."""
|
||||
nonlocal remove
|
||||
remove = track_point_in_utc_time(hass, sunrise_automation_listener,
|
||||
next_rise())
|
||||
action()
|
||||
remove = async_track_point_in_utc_time(
|
||||
hass, sunrise_automation_listener, next_rise())
|
||||
hass.async_add_job(action)
|
||||
|
||||
remove = track_point_in_utc_time(hass, sunrise_automation_listener,
|
||||
next_rise())
|
||||
remove = run_callback_threadsafe(
|
||||
hass.loop, async_track_point_in_utc_time, hass,
|
||||
sunrise_automation_listener, next_rise()).result()
|
||||
|
||||
def remove_listener():
|
||||
"""Remove sunrise listener."""
|
||||
remove()
|
||||
"""Remove sunset listener."""
|
||||
run_callback_threadsafe(hass.loop, remove).result()
|
||||
|
||||
return remove_listener
|
||||
|
||||
@@ -149,19 +180,21 @@ def track_sunset(hass, action, offset=None):
|
||||
|
||||
return next_time
|
||||
|
||||
@asyncio.coroutine
|
||||
def sunset_automation_listener(now):
|
||||
"""Called when it's time for action."""
|
||||
nonlocal remove
|
||||
remove = track_point_in_utc_time(hass, sunset_automation_listener,
|
||||
next_set())
|
||||
action()
|
||||
remove = async_track_point_in_utc_time(
|
||||
hass, sunset_automation_listener, next_set())
|
||||
hass.async_add_job(action)
|
||||
|
||||
remove = track_point_in_utc_time(hass, sunset_automation_listener,
|
||||
next_set())
|
||||
remove = run_callback_threadsafe(
|
||||
hass.loop, async_track_point_in_utc_time, hass,
|
||||
sunset_automation_listener, next_set()).result()
|
||||
|
||||
def remove_listener():
|
||||
"""Remove sunset listener."""
|
||||
remove()
|
||||
run_callback_threadsafe(hass.loop, remove).result()
|
||||
|
||||
return remove_listener
|
||||
|
||||
|
||||
@@ -149,8 +149,8 @@ class Template(object):
|
||||
global_vars = ENV.make_globals({
|
||||
'closest': location_methods.closest,
|
||||
'distance': location_methods.distance,
|
||||
'is_state': self.hass.states.async_is_state,
|
||||
'is_state_attr': self.hass.states.async_is_state_attr,
|
||||
'is_state': self.hass.states.is_state,
|
||||
'is_state_attr': self.hass.states.is_state_attr,
|
||||
'states': AllStates(self.hass),
|
||||
})
|
||||
|
||||
|
||||
Reference in new issue
Block a user