Async syntax 5, light & lock & remote & scene & telegram & helpers (#17019)

This commit is contained in:
cdce8p 2018-10-01 08:56:50 +02:00 committed by Paulus Schoutsen
parent 9e4c8f45d6
commit 3b5e5cbcd6
28 changed files with 112 additions and 195 deletions

View File

@ -5,7 +5,6 @@ For more details about this platform, please refer to the documentation.
https://home-assistant.io/components/light.ads/ https://home-assistant.io/components/light.ads/
""" """
import asyncio
import logging import logging
import voluptuous as vol import voluptuous as vol
from homeassistant.components.light import Light, ATTR_BRIGHTNESS, \ from homeassistant.components.light import Light, ATTR_BRIGHTNESS, \
@ -50,8 +49,7 @@ class AdsLight(Light):
self.ads_var_enable = ads_var_enable self.ads_var_enable = ads_var_enable
self.ads_var_brightness = ads_var_brightness self.ads_var_brightness = ads_var_brightness
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Register device notification.""" """Register device notification."""
def update_on_state(name, value): def update_on_state(name, value):
"""Handle device notifications for state.""" """Handle device notifications for state."""

View File

@ -4,7 +4,6 @@ Support for Insteon lights via PowerLinc Modem.
For more details about this component, please refer to the documentation at For more details about this component, please refer to the documentation at
https://home-assistant.io/components/light.insteon/ https://home-assistant.io/components/light.insteon/
""" """
import asyncio
import logging import logging
from homeassistant.components.insteon import InsteonEntity from homeassistant.components.insteon import InsteonEntity
@ -18,8 +17,7 @@ DEPENDENCIES = ['insteon']
MAX_BRIGHTNESS = 255 MAX_BRIGHTNESS = 255
@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 the Insteon component.""" """Set up the Insteon component."""
insteon_modem = hass.data['insteon'].get('modem') insteon_modem = hass.data['insteon'].get('modem')
@ -55,8 +53,7 @@ class InsteonDimmerDevice(InsteonEntity, Light):
"""Flag supported features.""" """Flag supported features."""
return SUPPORT_BRIGHTNESS return SUPPORT_BRIGHTNESS
@asyncio.coroutine async def async_turn_on(self, **kwargs):
def async_turn_on(self, **kwargs):
"""Turn device on.""" """Turn device on."""
if ATTR_BRIGHTNESS in kwargs: if ATTR_BRIGHTNESS in kwargs:
brightness = int(kwargs[ATTR_BRIGHTNESS]) brightness = int(kwargs[ATTR_BRIGHTNESS])
@ -64,7 +61,6 @@ class InsteonDimmerDevice(InsteonEntity, Light):
else: else:
self._insteon_device_state.on() self._insteon_device_state.on()
@asyncio.coroutine async def async_turn_off(self, **kwargs):
def async_turn_off(self, **kwargs):
"""Turn device off.""" """Turn device off."""
self._insteon_device_state.off() self._insteon_device_state.off()

View File

@ -4,7 +4,6 @@ Support for LimitlessLED bulbs.
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/light.limitlessled/ https://home-assistant.io/components/light.limitlessled/
""" """
import asyncio
import logging import logging
import voluptuous as vol import voluptuous as vol
@ -188,10 +187,9 @@ class LimitlessLEDGroup(Light):
self._color = None self._color = None
self._effect = None self._effect = None
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Handle entity about to be added to hass event.""" """Handle entity about to be added to hass event."""
last_state = yield from async_get_last_state(self.hass, self.entity_id) last_state = await async_get_last_state(self.hass, self.entity_id)
if last_state: if last_state:
self._is_on = (last_state.state == STATE_ON) self._is_on = (last_state.state == STATE_ON)
self._brightness = last_state.attributes.get('brightness') self._brightness = last_state.attributes.get('brightness')

View File

@ -4,7 +4,6 @@ Support for Lutron Caseta lights.
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/light.lutron_caseta/ https://home-assistant.io/components/light.lutron_caseta/
""" """
import asyncio
import logging import logging
from homeassistant.components.light import ( from homeassistant.components.light import (
@ -19,8 +18,7 @@ _LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['lutron_caseta'] DEPENDENCIES = ['lutron_caseta']
@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 the Lutron Caseta lights.""" """Set up the Lutron Caseta lights."""
devs = [] devs = []
@ -46,15 +44,13 @@ class LutronCasetaLight(LutronCasetaDevice, Light):
"""Return the brightness of the light.""" """Return the brightness of the light."""
return to_hass_level(self._state["current_state"]) return to_hass_level(self._state["current_state"])
@asyncio.coroutine async def async_turn_on(self, **kwargs):
def async_turn_on(self, **kwargs):
"""Turn the light on.""" """Turn the light on."""
brightness = kwargs.get(ATTR_BRIGHTNESS, 255) brightness = kwargs.get(ATTR_BRIGHTNESS, 255)
self._smartbridge.set_value(self._device_id, self._smartbridge.set_value(self._device_id,
to_lutron_level(brightness)) to_lutron_level(brightness))
@asyncio.coroutine async def async_turn_off(self, **kwargs):
def async_turn_off(self, **kwargs):
"""Turn the light off.""" """Turn the light off."""
self._smartbridge.set_value(self._device_id, 0) self._smartbridge.set_value(self._device_id, 0)
@ -63,8 +59,7 @@ class LutronCasetaLight(LutronCasetaDevice, Light):
"""Return true if device is on.""" """Return true if device is on."""
return self._state["current_state"] > 0 return self._state["current_state"] > 0
@asyncio.coroutine async def async_update(self):
def async_update(self):
"""Call when forcing a refresh of the device.""" """Call when forcing a refresh of the device."""
self._state = self._smartbridge.get_device_by_id(self._device_id) self._state = self._smartbridge.get_device_by_id(self._device_id)
_LOGGER.debug(self._state) _LOGGER.debug(self._state)

View File

@ -4,7 +4,6 @@ Support for Rflink lights.
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/light.rflink/ https://home-assistant.io/components/light.rflink/
""" """
import asyncio
import logging import logging
from homeassistant.components.light import ( from homeassistant.components.light import (
@ -155,14 +154,12 @@ def devices_from_config(domain_config, hass=None):
return devices return devices
@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 the Rflink light platform.""" """Set up the Rflink light platform."""
async_add_entities(devices_from_config(config, hass)) async_add_entities(devices_from_config(config, hass))
@asyncio.coroutine async def add_new_device(event):
def add_new_device(event):
"""Check if device is known, otherwise add to list of known devices.""" """Check if device is known, otherwise add to list of known devices."""
device_id = event[EVENT_KEY_ID] device_id = event[EVENT_KEY_ID]
@ -195,15 +192,14 @@ class DimmableRflinkLight(SwitchableRflinkDevice, Light):
_brightness = 255 _brightness = 255
@asyncio.coroutine async def async_turn_on(self, **kwargs):
def async_turn_on(self, **kwargs):
"""Turn the device on.""" """Turn the device on."""
if ATTR_BRIGHTNESS in kwargs: if ATTR_BRIGHTNESS in kwargs:
# rflink only support 16 brightness levels # rflink only support 16 brightness levels
self._brightness = int(kwargs[ATTR_BRIGHTNESS] / 17) * 17 self._brightness = int(kwargs[ATTR_BRIGHTNESS] / 17) * 17
# Turn on light at the requested dim level # Turn on light at the requested dim level
yield from self._async_handle_command('dim', self._brightness) await self._async_handle_command('dim', self._brightness)
@property @property
def brightness(self): def brightness(self):
@ -233,8 +229,7 @@ class HybridRflinkLight(SwitchableRflinkDevice, Light):
_brightness = 255 _brightness = 255
@asyncio.coroutine async def async_turn_on(self, **kwargs):
def async_turn_on(self, **kwargs):
"""Turn the device on and set dim level.""" """Turn the device on and set dim level."""
if ATTR_BRIGHTNESS in kwargs: if ATTR_BRIGHTNESS in kwargs:
# rflink only support 16 brightness levels # rflink only support 16 brightness levels
@ -242,12 +237,12 @@ class HybridRflinkLight(SwitchableRflinkDevice, Light):
# if receiver supports dimming this will turn on the light # if receiver supports dimming this will turn on the light
# at the requested dim level # at the requested dim level
yield from self._async_handle_command('dim', self._brightness) await self._async_handle_command('dim', self._brightness)
# if the receiving device does not support dimlevel this # if the receiving device does not support dimlevel this
# will ensure it is turned on when full brightness is set # will ensure it is turned on when full brightness is set
if self._brightness == 255: if self._brightness == 255:
yield from self._async_handle_command('turn_on') await self._async_handle_command('turn_on')
@property @property
def brightness(self): def brightness(self):
@ -284,12 +279,10 @@ class ToggleRflinkLight(SwitchableRflinkDevice, Light):
# if the state is true, it gets set as false # if the state is true, it gets set as false
self._state = self._state in [STATE_UNKNOWN, False] self._state = self._state in [STATE_UNKNOWN, False]
@asyncio.coroutine async def async_turn_on(self, **kwargs):
def async_turn_on(self, **kwargs):
"""Turn the device on.""" """Turn the device on."""
yield from self._async_handle_command('toggle') await self._async_handle_command('toggle')
@asyncio.coroutine async def async_turn_off(self, **kwargs):
def async_turn_off(self, **kwargs):
"""Turn the device off.""" """Turn the device off."""
yield from self._async_handle_command('toggle') await self._async_handle_command('toggle')

View File

@ -5,7 +5,6 @@ For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/light.template/ https://home-assistant.io/components/light.template/
""" """
import logging import logging
import asyncio
import voluptuous as vol import voluptuous as vol
@ -49,8 +48,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
}) })
@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 the Template Lights.""" """Set up the Template Lights."""
lights = [] lights = []
@ -182,8 +180,7 @@ class LightTemplate(Light):
"""Return the entity picture to use in the frontend, if any.""" """Return the entity picture to use in the frontend, if any."""
return self._entity_picture return self._entity_picture
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Register callbacks.""" """Register callbacks."""
@callback @callback
def template_light_state_listener(entity, old_state, new_state): def template_light_state_listener(entity, old_state, new_state):
@ -203,8 +200,7 @@ class LightTemplate(Light):
self.hass.bus.async_listen_once( self.hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_START, template_light_startup) EVENT_HOMEASSISTANT_START, template_light_startup)
@asyncio.coroutine async def async_turn_on(self, **kwargs):
def async_turn_on(self, **kwargs):
"""Turn the light on.""" """Turn the light on."""
optimistic_set = False optimistic_set = False
# set optimistic states # set optimistic states
@ -222,21 +218,19 @@ class LightTemplate(Light):
self.hass.async_add_job(self._level_script.async_run( self.hass.async_add_job(self._level_script.async_run(
{"brightness": kwargs[ATTR_BRIGHTNESS]})) {"brightness": kwargs[ATTR_BRIGHTNESS]}))
else: else:
yield from self._on_script.async_run() await self._on_script.async_run()
if optimistic_set: if optimistic_set:
self.async_schedule_update_ha_state() self.async_schedule_update_ha_state()
@asyncio.coroutine async def async_turn_off(self, **kwargs):
def async_turn_off(self, **kwargs):
"""Turn the light off.""" """Turn the light off."""
yield from self._off_script.async_run() await self._off_script.async_run()
if self._template is None: if self._template is None:
self._state = False self._state = False
self.async_schedule_update_ha_state() self.async_schedule_update_ha_state()
@asyncio.coroutine async def async_update(self):
def async_update(self):
"""Update the state from the template.""" """Update the state from the template."""
if self._template is not None: if self._template is not None:
try: try:

View File

@ -4,7 +4,6 @@ Support for Belkin WeMo lights.
For more details about this component, please refer to the documentation at For more details about this component, please refer to the documentation at
https://home-assistant.io/components/light.wemo/ https://home-assistant.io/components/light.wemo/
""" """
import asyncio
import logging import logging
from datetime import timedelta from datetime import timedelta
import requests import requests
@ -160,13 +159,12 @@ class WemoDimmer(Light):
self._brightness = None self._brightness = None
self._state = None self._state = None
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Register update callback.""" """Register update callback."""
wemo = self.hass.components.wemo wemo = self.hass.components.wemo
# The register method uses a threading condition, so call via executor. # The register method uses a threading condition, so call via executor.
# and yield from to wait until the task is done. # and await to wait until the task is done.
yield from self.hass.async_add_job( await self.hass.async_add_job(
wemo.SUBSCRIPTION_REGISTRY.register, self.wemo) wemo.SUBSCRIPTION_REGISTRY.register, self.wemo)
# The on method just appends to a defaultdict list. # The on method just appends to a defaultdict list.
wemo.SUBSCRIPTION_REGISTRY.on(self.wemo, None, self._update_callback) wemo.SUBSCRIPTION_REGISTRY.on(self.wemo, None, self._update_callback)

View File

@ -4,7 +4,6 @@ Support for Wink lights.
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/light.wink/ https://home-assistant.io/components/light.wink/
""" """
import asyncio
from homeassistant.components.light import ( from homeassistant.components.light import (
ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, SUPPORT_BRIGHTNESS, ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, SUPPORT_BRIGHTNESS,
@ -34,8 +33,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
class WinkLight(WinkDevice, Light): class WinkLight(WinkDevice, Light):
"""Representation of a Wink light.""" """Representation of a Wink light."""
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Call when entity is added to hass.""" """Call when entity is added to hass."""
self.hass.data[DOMAIN]['entities']['light'].append(self) self.hass.data[DOMAIN]['entities']['light'].append(self)

View File

@ -4,7 +4,6 @@ Component to interface with various locks that can be controlled remotely.
For more details about this component, please refer to the documentation For more details about this component, please refer to the documentation
at https://home-assistant.io/components/lock/ at https://home-assistant.io/components/lock/
""" """
import asyncio
from datetime import timedelta from datetime import timedelta
import functools as ft import functools as ft
import logging import logging
@ -57,13 +56,12 @@ def is_locked(hass, entity_id=None):
return hass.states.is_state(entity_id, STATE_LOCKED) return hass.states.is_state(entity_id, STATE_LOCKED)
@asyncio.coroutine async def async_setup(hass, config):
def async_setup(hass, config):
"""Track states and offer events for locks.""" """Track states and offer events for locks."""
component = EntityComponent( component = EntityComponent(
_LOGGER, DOMAIN, hass, SCAN_INTERVAL, GROUP_NAME_ALL_LOCKS) _LOGGER, DOMAIN, hass, SCAN_INTERVAL, GROUP_NAME_ALL_LOCKS)
yield from component.async_setup(config) await component.async_setup(config)
component.async_register_entity_service( component.async_register_entity_service(
SERVICE_UNLOCK, LOCK_SERVICE_SCHEMA, SERVICE_UNLOCK, LOCK_SERVICE_SCHEMA,

View File

@ -4,7 +4,6 @@ Support for BMW cars with BMW ConnectedDrive.
For more details about this component, please refer to the documentation at For more details about this component, please refer to the documentation at
https://home-assistant.io/components/lock.bmw_connected_drive/ https://home-assistant.io/components/lock.bmw_connected_drive/
""" """
import asyncio
import logging import logging
from homeassistant.components.bmw_connected_drive import DOMAIN as BMW_DOMAIN from homeassistant.components.bmw_connected_drive import DOMAIN as BMW_DOMAIN
@ -111,8 +110,7 @@ class BMWLock(LockDevice):
"""Schedule a state update.""" """Schedule a state update."""
self.schedule_update_ha_state(True) self.schedule_update_ha_state(True)
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Add callback after being added to hass. """Add callback after being added to hass.
Show latest data after startup. Show latest data after startup.

View File

@ -4,7 +4,6 @@ Support for MQTT locks.
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/lock.mqtt/ https://home-assistant.io/components/lock.mqtt/
""" """
import asyncio
import logging import logging
import voluptuous as vol import voluptuous as vol
@ -41,8 +40,7 @@ PLATFORM_SCHEMA = mqtt.MQTT_RW_PLATFORM_SCHEMA.extend({
}).extend(mqtt.MQTT_AVAILABILITY_SCHEMA.schema) }).extend(mqtt.MQTT_AVAILABILITY_SCHEMA.schema)
@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 the MQTT lock.""" """Set up the MQTT lock."""
if discovery_info is not None: if discovery_info is not None:
@ -96,11 +94,10 @@ class MqttLock(MqttAvailability, MqttDiscoveryUpdate, LockDevice):
self._template = value_template self._template = value_template
self._discovery_hash = discovery_hash self._discovery_hash = discovery_hash
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Subscribe to MQTT events.""" """Subscribe to MQTT events."""
yield from MqttAvailability.async_added_to_hass(self) await MqttAvailability.async_added_to_hass(self)
yield from MqttDiscoveryUpdate.async_added_to_hass(self) await MqttDiscoveryUpdate.async_added_to_hass(self)
@callback @callback
def message_received(topic, payload, qos): def message_received(topic, payload, qos):
@ -119,7 +116,7 @@ class MqttLock(MqttAvailability, MqttDiscoveryUpdate, LockDevice):
# Force into optimistic mode. # Force into optimistic mode.
self._optimistic = True self._optimistic = True
else: else:
yield from mqtt.async_subscribe( await mqtt.async_subscribe(
self.hass, self._state_topic, message_received, self._qos) self.hass, self._state_topic, message_received, self._qos)
@property @property
@ -142,8 +139,7 @@ class MqttLock(MqttAvailability, MqttDiscoveryUpdate, LockDevice):
"""Return true if we do optimistic updates.""" """Return true if we do optimistic updates."""
return self._optimistic return self._optimistic
@asyncio.coroutine async def async_lock(self, **kwargs):
def async_lock(self, **kwargs):
"""Lock the device. """Lock the device.
This method is a coroutine. This method is a coroutine.
@ -156,8 +152,7 @@ class MqttLock(MqttAvailability, MqttDiscoveryUpdate, LockDevice):
self._state = True self._state = True
self.async_schedule_update_ha_state() self.async_schedule_update_ha_state()
@asyncio.coroutine async def async_unlock(self, **kwargs):
def async_unlock(self, **kwargs):
"""Unlock the device. """Unlock the device.
This method is a coroutine. This method is a coroutine.

View File

@ -4,7 +4,6 @@ Nuki.io lock platform.
For more details about this platform, please refer to the documentation For more details about this platform, please refer to the documentation
https://home-assistant.io/components/lock.nuki/ https://home-assistant.io/components/lock.nuki/
""" """
import asyncio
from datetime import timedelta from datetime import timedelta
import logging import logging
@ -92,8 +91,7 @@ class NukiLock(LockDevice):
self._name = nuki_lock.name self._name = nuki_lock.name
self._battery_critical = nuki_lock.battery_critical self._battery_critical = nuki_lock.battery_critical
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Call when entity is added to hass.""" """Call when entity is added to hass."""
if NUKI_DATA not in self.hass.data: if NUKI_DATA not in self.hass.data:
self.hass.data[NUKI_DATA] = {} self.hass.data[NUKI_DATA] = {}

View File

@ -4,7 +4,6 @@ Support for Wink locks.
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/lock.wink/ https://home-assistant.io/components/lock.wink/
""" """
import asyncio
import logging import logging
import voluptuous as vol import voluptuous as vol
@ -131,8 +130,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
class WinkLockDevice(WinkDevice, LockDevice): class WinkLockDevice(WinkDevice, LockDevice):
"""Representation of a Wink lock.""" """Representation of a Wink lock."""
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Call when entity is added to hass.""" """Call when entity is added to hass."""
self.hass.data[DOMAIN]['entities']['lock'].append(self) self.hass.data[DOMAIN]['entities']['lock'].append(self)

View File

@ -4,7 +4,6 @@ Z-Wave platform that handles simple door locks.
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/lock.zwave/ https://home-assistant.io/components/lock.zwave/
""" """
import asyncio
import logging import logging
import voluptuous as vol import voluptuous as vol
@ -119,11 +118,10 @@ CLEAR_USERCODE_SCHEMA = vol.Schema({
}) })
@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 the Z-Wave Lock platform.""" """Set up the Z-Wave Lock platform."""
yield from zwave.async_setup_platform( await zwave.async_setup_platform(
hass, config, async_add_entities, discovery_info) hass, config, async_add_entities, discovery_info)
network = hass.data[zwave.const.DATA_NETWORK] network = hass.data[zwave.const.DATA_NETWORK]

View File

@ -4,7 +4,6 @@ Component to interface with universal remote control devices.
For more details about this component, please refer to the documentation For more details about this component, please refer to the documentation
at https://home-assistant.io/components/remote/ at https://home-assistant.io/components/remote/
""" """
import asyncio
from datetime import timedelta from datetime import timedelta
import functools as ft import functools as ft
import logging import logging
@ -70,12 +69,11 @@ def is_on(hass, entity_id=None):
return hass.states.is_state(entity_id, STATE_ON) return hass.states.is_state(entity_id, STATE_ON)
@asyncio.coroutine async def async_setup(hass, config):
def async_setup(hass, config):
"""Track states and offer events for remotes.""" """Track states and offer events for remotes."""
component = EntityComponent( component = EntityComponent(
_LOGGER, DOMAIN, hass, SCAN_INTERVAL, GROUP_NAME_ALL_REMOTES) _LOGGER, DOMAIN, hass, SCAN_INTERVAL, GROUP_NAME_ALL_REMOTES)
yield from component.async_setup(config) await component.async_setup(config)
component.async_register_entity_service( component.async_register_entity_service(
SERVICE_TURN_OFF, REMOTE_SERVICE_ACTIVITY_SCHEMA, SERVICE_TURN_OFF, REMOTE_SERVICE_ACTIVITY_SCHEMA,

View File

@ -4,7 +4,6 @@ Remote control support for Apple TV.
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/remote.apple_tv/ https://home-assistant.io/components/remote.apple_tv/
""" """
import asyncio
from homeassistant.components.apple_tv import ( from homeassistant.components.apple_tv import (
ATTR_ATV, ATTR_POWER, DATA_APPLE_TV) ATTR_ATV, ATTR_POWER, DATA_APPLE_TV)
@ -15,8 +14,7 @@ from homeassistant.const import (CONF_NAME, CONF_HOST)
DEPENDENCIES = ['apple_tv'] DEPENDENCIES = ['apple_tv']
@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 the Apple TV remote platform.""" """Set up the Apple TV remote platform."""
if not discovery_info: if not discovery_info:
@ -59,16 +57,14 @@ class AppleTVRemote(remote.RemoteDevice):
"""No polling needed for Apple TV.""" """No polling needed for Apple TV."""
return False return False
@asyncio.coroutine async def async_turn_on(self, **kwargs):
def async_turn_on(self, **kwargs):
"""Turn the device on. """Turn the device on.
This method is a coroutine. This method is a coroutine.
""" """
self._power.set_power_on(True) self._power.set_power_on(True)
@asyncio.coroutine async def async_turn_off(self, **kwargs):
def async_turn_off(self, **kwargs):
"""Turn the device off. """Turn the device off.
This method is a coroutine. This method is a coroutine.
@ -81,12 +77,11 @@ class AppleTVRemote(remote.RemoteDevice):
This method must be run in the event loop and returns a coroutine. This method must be run in the event loop and returns a coroutine.
""" """
# Send commands in specified order but schedule only one coroutine # Send commands in specified order but schedule only one coroutine
@asyncio.coroutine async def _send_commands():
def _send_commands():
for single_command in command: for single_command in command:
if not hasattr(self._atv.remote_control, single_command): if not hasattr(self._atv.remote_control, single_command):
continue continue
yield from getattr(self._atv.remote_control, single_command)() await getattr(self._atv.remote_control, single_command)()
return _send_commands() return _send_commands()

View File

@ -4,7 +4,6 @@ Support for Harmony Hub devices.
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/remote.harmony/ https://home-assistant.io/components/remote.harmony/
""" """
import asyncio
import logging import logging
import time import time
@ -152,8 +151,7 @@ class HarmonyRemote(remote.RemoteDevice):
pyharmony.ha_write_config_file(self._config, self._config_path) pyharmony.ha_write_config_file(self._config, self._config_path)
self._delay_secs = delay_secs self._delay_secs = delay_secs
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Complete the initialization.""" """Complete the initialization."""
self.hass.bus.async_listen_once( self.hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, EVENT_HOMEASSISTANT_STOP,

View File

@ -61,8 +61,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
}, 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 the Xiaomi IR Remote (Chuangmi IR) platform.""" """Set up the Xiaomi IR Remote (Chuangmi IR) platform."""
from miio import ChuangmiIr, DeviceException from miio import ChuangmiIr, DeviceException
@ -109,8 +108,7 @@ def async_setup_platform(hass, config, async_add_entities,
async_add_entities([xiaomi_miio_remote]) async_add_entities([xiaomi_miio_remote])
@asyncio.coroutine async def async_service_handler(service):
def async_service_handler(service):
"""Handle a learn command.""" """Handle a learn command."""
if service.service != SERVICE_LEARN: if service.service != SERVICE_LEARN:
_LOGGER.error("We should not handle service: %s", service.service) _LOGGER.error("We should not handle service: %s", service.service)
@ -130,14 +128,14 @@ def async_setup_platform(hass, config, async_add_entities,
slot = service.data.get(CONF_SLOT, entity.slot) slot = service.data.get(CONF_SLOT, entity.slot)
yield from hass.async_add_job(device.learn, slot) await hass.async_add_job(device.learn, slot)
timeout = service.data.get(CONF_TIMEOUT, entity.timeout) timeout = service.data.get(CONF_TIMEOUT, entity.timeout)
_LOGGER.info("Press the key you want Home Assistant to learn") _LOGGER.info("Press the key you want Home Assistant to learn")
start_time = utcnow() start_time = utcnow()
while (utcnow() - start_time) < timedelta(seconds=timeout): while (utcnow() - start_time) < timedelta(seconds=timeout):
message = yield from hass.async_add_job( message = await hass.async_add_job(
device.read, slot) device.read, slot)
_LOGGER.debug("Message received from device: '%s'", message) _LOGGER.debug("Message received from device: '%s'", message)
@ -150,9 +148,9 @@ def async_setup_platform(hass, config, async_add_entities,
if ('error' in message and if ('error' in message and
message['error']['message'] == "learn timeout"): message['error']['message'] == "learn timeout"):
yield from hass.async_add_job(device.learn, slot) await hass.async_add_job(device.learn, slot)
yield from asyncio.sleep(1, loop=hass.loop) await asyncio.sleep(1, loop=hass.loop)
_LOGGER.error("Timeout. No infrared command captured") _LOGGER.error("Timeout. No infrared command captured")
hass.components.persistent_notification.async_create( hass.components.persistent_notification.async_create(
@ -230,14 +228,12 @@ class XiaomiMiioRemote(RemoteDevice):
return {'hidden': 'true'} return {'hidden': 'true'}
return return
@asyncio.coroutine async def async_turn_on(self, **kwargs):
def async_turn_on(self, **kwargs):
"""Turn the device on.""" """Turn the device on."""
_LOGGER.error("Device does not support turn_on, " _LOGGER.error("Device does not support turn_on, "
"please use 'remote.send_command' to send commands.") "please use 'remote.send_command' to send commands.")
@asyncio.coroutine async def async_turn_off(self, **kwargs):
def async_turn_off(self, **kwargs):
"""Turn the device off.""" """Turn the device off."""
_LOGGER.error("Device does not support turn_off, " _LOGGER.error("Device does not support turn_off, "
"please use 'remote.send_command' to send commands.") "please use 'remote.send_command' to send commands.")

View File

@ -4,7 +4,6 @@ Allow users to set and activate scenes.
For more details about this component, please refer to the documentation at For more details about this component, please refer to the documentation at
https://home-assistant.io/components/scene/ https://home-assistant.io/components/scene/
""" """
import asyncio
from collections import namedtuple from collections import namedtuple
import voluptuous as vol import voluptuous as vol
@ -35,8 +34,7 @@ PLATFORM_SCHEMA = vol.Schema({
SCENECONFIG = namedtuple('SceneConfig', [CONF_NAME, STATES]) SCENECONFIG = namedtuple('SceneConfig', [CONF_NAME, STATES])
@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 home assistant scene entries.""" """Set up home assistant scene entries."""
scene_config = config.get(STATES) scene_config = config.get(STATES)
@ -97,8 +95,7 @@ class HomeAssistantScene(Scene):
ATTR_ENTITY_ID: list(self.scene_config.states.keys()), ATTR_ENTITY_ID: list(self.scene_config.states.keys()),
} }
@asyncio.coroutine async def async_activate(self):
def async_activate(self):
"""Activate scene. Try to get entities into requested state.""" """Activate scene. Try to get entities into requested state."""
yield from async_reproduce_state( await async_reproduce_state(
self.hass, self.scene_config.states.values(), True) self.hass, self.scene_config.states.values(), True)

View File

@ -4,7 +4,6 @@ Support for Powerview scenes from a Powerview hub.
For more details about this component, please refer to the documentation at For more details about this component, please refer to the documentation at
https://home-assistant.io/components/scene.hunterdouglas_powerview/ https://home-assistant.io/components/scene.hunterdouglas_powerview/
""" """
import asyncio
import logging import logging
import voluptuous as vol import voluptuous as vol
@ -36,8 +35,7 @@ ROOM_ID_IN_SCENE = 'roomId'
STATE_ATTRIBUTE_ROOM_NAME = 'roomName' STATE_ATTRIBUTE_ROOM_NAME = 'roomName'
@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 home assistant scene entries.""" """Set up home assistant scene entries."""
# from aiopvapi.hub import Hub # from aiopvapi.hub import Hub
@ -48,9 +46,9 @@ def async_setup_platform(hass, config, async_add_entities,
hub_address = config.get(HUB_ADDRESS) hub_address = config.get(HUB_ADDRESS)
websession = async_get_clientsession(hass) websession = async_get_clientsession(hass)
_scenes = yield from Scenes( _scenes = await Scenes(
hub_address, hass.loop, websession).get_resources() hub_address, hass.loop, websession).get_resources()
_rooms = yield from Rooms( _rooms = await Rooms(
hub_address, hass.loop, websession).get_resources() hub_address, hass.loop, websession).get_resources()
if not _scenes or not _rooms: if not _scenes or not _rooms:

View File

@ -29,8 +29,7 @@ PLATFORM_SCHEMA = vol.Schema({
}) })
@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 the scenes stored in the LIFX Cloud.""" """Set up the scenes stored in the LIFX Cloud."""
token = config.get(CONF_TOKEN) token = config.get(CONF_TOKEN)
@ -45,7 +44,7 @@ def async_setup_platform(hass, config, async_add_entities,
try: try:
httpsession = async_get_clientsession(hass) httpsession = async_get_clientsession(hass)
with async_timeout.timeout(timeout, loop=hass.loop): with async_timeout.timeout(timeout, loop=hass.loop):
scenes_resp = yield from httpsession.get(url, headers=headers) scenes_resp = await httpsession.get(url, headers=headers)
except (asyncio.TimeoutError, aiohttp.ClientError): except (asyncio.TimeoutError, aiohttp.ClientError):
_LOGGER.exception("Error on %s", url) _LOGGER.exception("Error on %s", url)
@ -53,7 +52,7 @@ def async_setup_platform(hass, config, async_add_entities,
status = scenes_resp.status status = scenes_resp.status
if status == 200: if status == 200:
data = yield from scenes_resp.json() data = await scenes_resp.json()
devices = [] devices = []
for scene in data: for scene in data:
devices.append(LifxCloudScene(hass, headers, timeout, scene)) devices.append(LifxCloudScene(hass, headers, timeout, scene))
@ -83,15 +82,14 @@ class LifxCloudScene(Scene):
"""Return the name of the scene.""" """Return the name of the scene."""
return self._name return self._name
@asyncio.coroutine async def async_activate(self):
def async_activate(self):
"""Activate the scene.""" """Activate the scene."""
url = LIFX_API_URL.format('scenes/scene_id:%s/activate' % self._uuid) url = LIFX_API_URL.format('scenes/scene_id:%s/activate' % self._uuid)
try: try:
httpsession = async_get_clientsession(self.hass) httpsession = async_get_clientsession(self.hass)
with async_timeout.timeout(self._timeout, loop=self.hass.loop): with async_timeout.timeout(self._timeout, loop=self.hass.loop):
yield from httpsession.put(url, headers=self._headers) await httpsession.put(url, headers=self._headers)
except (asyncio.TimeoutError, aiohttp.ClientError): except (asyncio.TimeoutError, aiohttp.ClientError):
_LOGGER.exception("Error on %s", url) _LOGGER.exception("Error on %s", url)

View File

@ -4,7 +4,6 @@ Support for Lutron Caseta scenes.
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/scene.lutron_caseta/ https://home-assistant.io/components/scene.lutron_caseta/
""" """
import asyncio
import logging import logging
from homeassistant.components.lutron_caseta import LUTRON_CASETA_SMARTBRIDGE from homeassistant.components.lutron_caseta import LUTRON_CASETA_SMARTBRIDGE
@ -15,8 +14,7 @@ _LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['lutron_caseta'] DEPENDENCIES = ['lutron_caseta']
@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 the Lutron Caseta lights.""" """Set up the Lutron Caseta lights."""
devs = [] devs = []
@ -43,7 +41,6 @@ class LutronCasetaScene(Scene):
"""Return the name of the scene.""" """Return the name of the scene."""
return self._scene_name return self._scene_name
@asyncio.coroutine async def async_activate(self):
def async_activate(self):
"""Activate the scene.""" """Activate the scene."""
self._bridge.activate_scene(self._scene_id) self._bridge.activate_scene(self._scene_id)

View File

@ -4,7 +4,6 @@ Support for Wink scenes.
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/scene.wink/ https://home-assistant.io/components/scene.wink/
""" """
import asyncio
import logging import logging
from homeassistant.components.scene import Scene from homeassistant.components.scene import Scene
@ -33,8 +32,7 @@ class WinkScene(WinkDevice, Scene):
super().__init__(wink, hass) super().__init__(wink, hass)
hass.data[DOMAIN]['entities']['scene'].append(self) hass.data[DOMAIN]['entities']['scene'].append(self)
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Call when entity is added to hass.""" """Call when entity is added to hass."""
self.hass.data[DOMAIN]['entities']['scene'].append(self) self.hass.data[DOMAIN]['entities']['scene'].append(self)

View File

@ -4,7 +4,6 @@ Component to send and receive Telegram messages.
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/telegram_bot/ https://home-assistant.io/components/telegram_bot/
""" """
import asyncio
import io import io
from functools import partial from functools import partial
import logging import logging
@ -210,8 +209,7 @@ def load_data(hass, url=None, filepath=None, username=None, password=None,
return None return None
@asyncio.coroutine async def async_setup(hass, config):
def async_setup(hass, config):
"""Set up the Telegram bot component.""" """Set up the Telegram bot component."""
if not config[DOMAIN]: if not config[DOMAIN]:
return False return False
@ -220,7 +218,7 @@ def async_setup(hass, config):
p_type = p_config.get(CONF_PLATFORM) p_type = p_config.get(CONF_PLATFORM)
platform = yield from async_prepare_setup_platform( platform = await async_prepare_setup_platform(
hass, config, DOMAIN, p_type) hass, config, DOMAIN, p_type)
if platform is None: if platform is None:
@ -228,7 +226,7 @@ def async_setup(hass, config):
_LOGGER.info("Setting up %s.%s", DOMAIN, p_type) _LOGGER.info("Setting up %s.%s", DOMAIN, p_type)
try: try:
receiver_service = yield from \ receiver_service = await \
platform.async_setup_platform(hass, p_config) platform.async_setup_platform(hass, p_config)
if receiver_service is False: if receiver_service is False:
_LOGGER.error( _LOGGER.error(
@ -247,8 +245,7 @@ def async_setup(hass, config):
p_config.get(ATTR_PARSER) p_config.get(ATTR_PARSER)
) )
@asyncio.coroutine async def async_send_telegram_message(service):
def async_send_telegram_message(service):
"""Handle sending Telegram Bot message service calls.""" """Handle sending Telegram Bot message service calls."""
def _render_template_attr(data, attribute): def _render_template_attr(data, attribute):
attribute_templ = data.get(attribute) attribute_templ = data.get(attribute)
@ -274,23 +271,23 @@ def async_setup(hass, config):
_LOGGER.debug("New telegram message %s: %s", msgtype, kwargs) _LOGGER.debug("New telegram message %s: %s", msgtype, kwargs)
if msgtype == SERVICE_SEND_MESSAGE: if msgtype == SERVICE_SEND_MESSAGE:
yield from hass.async_add_job( await hass.async_add_job(
partial(notify_service.send_message, **kwargs)) partial(notify_service.send_message, **kwargs))
elif msgtype in [SERVICE_SEND_PHOTO, SERVICE_SEND_STICKER, elif msgtype in [SERVICE_SEND_PHOTO, SERVICE_SEND_STICKER,
SERVICE_SEND_VIDEO, SERVICE_SEND_DOCUMENT]: SERVICE_SEND_VIDEO, SERVICE_SEND_DOCUMENT]:
yield from hass.async_add_job( await hass.async_add_job(
partial(notify_service.send_file, msgtype, **kwargs)) partial(notify_service.send_file, msgtype, **kwargs))
elif msgtype == SERVICE_SEND_LOCATION: elif msgtype == SERVICE_SEND_LOCATION:
yield from hass.async_add_job( await hass.async_add_job(
partial(notify_service.send_location, **kwargs)) partial(notify_service.send_location, **kwargs))
elif msgtype == SERVICE_ANSWER_CALLBACK_QUERY: elif msgtype == SERVICE_ANSWER_CALLBACK_QUERY:
yield from hass.async_add_job( await hass.async_add_job(
partial(notify_service.answer_callback_query, **kwargs)) partial(notify_service.answer_callback_query, **kwargs))
elif msgtype == SERVICE_DELETE_MESSAGE: elif msgtype == SERVICE_DELETE_MESSAGE:
yield from hass.async_add_job( await hass.async_add_job(
partial(notify_service.delete_message, **kwargs)) partial(notify_service.delete_message, **kwargs))
else: else:
yield from hass.async_add_job( await hass.async_add_job(
partial(notify_service.edit_message, msgtype, **kwargs)) partial(notify_service.edit_message, msgtype, **kwargs))
# Register notification services # Register notification services

View File

@ -4,7 +4,6 @@ Telegram bot implementation to send messages only.
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/telegram_bot.broadcast/ https://home-assistant.io/components/telegram_bot.broadcast/
""" """
import asyncio
import logging import logging
from homeassistant.components.telegram_bot import ( from homeassistant.components.telegram_bot import (
@ -16,14 +15,13 @@ _LOGGER = logging.getLogger(__name__)
PLATFORM_SCHEMA = TELEGRAM_PLATFORM_SCHEMA PLATFORM_SCHEMA = TELEGRAM_PLATFORM_SCHEMA
@asyncio.coroutine async def async_setup_platform(hass, config):
def async_setup_platform(hass, config):
"""Set up the Telegram broadcast platform.""" """Set up the Telegram broadcast platform."""
# Check the API key works # Check the API key works
bot = initialize_bot(config) bot = initialize_bot(config)
bot_config = yield from hass.async_add_job(bot.getMe) bot_config = await hass.async_add_job(bot.getMe)
_LOGGER.debug("Telegram broadcast platform setup with bot %s", _LOGGER.debug("Telegram broadcast platform setup with bot %s",
bot_config['username']) bot_config['username'])
return True return True

View File

@ -4,7 +4,6 @@ Telegram bot polling implementation.
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/telegram_bot.polling/ https://home-assistant.io/components/telegram_bot.polling/
""" """
import asyncio
import logging import logging
from homeassistant.components.telegram_bot import ( from homeassistant.components.telegram_bot import (
@ -20,8 +19,7 @@ _LOGGER = logging.getLogger(__name__)
PLATFORM_SCHEMA = TELEGRAM_PLATFORM_SCHEMA PLATFORM_SCHEMA = TELEGRAM_PLATFORM_SCHEMA
@asyncio.coroutine async def async_setup_platform(hass, config):
def async_setup_platform(hass, config):
"""Set up the Telegram polling platform.""" """Set up the Telegram polling platform."""
bot = initialize_bot(config) bot = initialize_bot(config)
pol = TelegramPoll(bot, hass, config[CONF_ALLOWED_CHAT_IDS]) pol = TelegramPoll(bot, hass, config[CONF_ALLOWED_CHAT_IDS])

View File

@ -4,7 +4,6 @@ Allows utilizing telegram webhooks.
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/telegram_bot.webhooks/ https://home-assistant.io/components/telegram_bot.webhooks/
""" """
import asyncio
import datetime as dt import datetime as dt
from ipaddress import ip_network from ipaddress import ip_network
import logging import logging
@ -47,13 +46,12 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
}) })
@asyncio.coroutine async def async_setup_platform(hass, config):
def async_setup_platform(hass, config):
"""Set up the Telegram webhooks platform.""" """Set up the Telegram webhooks platform."""
import telegram import telegram
bot = initialize_bot(config) bot = initialize_bot(config)
current_status = yield from hass.async_add_job(bot.getWebhookInfo) current_status = await hass.async_add_job(bot.getWebhookInfo)
base_url = config.get(CONF_URL, hass.config.api.base_url) base_url = config.get(CONF_URL, hass.config.api.base_url)
# Some logging of Bot current status: # Some logging of Bot current status:
@ -81,7 +79,7 @@ def async_setup_platform(hass, config):
retry_num) retry_num)
if current_status and current_status['url'] != handler_url: if current_status and current_status['url'] != handler_url:
result = yield from hass.async_add_job(_try_to_set_webhook) result = await hass.async_add_job(_try_to_set_webhook)
if result: if result:
_LOGGER.info("Set new telegram webhook %s", handler_url) _LOGGER.info("Set new telegram webhook %s", handler_url)
else: else:
@ -108,8 +106,7 @@ class BotPushReceiver(HomeAssistantView, BaseTelegramBotEntity):
BaseTelegramBotEntity.__init__(self, hass, allowed_chat_ids) BaseTelegramBotEntity.__init__(self, hass, allowed_chat_ids)
self.trusted_networks = trusted_networks self.trusted_networks = trusted_networks
@asyncio.coroutine async def post(self, request):
def post(self, request):
"""Accept the POST from telegram.""" """Accept the POST from telegram."""
real_ip = request[KEY_REAL_IP] real_ip = request[KEY_REAL_IP]
if not any(real_ip in net for net in self.trusted_networks): if not any(real_ip in net for net in self.trusted_networks):
@ -117,7 +114,7 @@ class BotPushReceiver(HomeAssistantView, BaseTelegramBotEntity):
return self.json_message('Access denied', HTTP_UNAUTHORIZED) return self.json_message('Access denied', HTTP_UNAUTHORIZED)
try: try:
data = yield from request.json() data = await request.json()
except ValueError: except ValueError:
return self.json_message('Invalid JSON', HTTP_BAD_REQUEST) return self.json_message('Invalid JSON', HTTP_BAD_REQUEST)

View File

@ -1,5 +1,4 @@
"""An abstract class for entities.""" """An abstract class for entities."""
import asyncio
from datetime import timedelta from datetime import timedelta
import logging import logging
import functools as ft import functools as ft
@ -202,8 +201,7 @@ class Entity:
self._context = context self._context = context
self._context_set = dt_util.utcnow() self._context_set = dt_util.utcnow()
@asyncio.coroutine async def async_update_ha_state(self, force_refresh=False):
def async_update_ha_state(self, force_refresh=False):
"""Update Home Assistant with current state of entity. """Update Home Assistant with current state of entity.
If force_refresh == True will update entity before setting state. If force_refresh == True will update entity before setting state.
@ -220,7 +218,7 @@ class Entity:
# update entity data # update entity data
if force_refresh: if force_refresh:
try: try:
yield from self.async_device_update() await self.async_device_update()
except Exception: # pylint: disable=broad-except except Exception: # pylint: disable=broad-except
_LOGGER.exception("Update for %s fails", self.entity_id) _LOGGER.exception("Update for %s fails", self.entity_id)
return return
@ -323,8 +321,7 @@ class Entity:
"""Schedule an update ha state change task.""" """Schedule an update ha state change task."""
self.hass.async_add_job(self.async_update_ha_state(force_refresh)) self.hass.async_add_job(self.async_update_ha_state(force_refresh))
@asyncio.coroutine async def async_device_update(self, warning=True):
def async_device_update(self, warning=True):
"""Process 'update' or 'async_update' from entity. """Process 'update' or 'async_update' from entity.
This method is a coroutine. This method is a coroutine.
@ -335,7 +332,7 @@ class Entity:
# Process update sequential # Process update sequential
if self.parallel_updates: if self.parallel_updates:
yield from self.parallel_updates.acquire() await self.parallel_updates.acquire()
if warning: if warning:
update_warn = self.hass.loop.call_later( update_warn = self.hass.loop.call_later(
@ -347,9 +344,9 @@ class Entity:
try: try:
# pylint: disable=no-member # pylint: disable=no-member
if hasattr(self, 'async_update'): if hasattr(self, 'async_update'):
yield from self.async_update() await self.async_update()
elif hasattr(self, 'update'): elif hasattr(self, 'update'):
yield from self.hass.async_add_job(self.update) await self.hass.async_add_job(self.update)
finally: finally:
self._update_staged = False self._update_staged = False
if warning: if warning: