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:
Paulus Schoutsen authored and GitHub committed 2016-09-30 12:57:24 -07:00
1 parent 7e50ccd32a
commit b650b2b0db
17 files changed
+323 -151

No files matched your search

+3 -1
View File
@@ -4,6 +4,7 @@ Offer MQTT listening automation rules.
For more details about this automation rule, please refer to the documentation
at https://home-assistant.io/components/automation/#mqtt-trigger
"""
import asyncio
import voluptuous as vol
import homeassistant.components.mqtt as mqtt
@@ -26,10 +27,11 @@ def trigger(hass, config, action):
topic = config.get(CONF_TOPIC)
payload = config.get(CONF_PAYLOAD)
@asyncio.coroutine
def mqtt_automation_listener(msg_topic, msg_payload, qos):
"""Listen for MQTT messages."""
if payload is None or payload == msg_payload:
action({
hass.async_add_job(action, {
'trigger': {
'platform': 'mqtt',
'topic': msg_topic,
@@ -4,6 +4,7 @@ Offer numeric state listening automation rules.
For more details about this automation rule, please refer to the documentation
at https://home-assistant.io/components/automation/#numeric-state-trigger
"""
import asyncio
import logging
import voluptuous as vol
@@ -34,7 +35,7 @@ def trigger(hass, config, action):
if value_template is not None:
value_template.hass = hass
# pylint: disable=unused-argument
@asyncio.coroutine
def state_automation_listener(entity, from_s, to_s):
"""Listen for state changes and calls action."""
if to_s is None:
@@ -50,19 +51,19 @@ def trigger(hass, config, action):
}
# If new one doesn't match, nothing to do
if not condition.numeric_state(
if not condition.async_numeric_state(
hass, to_s, below, above, value_template, variables):
return
# Only match if old didn't exist or existed but didn't match
# Written as: skip if old one did exist and matched
if from_s is not None and condition.numeric_state(
if from_s is not None and condition.async_numeric_state(
hass, from_s, below, above, value_template, variables):
return
variables['trigger']['from_state'] = from_s
variables['trigger']['to_state'] = to_s
action(variables)
hass.async_add_job(action, variables)
return track_state_change(hass, entity_id, state_automation_listener)
+29 -19
View File
@@ -4,12 +4,15 @@ Offer state listening automation rules.
For more details about this automation rule, please refer to the documentation
at https://home-assistant.io/components/automation/#state-trigger
"""
import asyncio
import voluptuous as vol
import homeassistant.util.dt as dt_util
from homeassistant.const import MATCH_ALL, CONF_PLATFORM
from homeassistant.helpers.event import track_state_change, track_point_in_time
from homeassistant.helpers.event import (
async_track_state_change, async_track_point_in_utc_time)
import homeassistant.helpers.config_validation as cv
from homeassistant.util.async import run_callback_threadsafe
CONF_ENTITY_ID = "entity_id"
CONF_FROM = "from"
@@ -38,16 +41,17 @@ def trigger(hass, config, action):
from_state = config.get(CONF_FROM, MATCH_ALL)
to_state = config.get(CONF_TO) or config.get(CONF_STATE) or MATCH_ALL
time_delta = config.get(CONF_FOR)
remove_state_for_cancel = None
remove_state_for_listener = None
async_remove_state_for_cancel = None
async_remove_state_for_listener = None
@asyncio.coroutine
def state_automation_listener(entity, from_s, to_s):
"""Listen for state changes and calls action."""
nonlocal remove_state_for_cancel, remove_state_for_listener
nonlocal async_remove_state_for_cancel, async_remove_state_for_listener
def call_action():
"""Call action with right context."""
action({
hass.async_add_job(action, {
'trigger': {
'platform': 'state',
'entity_id': entity,
@@ -61,35 +65,41 @@ def trigger(hass, config, action):
call_action()
return
@asyncio.coroutine
def state_for_listener(now):
"""Fire on state changes after a delay and calls action."""
remove_state_for_cancel()
async_remove_state_for_cancel()
call_action()
@asyncio.coroutine
def state_for_cancel_listener(entity, inner_from_s, inner_to_s):
"""Fire on changes and cancel for listener if changed."""
if inner_to_s.state == to_s.state:
return
remove_state_for_listener()
remove_state_for_cancel()
async_remove_state_for_listener()
async_remove_state_for_cancel()
remove_state_for_listener = track_point_in_time(
async_remove_state_for_listener = async_track_point_in_utc_time(
hass, state_for_listener, dt_util.utcnow() + time_delta)
remove_state_for_cancel = track_state_change(
async_remove_state_for_cancel = async_track_state_change(
hass, entity, state_for_cancel_listener)
unsub = track_state_change(hass, entity_id, state_automation_listener,
from_state, to_state)
unsub = async_track_state_change(
hass, entity_id, state_automation_listener, from_state, to_state)
def async_remove():
"""Remove state listeners async."""
unsub()
# pylint: disable=not-callable
if async_remove_state_for_cancel is not None:
async_remove_state_for_cancel()
if async_remove_state_for_listener is not None:
async_remove_state_for_listener()
def remove():
"""Remove state listeners."""
unsub()
# pylint: disable=not-callable
if remove_state_for_cancel is not None:
remove_state_for_cancel()
if remove_state_for_listener is not None:
remove_state_for_listener()
run_callback_threadsafe(hass.loop, async_remove).result()
return remove
+3 -1
View File
@@ -4,6 +4,7 @@ Offer sun based automation rules.
For more details about this automation rule, please refer to the documentation
at https://home-assistant.io/components/automation/#sun-trigger
"""
import asyncio
from datetime import timedelta
import logging
@@ -30,9 +31,10 @@ def trigger(hass, config, action):
event = config.get(CONF_EVENT)
offset = config.get(CONF_OFFSET)
@asyncio.coroutine
def call_action():
"""Call action with right context."""
action({
hass.async_add_job(action, {
'trigger': {
'platform': 'sun',
'event': event,
+3 -1
View File
@@ -4,6 +4,7 @@ Offer time listening automation rules.
For more details about this automation rule, please refer to the documentation
at https://home-assistant.io/components/automation/#time-trigger
"""
import asyncio
import logging
import voluptuous as vol
@@ -38,9 +39,10 @@ def trigger(hass, config, action):
minutes = config.get(CONF_MINUTES)
seconds = config.get(CONF_SECONDS)
@asyncio.coroutine
def time_automation_listener(now):
"""Listen for time changes and calls action."""
action({
hass.async_add_job(action, {
'trigger': {
'platform': 'time',
'now': now,
+3 -1
View File
@@ -4,6 +4,7 @@ Offer zone automation rules.
For more details about this automation rule, please refer to the documentation
at https://home-assistant.io/components/automation/#zone-trigger
"""
import asyncio
import voluptuous as vol
from homeassistant.const import (
@@ -31,6 +32,7 @@ def trigger(hass, config, action):
zone_entity_id = config.get(CONF_ZONE)
event = config.get(CONF_EVENT)
@asyncio.coroutine
def zone_automation_listener(entity, from_s, to_s):
"""Listen for state changes and calls action."""
if from_s and not location.has_location(from_s) or \
@@ -47,7 +49,7 @@ def trigger(hass, config, action):
# pylint: disable=too-many-boolean-expressions
if event == EVENT_ENTER and not from_match and to_match or \
event == EVENT_LEAVE and from_match and not to_match:
action({
hass.async_add_job(action, {
'trigger': {
'platform': 'zone',
'entity_id': entity,
+13 -3
View File
@@ -4,6 +4,7 @@ Event parser and human readable log generator.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/logbook/
"""
import asyncio
import logging
from datetime import timedelta
from itertools import groupby
@@ -20,6 +21,7 @@ from homeassistant.const import (EVENT_HOMEASSISTANT_START,
STATE_NOT_HOME, STATE_OFF, STATE_ON,
ATTR_HIDDEN)
from homeassistant.core import State, split_entity_id, DOMAIN as HA_DOMAIN
from homeassistant.util.async import run_callback_threadsafe
DOMAIN = "logbook"
DEPENDENCIES = ['recorder', 'frontend']
@@ -57,6 +59,13 @@ LOG_MESSAGE_SCHEMA = vol.Schema({
def log_entry(hass, name, message, domain=None, entity_id=None):
"""Add an entry to the logbook."""
run_callback_threadsafe(
hass.loop, async_log_entry, hass, name, message, domain, entity_id
).result()
def async_log_entry(hass, name, message, domain=None, entity_id=None):
"""Add an entry to the logbook."""
data = {
ATTR_NAME: name,
@@ -67,11 +76,12 @@ def log_entry(hass, name, message, domain=None, entity_id=None):
data[ATTR_DOMAIN] = domain
if entity_id is not None:
data[ATTR_ENTITY_ID] = entity_id
hass.bus.fire(EVENT_LOGBOOK_ENTRY, data)
hass.bus.async_fire(EVENT_LOGBOOK_ENTRY, data)
def setup(hass, config):
"""Listen for download events to download files."""
@asyncio.coroutine
def log_message(service):
"""Handle sending notification message service calls."""
message = service.data[ATTR_MESSAGE]
@@ -80,8 +90,8 @@ def setup(hass, config):
entity_id = service.data.get(ATTR_ENTITY_ID)
message.hass = hass
message = message.render()
log_entry(hass, name, message, domain, entity_id)
message = message.async_render()
async_log_entry(hass, name, message, domain, entity_id)
hass.wsgi.register_view(LogbookView(hass, config))
+14 -3
View File
@@ -4,6 +4,7 @@ Support for MQTT message handling.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/mqtt/
"""
import asyncio
import logging
import os
import socket
@@ -11,6 +12,7 @@ import time
import voluptuous as vol
from homeassistant.core import JobPriority
from homeassistant.bootstrap import prepare_setup_platform
from homeassistant.config import load_yaml_config_file
from homeassistant.exceptions import HomeAssistantError
@@ -164,11 +166,20 @@ def publish_template(hass, topic, payload_template, qos=None, retain=None):
def subscribe(hass, topic, callback, qos=DEFAULT_QOS):
"""Subscribe to an MQTT topic."""
@asyncio.coroutine
def mqtt_topic_subscriber(event):
"""Match subscribed MQTT topic."""
if _match_topic(topic, event.data[ATTR_TOPIC]):
callback(event.data[ATTR_TOPIC], event.data[ATTR_PAYLOAD],
event.data[ATTR_QOS])
if not _match_topic(topic, event.data[ATTR_TOPIC]):
return
if asyncio.iscoroutinefunction(callback):
yield from callback(
event.data[ATTR_TOPIC], event.data[ATTR_PAYLOAD],
event.data[ATTR_QOS])
else:
hass.add_job(callback, event.data[ATTR_TOPIC],
event.data[ATTR_PAYLOAD], event.data[ATTR_QOS],
priority=JobPriority.EVENT_CALLBACK)
remove = hass.bus.listen(EVENT_MQTT_MESSAGE_RECEIVED,
mqtt_topic_subscriber)