Async syntax (#17033)

* async-syntax-mqtt_room

* async-syntax-alert

* Additional fixes
This commit is contained in:
cdce8p 2018-10-01 14:44:11 +02:00 committed by Paulus Schoutsen
parent f0fbdd6a26
commit b5e3d8c337
4 changed files with 33 additions and 47 deletions

View file

@ -98,14 +98,12 @@ def async_toggle(hass, entity_id):
hass.services.async_call(DOMAIN, SERVICE_TOGGLE, data)) hass.services.async_call(DOMAIN, SERVICE_TOGGLE, data))
@asyncio.coroutine async def async_setup(hass, config):
def async_setup(hass, config):
"""Set up the Alert component.""" """Set up the Alert component."""
alerts = config.get(DOMAIN) alerts = config.get(DOMAIN)
all_alerts = {} all_alerts = {}
@asyncio.coroutine async def async_handle_alert_service(service_call):
def async_handle_alert_service(service_call):
"""Handle calls to alert services.""" """Handle calls to alert services."""
alert_ids = service.extract_entity_ids(hass, service_call) alert_ids = service.extract_entity_ids(hass, service_call)
@ -113,11 +111,11 @@ def async_setup(hass, config):
alert = all_alerts[alert_id] alert = all_alerts[alert_id]
alert.async_set_context(service_call.context) alert.async_set_context(service_call.context)
if service_call.service == SERVICE_TURN_ON: if service_call.service == SERVICE_TURN_ON:
yield from alert.async_turn_on() await alert.async_turn_on()
elif service_call.service == SERVICE_TOGGLE: elif service_call.service == SERVICE_TOGGLE:
yield from alert.async_toggle() await alert.async_toggle()
else: else:
yield from alert.async_turn_off() await alert.async_turn_off()
# Setup alerts # Setup alerts
for entity_id, alert in alerts.items(): for entity_id, alert in alerts.items():
@ -141,7 +139,7 @@ def async_setup(hass, config):
tasks = [alert.async_update_ha_state() for alert in all_alerts.values()] tasks = [alert.async_update_ha_state() for alert in all_alerts.values()]
if tasks: if tasks:
yield from asyncio.wait(tasks, loop=hass.loop) await asyncio.wait(tasks, loop=hass.loop)
return True return True
@ -196,17 +194,15 @@ class Alert(ToggleEntity):
"""Hide the alert when it is not firing.""" """Hide the alert when it is not firing."""
return not self._can_ack or not self._firing return not self._can_ack or not self._firing
@asyncio.coroutine async def watched_entity_change(self, entity, from_state, to_state):
def watched_entity_change(self, entity, from_state, to_state):
"""Determine if the alert should start or stop.""" """Determine if the alert should start or stop."""
_LOGGER.debug("Watched entity (%s) has changed", entity) _LOGGER.debug("Watched entity (%s) has changed", entity)
if to_state.state == self._alert_state and not self._firing: if to_state.state == self._alert_state and not self._firing:
yield from self.begin_alerting() await self.begin_alerting()
if to_state.state != self._alert_state and self._firing: if to_state.state != self._alert_state and self._firing:
yield from self.end_alerting() await self.end_alerting()
@asyncio.coroutine async def begin_alerting(self):
def begin_alerting(self):
"""Begin the alert procedures.""" """Begin the alert procedures."""
_LOGGER.debug("Beginning Alert: %s", self._name) _LOGGER.debug("Beginning Alert: %s", self._name)
self._ack = False self._ack = False
@ -214,25 +210,23 @@ class Alert(ToggleEntity):
self._next_delay = 0 self._next_delay = 0
if not self._skip_first: if not self._skip_first:
yield from self._notify() await self._notify()
else: else:
yield from self._schedule_notify() await self._schedule_notify()
self.async_schedule_update_ha_state() self.async_schedule_update_ha_state()
@asyncio.coroutine async def end_alerting(self):
def end_alerting(self):
"""End the alert procedures.""" """End the alert procedures."""
_LOGGER.debug("Ending Alert: %s", self._name) _LOGGER.debug("Ending Alert: %s", self._name)
self._cancel() self._cancel()
self._ack = False self._ack = False
self._firing = False self._firing = False
if self._done_message and self._send_done_message: if self._done_message and self._send_done_message:
yield from self._notify_done_message() await self._notify_done_message()
self.async_schedule_update_ha_state() self.async_schedule_update_ha_state()
@asyncio.coroutine async def _schedule_notify(self):
def _schedule_notify(self):
"""Schedule a notification.""" """Schedule a notification."""
delay = self._delay[self._next_delay] delay = self._delay[self._next_delay]
next_msg = datetime.now() + delay next_msg = datetime.now() + delay
@ -240,8 +234,7 @@ class Alert(ToggleEntity):
event.async_track_point_in_time(self.hass, self._notify, next_msg) event.async_track_point_in_time(self.hass, self._notify, next_msg)
self._next_delay = min(self._next_delay + 1, len(self._delay) - 1) self._next_delay = min(self._next_delay + 1, len(self._delay) - 1)
@asyncio.coroutine async def _notify(self, *args):
def _notify(self, *args):
"""Send the alert notification.""" """Send the alert notification."""
if not self._firing: if not self._firing:
return return
@ -250,36 +243,32 @@ class Alert(ToggleEntity):
_LOGGER.info("Alerting: %s", self._name) _LOGGER.info("Alerting: %s", self._name)
self._send_done_message = True self._send_done_message = True
for target in self._notifiers: for target in self._notifiers:
yield from self.hass.services.async_call( await self.hass.services.async_call(
'notify', target, {'message': self._name}) 'notify', target, {'message': self._name})
yield from self._schedule_notify() await self._schedule_notify()
@asyncio.coroutine async def _notify_done_message(self, *args):
def _notify_done_message(self, *args):
"""Send notification of complete alert.""" """Send notification of complete alert."""
_LOGGER.info("Alerting: %s", self._done_message) _LOGGER.info("Alerting: %s", self._done_message)
self._send_done_message = False self._send_done_message = False
for target in self._notifiers: for target in self._notifiers:
yield from self.hass.services.async_call( await self.hass.services.async_call(
'notify', target, {'message': self._done_message}) 'notify', target, {'message': self._done_message})
@asyncio.coroutine async def async_turn_on(self, **kwargs):
def async_turn_on(self, **kwargs):
"""Async Unacknowledge alert.""" """Async Unacknowledge alert."""
_LOGGER.debug("Reset Alert: %s", self._name) _LOGGER.debug("Reset Alert: %s", self._name)
self._ack = False self._ack = False
yield from self.async_update_ha_state() await self.async_update_ha_state()
@asyncio.coroutine async def async_turn_off(self, **kwargs):
def async_turn_off(self, **kwargs):
"""Async Acknowledge alert.""" """Async Acknowledge alert."""
_LOGGER.debug("Acknowledged Alert: %s", self._name) _LOGGER.debug("Acknowledged Alert: %s", self._name)
self._ack = True self._ack = True
yield from self.async_update_ha_state() await self.async_update_ha_state()
@asyncio.coroutine async def async_toggle(self, **kwargs):
def async_toggle(self, **kwargs):
"""Async toggle alert.""" """Async toggle alert."""
if self._ack: if self._ack:
return self.async_turn_on() return await self.async_turn_on()
return self.async_turn_off() return await self.async_turn_off()

View file

@ -50,7 +50,7 @@ async def async_setup_platform(hass, config, async_add_entities,
"""Set up the FFmpeg binary motion sensor.""" """Set up the FFmpeg binary motion sensor."""
manager = hass.data[DATA_FFMPEG] manager = hass.data[DATA_FFMPEG]
if not manager.async_run_test(config.get(CONF_INPUT)): if not await manager.async_run_test(config.get(CONF_INPUT)):
return return
entity = FFmpegMotion(hass, manager, config) entity = FFmpegMotion(hass, manager, config)

View file

@ -47,7 +47,7 @@ async def async_setup_platform(hass, config, async_add_entities,
"""Set up the FFmpeg noise binary sensor.""" """Set up the FFmpeg noise binary sensor."""
manager = hass.data[DATA_FFMPEG] manager = hass.data[DATA_FFMPEG]
if not manager.async_run_test(config.get(CONF_INPUT)): if not await manager.async_run_test(config.get(CONF_INPUT)):
return return
entity = FFmpegNoise(hass, manager, config) entity = FFmpegNoise(hass, manager, config)

View file

@ -4,7 +4,6 @@ Support for MQTT room presence detection.
For more details about this platform, please refer to the documentation at For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.mqtt_room/ https://home-assistant.io/components/sensor.mqtt_room/
""" """
import asyncio
import logging import logging
import json import json
from datetime import timedelta from datetime import timedelta
@ -52,8 +51,7 @@ MQTT_PAYLOAD = vol.Schema(vol.All(json.loads, vol.Schema({
}, extra=vol.ALLOW_EXTRA))) }, extra=vol.ALLOW_EXTRA)))
@asyncio.coroutine async def async_setup_platform(hass, config, async_add_entities,
def async_setup_platform(hass, config, async_add_entities,
discovery_info=None): discovery_info=None):
"""Set up MQTT room Sensor.""" """Set up MQTT room Sensor."""
async_add_entities([MQTTRoomSensor( async_add_entities([MQTTRoomSensor(
@ -81,8 +79,7 @@ class MQTTRoomSensor(Entity):
self._distance = None self._distance = None
self._updated = None self._updated = None
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Subscribe to MQTT events.""" """Subscribe to MQTT events."""
@callback @callback
def update_state(device_id, room, distance): def update_state(device_id, room, distance):
@ -118,7 +115,7 @@ class MQTTRoomSensor(Entity):
or timediff.seconds >= self._timeout: or timediff.seconds >= self._timeout:
update_state(**device) update_state(**device)
return mqtt.async_subscribe( return await mqtt.async_subscribe(
self.hass, self._state_topic, message_received, 1) self.hass, self._state_topic, message_received, 1)
@property @property