Async syntax 8/8 (#17022)

* Async syntax 8

* Pylint fixes
This commit is contained in:
cdce8p 2018-10-01 08:52:42 +02:00 committed by Paulus Schoutsen
parent ea7b1e4573
commit 9aaf11de8c
54 changed files with 223 additions and 382 deletions

View File

@ -103,17 +103,14 @@ def reload_core_config(hass):
hass.services.call(ha.DOMAIN, SERVICE_RELOAD_CORE_CONFIG) hass.services.call(ha.DOMAIN, SERVICE_RELOAD_CORE_CONFIG)
@asyncio.coroutine async def async_reload_core_config(hass):
def async_reload_core_config(hass):
"""Reload the core config.""" """Reload the core config."""
yield from hass.services.async_call(ha.DOMAIN, SERVICE_RELOAD_CORE_CONFIG) await hass.services.async_call(ha.DOMAIN, SERVICE_RELOAD_CORE_CONFIG)
@asyncio.coroutine async def async_setup(hass: ha.HomeAssistant, config: dict) -> Awaitable[bool]:
def async_setup(hass: ha.HomeAssistant, config: dict) -> Awaitable[bool]:
"""Set up general services related to Home Assistant.""" """Set up general services related to Home Assistant."""
@asyncio.coroutine async def async_handle_turn_service(service):
def async_handle_turn_service(service):
"""Handle calls to homeassistant.turn_on/off.""" """Handle calls to homeassistant.turn_on/off."""
entity_ids = extract_entity_ids(hass, service) entity_ids = extract_entity_ids(hass, service)
@ -148,7 +145,7 @@ def async_setup(hass: ha.HomeAssistant, config: dict) -> Awaitable[bool]:
tasks.append(hass.services.async_call( tasks.append(hass.services.async_call(
domain, service.service, data, blocking)) domain, service.service, data, blocking))
yield from asyncio.wait(tasks, loop=hass.loop) await asyncio.wait(tasks, loop=hass.loop)
hass.services.async_register( hass.services.async_register(
ha.DOMAIN, SERVICE_TURN_OFF, async_handle_turn_service) ha.DOMAIN, SERVICE_TURN_OFF, async_handle_turn_service)
@ -164,15 +161,14 @@ def async_setup(hass: ha.HomeAssistant, config: dict) -> Awaitable[bool]:
hass.helpers.intent.async_register(intent.ServiceIntentHandler( hass.helpers.intent.async_register(intent.ServiceIntentHandler(
intent.INTENT_TOGGLE, ha.DOMAIN, SERVICE_TOGGLE, "Toggled {}")) intent.INTENT_TOGGLE, ha.DOMAIN, SERVICE_TOGGLE, "Toggled {}"))
@asyncio.coroutine async def async_handle_core_service(call):
def async_handle_core_service(call):
"""Service handler for handling core services.""" """Service handler for handling core services."""
if call.service == SERVICE_HOMEASSISTANT_STOP: if call.service == SERVICE_HOMEASSISTANT_STOP:
hass.async_create_task(hass.async_stop()) hass.async_create_task(hass.async_stop())
return return
try: try:
errors = yield from conf_util.async_check_ha_config_file(hass) errors = await conf_util.async_check_ha_config_file(hass)
except HomeAssistantError: except HomeAssistantError:
return return
@ -193,16 +189,15 @@ def async_setup(hass: ha.HomeAssistant, config: dict) -> Awaitable[bool]:
hass.services.async_register( hass.services.async_register(
ha.DOMAIN, SERVICE_CHECK_CONFIG, async_handle_core_service) ha.DOMAIN, SERVICE_CHECK_CONFIG, async_handle_core_service)
@asyncio.coroutine async def async_handle_reload_config(call):
def async_handle_reload_config(call):
"""Service handler for reloading core config.""" """Service handler for reloading core config."""
try: try:
conf = yield from conf_util.async_hass_config_yaml(hass) conf = await conf_util.async_hass_config_yaml(hass)
except HomeAssistantError as err: except HomeAssistantError as err:
_LOGGER.error(err) _LOGGER.error(err)
return return
yield from conf_util.async_process_ha_core_config( await conf_util.async_process_ha_core_config(
hass, conf.get(ha.DOMAIN) or {}) hass, conf.get(ha.DOMAIN) or {})
hass.services.async_register( hass.services.async_register(

View File

@ -4,7 +4,6 @@ This component provides basic support for Abode Home Security system.
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/abode/ https://home-assistant.io/components/abode/
""" """
import asyncio
import logging import logging
from functools import partial from functools import partial
from requests.exceptions import HTTPError, ConnectTimeout from requests.exceptions import HTTPError, ConnectTimeout
@ -261,8 +260,7 @@ class AbodeDevice(Entity):
self._data = data self._data = data
self._device = device self._device = device
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Subscribe Abode events.""" """Subscribe Abode events."""
self.hass.async_add_job( self.hass.async_add_job(
self._data.abode.events.add_device_callback, self._data.abode.events.add_device_callback,
@ -308,8 +306,7 @@ class AbodeAutomation(Entity):
self._automation = automation self._automation = automation
self._event = event self._event = event
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Subscribe Abode events.""" """Subscribe Abode events."""
if self._event: if self._event:
self.hass.async_add_job( self.hass.async_add_job(

View File

@ -4,7 +4,6 @@ Support for Alexa skill service end point.
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/alexa/ https://home-assistant.io/components/alexa/
""" """
import asyncio
import logging import logging
import voluptuous as vol import voluptuous as vol
@ -53,8 +52,7 @@ CONFIG_SCHEMA = vol.Schema({
}, extra=vol.ALLOW_EXTRA) }, extra=vol.ALLOW_EXTRA)
@asyncio.coroutine async def async_setup(hass, config):
def async_setup(hass, config):
"""Activate Alexa component.""" """Activate Alexa component."""
config = config.get(DOMAIN, {}) config = config.get(DOMAIN, {})
flash_briefings_config = config.get(CONF_FLASH_BRIEFINGS) flash_briefings_config = config.get(CONF_FLASH_BRIEFINGS)

View File

@ -4,7 +4,6 @@ Support for Alexa skill service end point.
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/alexa/ https://home-assistant.io/components/alexa/
""" """
import asyncio
import enum import enum
import logging import logging
@ -59,16 +58,15 @@ class AlexaIntentsView(http.HomeAssistantView):
url = INTENTS_API_ENDPOINT url = INTENTS_API_ENDPOINT
name = 'api:alexa' name = 'api:alexa'
@asyncio.coroutine async def post(self, request):
def post(self, request):
"""Handle Alexa.""" """Handle Alexa."""
hass = request.app['hass'] hass = request.app['hass']
message = yield from request.json() message = await request.json()
_LOGGER.debug("Received Alexa request: %s", message) _LOGGER.debug("Received Alexa request: %s", message)
try: try:
response = yield from async_handle_message(hass, message) response = await async_handle_message(hass, message)
return b'' if response is None else self.json(response) return b'' if response is None else self.json(response)
except UnknownRequest as err: except UnknownRequest as err:
_LOGGER.warning(str(err)) _LOGGER.warning(str(err))
@ -101,8 +99,7 @@ def intent_error_response(hass, message, error):
return alexa_response.as_dict() return alexa_response.as_dict()
@asyncio.coroutine async def async_handle_message(hass, message):
def async_handle_message(hass, message):
"""Handle an Alexa intent. """Handle an Alexa intent.
Raises: Raises:
@ -120,20 +117,18 @@ def async_handle_message(hass, message):
if not handler: if not handler:
raise UnknownRequest('Received unknown request {}'.format(req_type)) raise UnknownRequest('Received unknown request {}'.format(req_type))
return (yield from handler(hass, message)) return await handler(hass, message)
@HANDLERS.register('SessionEndedRequest') @HANDLERS.register('SessionEndedRequest')
@asyncio.coroutine async def async_handle_session_end(hass, message):
def async_handle_session_end(hass, message):
"""Handle a session end request.""" """Handle a session end request."""
return None return None
@HANDLERS.register('IntentRequest') @HANDLERS.register('IntentRequest')
@HANDLERS.register('LaunchRequest') @HANDLERS.register('LaunchRequest')
@asyncio.coroutine async def async_handle_intent(hass, message):
def async_handle_intent(hass, message):
"""Handle an intent request. """Handle an intent request.
Raises: Raises:
@ -153,7 +148,7 @@ def async_handle_intent(hass, message):
else: else:
intent_name = alexa_intent_info['name'] intent_name = alexa_intent_info['name']
intent_response = yield from intent.async_handle( intent_response = await intent.async_handle(
hass, DOMAIN, intent_name, hass, DOMAIN, intent_name,
{key: {'value': value} for key, value {key: {'value': value} for key, value
in alexa_response.variables.items()}) in alexa_response.variables.items()})

View File

@ -1,5 +1,4 @@
"""Support for alexa Smart Home Skill API.""" """Support for alexa Smart Home Skill API."""
import asyncio
import logging import logging
import math import math
from datetime import datetime from datetime import datetime
@ -695,8 +694,7 @@ class SmartHomeView(http.HomeAssistantView):
"""Initialize.""" """Initialize."""
self.smart_home_config = smart_home_config self.smart_home_config = smart_home_config
@asyncio.coroutine async def post(self, request):
def post(self, request):
"""Handle Alexa Smart Home requests. """Handle Alexa Smart Home requests.
The Smart Home API requires the endpoint to be implemented in AWS The Smart Home API requires the endpoint to be implemented in AWS
@ -704,11 +702,11 @@ class SmartHomeView(http.HomeAssistantView):
the response. the response.
""" """
hass = request.app['hass'] hass = request.app['hass']
message = yield from request.json() message = await request.json()
_LOGGER.debug("Received Alexa Smart Home request: %s", message) _LOGGER.debug("Received Alexa Smart Home request: %s", message)
response = yield from async_handle_message( response = await async_handle_message(
hass, self.smart_home_config, message) hass, self.smart_home_config, message)
_LOGGER.debug("Sending Alexa Smart Home response: %s", response) _LOGGER.debug("Sending Alexa Smart Home response: %s", response)
return b'' if response is None else self.json(response) return b'' if response is None else self.json(response)

View File

@ -149,16 +149,14 @@ CONFIG_SCHEMA = vol.Schema({
}, extra=vol.ALLOW_EXTRA) }, extra=vol.ALLOW_EXTRA)
@asyncio.coroutine async def async_setup(hass, config):
def async_setup(hass, config):
"""Set up the IP Webcam component.""" """Set up the IP Webcam component."""
from pydroid_ipcam import PyDroidIPCam from pydroid_ipcam import PyDroidIPCam
webcams = hass.data[DATA_IP_WEBCAM] = {} webcams = hass.data[DATA_IP_WEBCAM] = {}
websession = async_get_clientsession(hass) websession = async_get_clientsession(hass)
@asyncio.coroutine async def async_setup_ipcamera(cam_config):
def async_setup_ipcamera(cam_config):
"""Set up an IP camera.""" """Set up an IP camera."""
host = cam_config[CONF_HOST] host = cam_config[CONF_HOST]
username = cam_config.get(CONF_USERNAME) username = cam_config.get(CONF_USERNAME)
@ -188,16 +186,15 @@ def async_setup(hass, config):
if motion is None: if motion is None:
motion = 'motion_active' in cam.enabled_sensors motion = 'motion_active' in cam.enabled_sensors
@asyncio.coroutine async def async_update_data(now):
def async_update_data(now):
"""Update data from IP camera in SCAN_INTERVAL.""" """Update data from IP camera in SCAN_INTERVAL."""
yield from cam.update() await cam.update()
async_dispatcher_send(hass, SIGNAL_UPDATE_DATA, host) async_dispatcher_send(hass, SIGNAL_UPDATE_DATA, host)
async_track_point_in_utc_time( async_track_point_in_utc_time(
hass, async_update_data, utcnow() + interval) hass, async_update_data, utcnow() + interval)
yield from async_update_data(None) await async_update_data(None)
# Load platforms # Load platforms
webcams[host] = cam webcams[host] = cam
@ -242,7 +239,7 @@ def async_setup(hass, config):
tasks = [async_setup_ipcamera(conf) for conf in config[DOMAIN]] tasks = [async_setup_ipcamera(conf) for conf in config[DOMAIN]]
if tasks: if tasks:
yield from asyncio.wait(tasks, loop=hass.loop) await asyncio.wait(tasks, loop=hass.loop)
return True return True
@ -255,8 +252,7 @@ class AndroidIPCamEntity(Entity):
self._host = host self._host = host
self._ipcam = ipcam self._ipcam = ipcam
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Register update dispatcher.""" """Register update dispatcher."""
@callback @callback
def async_ipcam_update(host): def async_ipcam_update(host):

View File

@ -77,14 +77,13 @@ def request_configuration(hass, config, atv, credentials):
"""Request configuration steps from the user.""" """Request configuration steps from the user."""
configurator = hass.components.configurator configurator = hass.components.configurator
@asyncio.coroutine async def configuration_callback(callback_data):
def configuration_callback(callback_data):
"""Handle the submitted configuration.""" """Handle the submitted configuration."""
from pyatv import exceptions from pyatv import exceptions
pin = callback_data.get('pin') pin = callback_data.get('pin')
try: try:
yield from atv.airplay.finish_authentication(pin) await atv.airplay.finish_authentication(pin)
hass.components.persistent_notification.async_create( hass.components.persistent_notification.async_create(
'Authentication succeeded!<br /><br />Add the following ' 'Authentication succeeded!<br /><br />Add the following '
'to credentials: in your apple_tv configuration:<br /><br />' 'to credentials: in your apple_tv configuration:<br /><br />'
@ -108,11 +107,10 @@ def request_configuration(hass, config, atv, credentials):
) )
@asyncio.coroutine async def scan_for_apple_tvs(hass):
def scan_for_apple_tvs(hass):
"""Scan for devices and present a notification of the ones found.""" """Scan for devices and present a notification of the ones found."""
import pyatv import pyatv
atvs = yield from pyatv.scan_for_apple_tvs(hass.loop, timeout=3) atvs = await pyatv.scan_for_apple_tvs(hass.loop, timeout=3)
devices = [] devices = []
for atv in atvs: for atv in atvs:
@ -132,14 +130,12 @@ def scan_for_apple_tvs(hass):
notification_id=NOTIFICATION_SCAN_ID) notification_id=NOTIFICATION_SCAN_ID)
@asyncio.coroutine async def async_setup(hass, config):
def async_setup(hass, config):
"""Set up the Apple TV component.""" """Set up the Apple TV component."""
if DATA_APPLE_TV not in hass.data: if DATA_APPLE_TV not in hass.data:
hass.data[DATA_APPLE_TV] = {} hass.data[DATA_APPLE_TV] = {}
@asyncio.coroutine async def async_service_handler(service):
def async_service_handler(service):
"""Handle service calls.""" """Handle service calls."""
entity_ids = service.data.get(ATTR_ENTITY_ID) entity_ids = service.data.get(ATTR_ENTITY_ID)
@ -158,17 +154,16 @@ def async_setup(hass, config):
continue continue
atv = device.atv atv = device.atv
credentials = yield from atv.airplay.generate_credentials() credentials = await atv.airplay.generate_credentials()
yield from atv.airplay.load_credentials(credentials) await atv.airplay.load_credentials(credentials)
_LOGGER.debug('Generated new credentials: %s', credentials) _LOGGER.debug('Generated new credentials: %s', credentials)
yield from atv.airplay.start_authentication() await atv.airplay.start_authentication()
hass.async_add_job(request_configuration, hass.async_add_job(request_configuration,
hass, config, atv, credentials) hass, config, atv, credentials)
@asyncio.coroutine async def atv_discovered(service, info):
def atv_discovered(service, info):
"""Set up an Apple TV that was auto discovered.""" """Set up an Apple TV that was auto discovered."""
yield from _setup_atv(hass, { await _setup_atv(hass, {
CONF_NAME: info['name'], CONF_NAME: info['name'],
CONF_HOST: info['host'], CONF_HOST: info['host'],
CONF_LOGIN_ID: info['properties']['hG'], CONF_LOGIN_ID: info['properties']['hG'],
@ -179,7 +174,7 @@ def async_setup(hass, config):
tasks = [_setup_atv(hass, conf) for conf in config.get(DOMAIN, [])] tasks = [_setup_atv(hass, conf) for conf in config.get(DOMAIN, [])]
if tasks: if tasks:
yield from asyncio.wait(tasks, loop=hass.loop) await asyncio.wait(tasks, loop=hass.loop)
hass.services.async_register( hass.services.async_register(
DOMAIN, SERVICE_SCAN, async_service_handler, DOMAIN, SERVICE_SCAN, async_service_handler,
@ -192,8 +187,7 @@ def async_setup(hass, config):
return True return True
@asyncio.coroutine async def _setup_atv(hass, atv_config):
def _setup_atv(hass, atv_config):
"""Set up an Apple TV.""" """Set up an Apple TV."""
import pyatv import pyatv
name = atv_config.get(CONF_NAME) name = atv_config.get(CONF_NAME)
@ -209,7 +203,7 @@ def _setup_atv(hass, atv_config):
session = async_get_clientsession(hass) session = async_get_clientsession(hass)
atv = pyatv.connect_to_apple_tv(details, hass.loop, session=session) atv = pyatv.connect_to_apple_tv(details, hass.loop, session=session)
if credentials: if credentials:
yield from atv.airplay.load_credentials(credentials) await atv.airplay.load_credentials(credentials)
power = AppleTVPowerManager(hass, atv, start_off) power = AppleTVPowerManager(hass, atv, start_off)
hass.data[DATA_APPLE_TV][host] = { hass.data[DATA_APPLE_TV][host] = {

View File

@ -92,8 +92,7 @@ CONFIG_SCHEMA = vol.Schema({
}, extra=vol.ALLOW_EXTRA) }, extra=vol.ALLOW_EXTRA)
@asyncio.coroutine async def async_setup(hass, config):
def async_setup(hass, config):
"""Initialize the Home Assistant cloud.""" """Initialize the Home Assistant cloud."""
if DOMAIN in config: if DOMAIN in config:
kwargs = dict(config[DOMAIN]) kwargs = dict(config[DOMAIN])
@ -112,7 +111,7 @@ def async_setup(hass, config):
cloud = hass.data[DOMAIN] = Cloud(hass, **kwargs) cloud = hass.data[DOMAIN] = Cloud(hass, **kwargs)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, cloud.async_start) hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, cloud.async_start)
yield from http_api.async_setup(hass) await http_api.async_setup(hass)
return True return True
@ -226,17 +225,16 @@ class Cloud:
'authorization': self.id_token 'authorization': self.id_token
}) })
@asyncio.coroutine async def logout(self):
def logout(self):
"""Close connection and remove all credentials.""" """Close connection and remove all credentials."""
yield from self.iot.disconnect() await self.iot.disconnect()
self.id_token = None self.id_token = None
self.access_token = None self.access_token = None
self.refresh_token = None self.refresh_token = None
self._gactions_config = None self._gactions_config = None
yield from self.hass.async_add_job( await self.hass.async_add_job(
lambda: os.remove(self.user_info_path)) lambda: os.remove(self.user_info_path))
def write_user_info(self): def write_user_info(self):
@ -313,8 +311,7 @@ class Cloud:
self._prefs[STORAGE_ENABLE_ALEXA] = alexa_enabled self._prefs[STORAGE_ENABLE_ALEXA] = alexa_enabled
await self._store.async_save(self._prefs) await self._store.async_save(self._prefs)
@asyncio.coroutine async def _fetch_jwt_keyset(self):
def _fetch_jwt_keyset(self):
"""Fetch the JWT keyset for the Cognito instance.""" """Fetch the JWT keyset for the Cognito instance."""
session = async_get_clientsession(self.hass) session = async_get_clientsession(self.hass)
url = ("https://cognito-idp.us-east-1.amazonaws.com/" url = ("https://cognito-idp.us-east-1.amazonaws.com/"
@ -322,8 +319,8 @@ class Cloud:
try: try:
with async_timeout.timeout(10, loop=self.hass.loop): with async_timeout.timeout(10, loop=self.hass.loop):
req = yield from session.get(url) req = await session.get(url)
self.jwt_keyset = yield from req.json() self.jwt_keyset = await req.json()
return True return True

View File

@ -35,8 +35,7 @@ COMPONENTS_WITH_DEMO_PLATFORM = [
] ]
@asyncio.coroutine async def async_setup(hass, config):
def async_setup(hass, config):
"""Set up the demo environment.""" """Set up the demo environment."""
group = hass.components.group group = hass.components.group
configurator = hass.components.configurator configurator = hass.components.configurator
@ -101,7 +100,7 @@ def async_setup(hass, config):
{'weblink': {'entities': [{'name': 'Router', {'weblink': {'entities': [{'name': 'Router',
'url': 'http://192.168.1.1'}]}})) 'url': 'http://192.168.1.1'}]}}))
results = yield from asyncio.gather(*tasks, loop=hass.loop) results = await asyncio.gather(*tasks, loop=hass.loop)
if any(not result for result in results): if any(not result for result in results):
return False return False
@ -192,7 +191,7 @@ def async_setup(hass, config):
'climate.ecobee', 'climate.ecobee',
], view=True)) ], view=True))
results = yield from asyncio.gather(*tasks2, loop=hass.loop) results = await asyncio.gather(*tasks2, loop=hass.loop)
if any(not result for result in results): if any(not result for result in results):
return False return False

View File

@ -4,7 +4,6 @@ Provides functionality to turn on lights based on the states.
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/device_sun_light_trigger/ https://home-assistant.io/components/device_sun_light_trigger/
""" """
import asyncio
import logging import logging
from datetime import timedelta from datetime import timedelta
@ -45,8 +44,7 @@ CONFIG_SCHEMA = vol.Schema({
}, extra=vol.ALLOW_EXTRA) }, extra=vol.ALLOW_EXTRA)
@asyncio.coroutine async def async_setup(hass, config):
def async_setup(hass, config):
"""Set up the triggers to control lights based on device presence.""" """Set up the triggers to control lights based on device presence."""
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
device_tracker = hass.components.device_tracker device_tracker = hass.components.device_tracker

View File

@ -6,7 +6,6 @@ https://home-assistant.io/components/doorbird/
""" """
import logging import logging
import asyncio
import voluptuous as vol import voluptuous as vol
from homeassistant.components.http import HomeAssistantView from homeassistant.components.http import HomeAssistantView
@ -170,8 +169,7 @@ class DoorbirdRequestView(HomeAssistantView):
extra_urls = [API_URL + '/{sensor}'] extra_urls = [API_URL + '/{sensor}']
# pylint: disable=no-self-use # pylint: disable=no-self-use
@asyncio.coroutine async def get(self, request, sensor):
def get(self, request, sensor):
"""Respond to requests from the device.""" """Respond to requests from the device."""
hass = request.app['hass'] hass = request.app['hass']

View File

@ -4,7 +4,6 @@ Integrate with DuckDNS.
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/duckdns/ https://home-assistant.io/components/duckdns/
""" """
import asyncio
from datetime import timedelta from datetime import timedelta
import logging import logging
@ -39,27 +38,24 @@ SERVICE_TXT_SCHEMA = vol.Schema({
}) })
@asyncio.coroutine async def async_setup(hass, config):
def async_setup(hass, config):
"""Initialize the DuckDNS component.""" """Initialize the DuckDNS component."""
domain = config[DOMAIN][CONF_DOMAIN] domain = config[DOMAIN][CONF_DOMAIN]
token = config[DOMAIN][CONF_ACCESS_TOKEN] token = config[DOMAIN][CONF_ACCESS_TOKEN]
session = async_get_clientsession(hass) session = async_get_clientsession(hass)
result = yield from _update_duckdns(session, domain, token) result = await _update_duckdns(session, domain, token)
if not result: if not result:
return False return False
@asyncio.coroutine async def update_domain_interval(now):
def update_domain_interval(now):
"""Update the DuckDNS entry.""" """Update the DuckDNS entry."""
yield from _update_duckdns(session, domain, token) await _update_duckdns(session, domain, token)
@asyncio.coroutine async def update_domain_service(call):
def update_domain_service(call):
"""Update the DuckDNS entry.""" """Update the DuckDNS entry."""
yield from _update_duckdns( await _update_duckdns(
session, domain, token, txt=call.data[ATTR_TXT]) session, domain, token, txt=call.data[ATTR_TXT])
async_track_time_interval(hass, update_domain_interval, INTERVAL) async_track_time_interval(hass, update_domain_interval, INTERVAL)
@ -73,8 +69,8 @@ def async_setup(hass, config):
_SENTINEL = object() _SENTINEL = object()
@asyncio.coroutine async def _update_duckdns(session, domain, token, *, txt=_SENTINEL,
def _update_duckdns(session, domain, token, *, txt=_SENTINEL, clear=False): clear=False):
"""Update DuckDNS.""" """Update DuckDNS."""
params = { params = {
'domains': domain, 'domains': domain,
@ -92,8 +88,8 @@ def _update_duckdns(session, domain, token, *, txt=_SENTINEL, clear=False):
if clear: if clear:
params['clear'] = 'true' params['clear'] = 'true'
resp = yield from session.get(UPDATE_URL, params=params) resp = await session.get(UPDATE_URL, params=params)
body = yield from resp.text() body = await resp.text()
if body != 'OK': if body != 'OK':
_LOGGER.warning("Updating DuckDNS domain failed: %s", domain) _LOGGER.warning("Updating DuckDNS domain failed: %s", domain)

View File

@ -1,5 +1,4 @@
"""Provides a Hue API to control Home Assistant.""" """Provides a Hue API to control Home Assistant."""
import asyncio
import logging import logging
from aiohttp import web from aiohttp import web
@ -36,11 +35,10 @@ class HueUsernameView(HomeAssistantView):
extra_urls = ['/api/'] extra_urls = ['/api/']
requires_auth = False requires_auth = False
@asyncio.coroutine async def post(self, request):
def post(self, request):
"""Handle a POST request.""" """Handle a POST request."""
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)
@ -146,8 +144,7 @@ class HueOneLightChangeView(HomeAssistantView):
"""Initialize the instance of the view.""" """Initialize the instance of the view."""
self.config = config self.config = config
@asyncio.coroutine async def put(self, request, username, entity_number):
def put(self, request, username, entity_number):
"""Process a request to set the state of an individual light.""" """Process a request to set the state of an individual light."""
config = self.config config = self.config
hass = request.app['hass'] hass = request.app['hass']
@ -168,7 +165,7 @@ class HueOneLightChangeView(HomeAssistantView):
return web.Response(text="Entity not exposed", status=404) return web.Response(text="Entity not exposed", status=404)
try: try:
request_json = yield from request.json() request_json = await request.json()
except ValueError: except ValueError:
_LOGGER.error('Received invalid json') _LOGGER.error('Received invalid json')
return self.json_message('Invalid JSON', HTTP_BAD_REQUEST) return self.json_message('Invalid JSON', HTTP_BAD_REQUEST)

View File

@ -81,8 +81,7 @@ CONFIG_SCHEMA = vol.Schema({
}, extra=vol.ALLOW_EXTRA) }, extra=vol.ALLOW_EXTRA)
@asyncio.coroutine async def async_setup(hass, config):
def async_setup(hass, config):
"""Set up for Envisalink devices.""" """Set up for Envisalink devices."""
from pyenvisalink import EnvisalinkAlarmPanel from pyenvisalink import EnvisalinkAlarmPanel
@ -165,7 +164,7 @@ def async_setup(hass, config):
_LOGGER.info("Start envisalink.") _LOGGER.info("Start envisalink.")
controller.start() controller.start()
result = yield from sync_connect result = await sync_connect
if not result: if not result:
return False return False

View File

@ -4,7 +4,6 @@ Component that will help set the FFmpeg component.
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/ffmpeg/ https://home-assistant.io/components/ffmpeg/
""" """
import asyncio
import logging import logging
import voluptuous as vol import voluptuous as vol
@ -76,8 +75,7 @@ def async_restart(hass, entity_id=None):
hass.async_add_job(hass.services.async_call(DOMAIN, SERVICE_RESTART, data)) hass.async_add_job(hass.services.async_call(DOMAIN, SERVICE_RESTART, data))
@asyncio.coroutine async def async_setup(hass, config):
def async_setup(hass, config):
"""Set up the FFmpeg component.""" """Set up the FFmpeg component."""
conf = config.get(DOMAIN, {}) conf = config.get(DOMAIN, {})
@ -88,8 +86,7 @@ def async_setup(hass, config):
) )
# Register service # Register service
@asyncio.coroutine async def async_service_handle(service):
def async_service_handle(service):
"""Handle service ffmpeg process.""" """Handle service ffmpeg process."""
entity_ids = service.data.get(ATTR_ENTITY_ID) entity_ids = service.data.get(ATTR_ENTITY_ID)
@ -131,8 +128,7 @@ class FFmpegManager:
"""Return ffmpeg binary from config.""" """Return ffmpeg binary from config."""
return self._bin return self._bin
@asyncio.coroutine async def async_run_test(self, input_source):
def async_run_test(self, input_source):
"""Run test on this input. TRUE is deactivate or run correct. """Run test on this input. TRUE is deactivate or run correct.
This method must be run in the event loop. This method must be run in the event loop.
@ -146,7 +142,7 @@ class FFmpegManager:
# run test # run test
ffmpeg_test = Test(self.binary, loop=self.hass.loop) ffmpeg_test = Test(self.binary, loop=self.hass.loop)
success = yield from ffmpeg_test.run_test(input_source) success = await ffmpeg_test.run_test(input_source)
if not success: if not success:
_LOGGER.error("FFmpeg '%s' test fails!", input_source) _LOGGER.error("FFmpeg '%s' test fails!", input_source)
self._cache[input_source] = False self._cache[input_source] = False
@ -163,8 +159,7 @@ class FFmpegBase(Entity):
self.ffmpeg = None self.ffmpeg = None
self.initial_state = initial_state self.initial_state = initial_state
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Register dispatcher & events. """Register dispatcher & events.
This method is a coroutine. This method is a coroutine.
@ -189,40 +184,36 @@ class FFmpegBase(Entity):
"""Return True if entity has to be polled for state.""" """Return True if entity has to be polled for state."""
return False return False
@asyncio.coroutine async def _async_start_ffmpeg(self, entity_ids):
def _async_start_ffmpeg(self, entity_ids):
"""Start a FFmpeg process. """Start a FFmpeg process.
This method is a coroutine. This method is a coroutine.
""" """
raise NotImplementedError() raise NotImplementedError()
@asyncio.coroutine async def _async_stop_ffmpeg(self, entity_ids):
def _async_stop_ffmpeg(self, entity_ids):
"""Stop a FFmpeg process. """Stop a FFmpeg process.
This method is a coroutine. This method is a coroutine.
""" """
if entity_ids is None or self.entity_id in entity_ids: if entity_ids is None or self.entity_id in entity_ids:
yield from self.ffmpeg.close() await self.ffmpeg.close()
@asyncio.coroutine async def _async_restart_ffmpeg(self, entity_ids):
def _async_restart_ffmpeg(self, entity_ids):
"""Stop a FFmpeg process. """Stop a FFmpeg process.
This method is a coroutine. This method is a coroutine.
""" """
if entity_ids is None or self.entity_id in entity_ids: if entity_ids is None or self.entity_id in entity_ids:
yield from self._async_stop_ffmpeg(None) await self._async_stop_ffmpeg(None)
yield from self._async_start_ffmpeg(None) await self._async_start_ffmpeg(None)
@callback @callback
def _async_register_events(self): def _async_register_events(self):
"""Register a FFmpeg process/device.""" """Register a FFmpeg process/device."""
@asyncio.coroutine async def async_shutdown_handle(event):
def async_shutdown_handle(event):
"""Stop FFmpeg process.""" """Stop FFmpeg process."""
yield from self._async_stop_ffmpeg(None) await self._async_stop_ffmpeg(None)
self.hass.bus.async_listen_once( self.hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, async_shutdown_handle) EVENT_HOMEASSISTANT_STOP, async_shutdown_handle)
@ -231,10 +222,9 @@ class FFmpegBase(Entity):
if not self.initial_state: if not self.initial_state:
return return
@asyncio.coroutine async def async_start_handle(event):
def async_start_handle(event):
"""Start FFmpeg process.""" """Start FFmpeg process."""
yield from self._async_start_ffmpeg(None) await self._async_start_ffmpeg(None)
self.async_schedule_update_ha_state() self.async_schedule_update_ha_state()
self.hass.bus.async_listen_once( self.hass.bus.async_listen_once(

View File

@ -4,7 +4,6 @@ Support for the Foursquare (Swarm) API.
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/foursquare/ https://home-assistant.io/components/foursquare/
""" """
import asyncio
import logging import logging
import requests import requests
@ -85,11 +84,10 @@ class FoursquarePushReceiver(HomeAssistantView):
"""Initialize the OAuth callback view.""" """Initialize the OAuth callback view."""
self.push_secret = push_secret self.push_secret = push_secret
@asyncio.coroutine async def post(self, request):
def post(self, request):
"""Accept the POST from Foursquare.""" """Accept the POST from Foursquare."""
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

@ -37,8 +37,7 @@ CONFIG_SCHEMA = vol.Schema({
}, extra=vol.ALLOW_EXTRA) }, extra=vol.ALLOW_EXTRA)
@asyncio.coroutine async def async_setup(hass, config):
def async_setup(hass, config):
"""Initialize the FreeDNS component.""" """Initialize the FreeDNS component."""
url = config[DOMAIN].get(CONF_URL) url = config[DOMAIN].get(CONF_URL)
auth_token = config[DOMAIN].get(CONF_ACCESS_TOKEN) auth_token = config[DOMAIN].get(CONF_ACCESS_TOKEN)
@ -46,16 +45,15 @@ def async_setup(hass, config):
session = hass.helpers.aiohttp_client.async_get_clientsession() session = hass.helpers.aiohttp_client.async_get_clientsession()
result = yield from _update_freedns( result = await _update_freedns(
hass, session, url, auth_token) hass, session, url, auth_token)
if result is False: if result is False:
return False return False
@asyncio.coroutine async def update_domain_callback(now):
def update_domain_callback(now):
"""Update the FreeDNS entry.""" """Update the FreeDNS entry."""
yield from _update_freedns(hass, session, url, auth_token) await _update_freedns(hass, session, url, auth_token)
hass.helpers.event.async_track_time_interval( hass.helpers.event.async_track_time_interval(
update_domain_callback, update_interval) update_domain_callback, update_interval)
@ -63,8 +61,7 @@ def async_setup(hass, config):
return True return True
@asyncio.coroutine async def _update_freedns(hass, session, url, auth_token):
def _update_freedns(hass, session, url, auth_token):
"""Update FreeDNS.""" """Update FreeDNS."""
params = None params = None
@ -77,8 +74,8 @@ def _update_freedns(hass, session, url, auth_token):
try: try:
with async_timeout.timeout(TIMEOUT, loop=hass.loop): with async_timeout.timeout(TIMEOUT, loop=hass.loop):
resp = yield from session.get(url, params=params) resp = await session.get(url, params=params)
body = yield from resp.text() body = await resp.text()
if "has not changed" in body: if "has not changed" in body:
# IP has not changed. # IP has not changed.

View File

@ -36,8 +36,7 @@ CONFIG_SCHEMA = vol.Schema({
}, extra=vol.ALLOW_EXTRA) }, extra=vol.ALLOW_EXTRA)
@asyncio.coroutine async def async_setup(hass, config):
def async_setup(hass, config):
"""Initialize the Google Domains component.""" """Initialize the Google Domains component."""
domain = config[DOMAIN].get(CONF_DOMAIN) domain = config[DOMAIN].get(CONF_DOMAIN)
user = config[DOMAIN].get(CONF_USERNAME) user = config[DOMAIN].get(CONF_USERNAME)
@ -46,16 +45,15 @@ def async_setup(hass, config):
session = hass.helpers.aiohttp_client.async_get_clientsession() session = hass.helpers.aiohttp_client.async_get_clientsession()
result = yield from _update_google_domains( result = await _update_google_domains(
hass, session, domain, user, password, timeout) hass, session, domain, user, password, timeout)
if not result: if not result:
return False return False
@asyncio.coroutine async def update_domain_interval(now):
def update_domain_interval(now):
"""Update the Google Domains entry.""" """Update the Google Domains entry."""
yield from _update_google_domains( await _update_google_domains(
hass, session, domain, user, password, timeout) hass, session, domain, user, password, timeout)
hass.helpers.event.async_track_time_interval( hass.helpers.event.async_track_time_interval(
@ -64,8 +62,8 @@ def async_setup(hass, config):
return True return True
@asyncio.coroutine async def _update_google_domains(hass, session, domain, user, password,
def _update_google_domains(hass, session, domain, user, password, timeout): timeout):
"""Update Google Domains.""" """Update Google Domains."""
url = UPDATE_URL.format(user, password) url = UPDATE_URL.format(user, password)
@ -75,8 +73,8 @@ def _update_google_domains(hass, session, domain, user, password, timeout):
try: try:
with async_timeout.timeout(timeout, loop=hass.loop): with async_timeout.timeout(timeout, loop=hass.loop):
resp = yield from session.get(url, params=params) resp = await session.get(url, params=params)
body = yield from resp.text() body = await resp.text()
if body.startswith('good') or body.startswith('nochg'): if body.startswith('good') or body.startswith('nochg'):
return True return True

View File

@ -4,7 +4,6 @@ Support for HomeMatic devices.
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/homematic/ https://home-assistant.io/components/homematic/
""" """
import asyncio
from datetime import timedelta from datetime import timedelta
from functools import partial from functools import partial
import logging import logging
@ -715,10 +714,9 @@ class HMDevice(Entity):
if self._state: if self._state:
self._state = self._state.upper() self._state = self._state.upper()
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Load data init callbacks.""" """Load data init callbacks."""
yield from self.hass.async_add_job(self.link_homematic) await self.hass.async_add_job(self.link_homematic)
@property @property
def unique_id(self): def unique_id(self):

View File

@ -4,7 +4,6 @@ Support for Hydrawise cloud.
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/hydrawise/ https://home-assistant.io/components/hydrawise/
""" """
import asyncio
from datetime import timedelta from datetime import timedelta
import logging import logging
@ -127,8 +126,7 @@ class HydrawiseEntity(Entity):
"""Return the name of the sensor.""" """Return the name of the sensor."""
return self._name return self._name
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Register callbacks.""" """Register callbacks."""
async_dispatcher_connect( async_dispatcher_connect(
self.hass, SIGNAL_UPDATE_HYDRAWISE, self._update_callback) self.hass, SIGNAL_UPDATE_HYDRAWISE, self._update_callback)

View File

@ -1,5 +1,4 @@
"""Implementation of a base class for all IHC devices.""" """Implementation of a base class for all IHC devices."""
import asyncio
from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity import Entity
@ -28,8 +27,7 @@ class IHCDevice(Entity):
self.ihc_note = '' self.ihc_note = ''
self.ihc_position = '' self.ihc_position = ''
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Add callback for IHC changes.""" """Add callback for IHC changes."""
self.ihc_controller.add_notify_event( self.ihc_controller.add_notify_event(
self.ihc_id, self.on_ihc_change, True) self.ihc_id, self.on_ihc_change, True)

View File

@ -4,7 +4,6 @@ Support for INSTEON Modems (PLM and 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/insteon/ https://home-assistant.io/components/insteon/
""" """
import asyncio
import collections import collections
import logging import logging
from typing import Dict from typing import Dict
@ -149,8 +148,7 @@ X10_HOUSECODE_SCHEMA = vol.Schema({
}) })
@asyncio.coroutine async def async_setup(hass, config):
def async_setup(hass, config):
"""Set up the connection to the modem.""" """Set up the connection to the modem."""
import insteonplm import insteonplm
@ -292,7 +290,7 @@ def async_setup(hass, config):
if host: if host:
_LOGGER.info('Connecting to Insteon Hub on %s', host) _LOGGER.info('Connecting to Insteon Hub on %s', host)
conn = yield from insteonplm.Connection.create( conn = await insteonplm.Connection.create(
host=host, host=host,
port=ip_port, port=ip_port,
username=username, username=username,
@ -302,7 +300,7 @@ def async_setup(hass, config):
workdir=hass.config.config_dir) workdir=hass.config.config_dir)
else: else:
_LOGGER.info("Looking for Insteon PLM on %s", port) _LOGGER.info("Looking for Insteon PLM on %s", port)
conn = yield from insteonplm.Connection.create( conn = await insteonplm.Connection.create(
device=port, device=port,
loop=hass.loop, loop=hass.loop,
workdir=hass.config.config_dir) workdir=hass.config.config_dir)
@ -494,8 +492,7 @@ class InsteonEntity(Entity):
deviceid.human, group, val) deviceid.human, group, val)
self.async_schedule_update_ha_state() self.async_schedule_update_ha_state()
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Register INSTEON update events.""" """Register INSTEON update events."""
_LOGGER.debug('Tracking updates for device %s group %d statename %s', _LOGGER.debug('Tracking updates for device %s group %d statename %s',
self.address, self.group, self.address, self.group,

View File

@ -4,14 +4,12 @@ Support for INSTEON 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/insteon_plm/ https://home-assistant.io/components/insteon_plm/
""" """
import asyncio
import logging import logging
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@asyncio.coroutine async def async_setup(hass, config):
def async_setup(hass, config):
"""Set up the insteon_plm component. """Set up the insteon_plm component.
This component is deprecated as of release 0.77 and should be removed in This component is deprecated as of release 0.77 and should be removed in

View File

@ -1,5 +1,4 @@
"""Handle intents with scripts.""" """Handle intents with scripts."""
import asyncio
import copy import copy
import logging import logging
@ -45,8 +44,7 @@ CONFIG_SCHEMA = vol.Schema({
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@asyncio.coroutine async def async_setup(hass, config):
def async_setup(hass, config):
"""Activate Alexa component.""" """Activate Alexa component."""
intents = copy.deepcopy(config[DOMAIN]) intents = copy.deepcopy(config[DOMAIN])
template.attach(hass, intents) template.attach(hass, intents)
@ -69,8 +67,7 @@ class ScriptIntentHandler(intent.IntentHandler):
self.intent_type = intent_type self.intent_type = intent_type
self.config = config self.config = config
@asyncio.coroutine async def async_handle(self, intent_obj):
def async_handle(self, intent_obj):
"""Handle the intent.""" """Handle the intent."""
speech = self.config.get(CONF_SPEECH) speech = self.config.get(CONF_SPEECH)
card = self.config.get(CONF_CARD) card = self.config.get(CONF_CARD)
@ -83,7 +80,7 @@ class ScriptIntentHandler(intent.IntentHandler):
if is_async_action: if is_async_action:
intent_obj.hass.async_add_job(action.async_run(slots)) intent_obj.hass.async_add_job(action.async_run(slots))
else: else:
yield from action.async_run(slots) await action.async_run(slots)
response = intent_obj.create_response() response = intent_obj.create_response()

View File

@ -4,7 +4,6 @@ Component that will help guide the user taking its first steps.
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/introduction/ https://home-assistant.io/components/introduction/
""" """
import asyncio
import logging import logging
import voluptuous as vol import voluptuous as vol
@ -16,8 +15,7 @@ CONFIG_SCHEMA = vol.Schema({
}, extra=vol.ALLOW_EXTRA) }, extra=vol.ALLOW_EXTRA)
@asyncio.coroutine async def async_setup(hass, config=None):
def async_setup(hass, config=None):
"""Set up the introduction component.""" """Set up the introduction component."""
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
log.info(""" log.info("""

View File

@ -4,7 +4,6 @@ Native Home Assistant iOS app component.
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/ecosystem/ios/ https://home-assistant.io/ecosystem/ios/
""" """
import asyncio
import logging import logging
import datetime import datetime
@ -259,11 +258,10 @@ class iOSIdentifyDeviceView(HomeAssistantView):
"""Initiliaze the view.""" """Initiliaze the view."""
self._config_path = config_path self._config_path = config_path
@asyncio.coroutine async def post(self, request):
def post(self, request):
"""Handle the POST request for device identification.""" """Handle the POST request for device identification."""
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

@ -4,7 +4,6 @@ Support the ISY-994 controllers.
For configuration details please visit the documentation for this component at For configuration details please visit the documentation for this component at
https://home-assistant.io/components/isy994/ https://home-assistant.io/components/isy994/
""" """
import asyncio
from collections import namedtuple from collections import namedtuple
import logging import logging
from urllib.parse import urlparse from urllib.parse import urlparse
@ -414,8 +413,7 @@ class ISYDevice(Entity):
self._change_handler = None self._change_handler = None
self._control_handler = None self._control_handler = None
@asyncio.coroutine async def async_added_to_hass(self) -> None:
def async_added_to_hass(self) -> None:
"""Subscribe to the node change events.""" """Subscribe to the node change events."""
self._change_handler = self._node.status.subscribe( self._change_handler = self._node.status.subscribe(
'changed', self.on_update) 'changed', self.on_update)

View File

@ -4,7 +4,6 @@ Component for interacting with a Lutron RadioRA 2 system.
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/lutron/ https://home-assistant.io/components/lutron/
""" """
import asyncio
import logging import logging
import voluptuous as vol import voluptuous as vol
@ -69,8 +68,7 @@ class LutronDevice(Entity):
self._controller = controller self._controller = controller
self._area_name = area_name self._area_name = area_name
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Register callbacks.""" """Register callbacks."""
self.hass.async_add_job( self.hass.async_add_job(
self._controller.subscribe, self._lutron_device, self._controller.subscribe, self._lutron_device,

View File

@ -4,7 +4,6 @@ Component for interacting with a Lutron Caseta system.
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/lutron_caseta/ https://home-assistant.io/components/lutron_caseta/
""" """
import asyncio
import logging import logging
import voluptuous as vol import voluptuous as vol
@ -40,8 +39,7 @@ LUTRON_CASETA_COMPONENTS = [
] ]
@asyncio.coroutine async def async_setup(hass, base_config):
def async_setup(hass, base_config):
"""Set up the Lutron component.""" """Set up the Lutron component."""
from pylutron_caseta.smartbridge import Smartbridge from pylutron_caseta.smartbridge import Smartbridge
@ -54,7 +52,7 @@ def async_setup(hass, base_config):
certfile=certfile, certfile=certfile,
ca_certs=ca_certs) ca_certs=ca_certs)
hass.data[LUTRON_CASETA_SMARTBRIDGE] = bridge hass.data[LUTRON_CASETA_SMARTBRIDGE] = bridge
yield from bridge.connect() await bridge.connect()
if not hass.data[LUTRON_CASETA_SMARTBRIDGE].is_connected(): if not hass.data[LUTRON_CASETA_SMARTBRIDGE].is_connected():
_LOGGER.error("Unable to connect to Lutron smartbridge at %s", _LOGGER.error("Unable to connect to Lutron smartbridge at %s",
config[CONF_HOST]) config[CONF_HOST])
@ -85,8 +83,7 @@ class LutronCasetaDevice(Entity):
self._state = None self._state = None
self._smartbridge = bridge self._smartbridge = bridge
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Register callbacks.""" """Register callbacks."""
self._smartbridge.add_subscriber(self._device_id, self._smartbridge.add_subscriber(self._device_id,
self.async_schedule_update_ha_state) self.async_schedule_update_ha_state)

View File

@ -106,8 +106,7 @@ def face_person(hass, group, person, camera_entity):
hass.services.call(DOMAIN, SERVICE_FACE_PERSON, data) hass.services.call(DOMAIN, SERVICE_FACE_PERSON, data)
@asyncio.coroutine async def async_setup(hass, config):
def async_setup(hass, config):
"""Set up Microsoft Face.""" """Set up Microsoft Face."""
entities = {} entities = {}
face = MicrosoftFace( face = MicrosoftFace(
@ -120,26 +119,25 @@ def async_setup(hass, config):
try: try:
# read exists group/person from cloud and create entities # read exists group/person from cloud and create entities
yield from face.update_store() await face.update_store()
except HomeAssistantError as err: except HomeAssistantError as err:
_LOGGER.error("Can't load data from face api: %s", err) _LOGGER.error("Can't load data from face api: %s", err)
return False return False
hass.data[DATA_MICROSOFT_FACE] = face hass.data[DATA_MICROSOFT_FACE] = face
@asyncio.coroutine async def async_create_group(service):
def async_create_group(service):
"""Create a new person group.""" """Create a new person group."""
name = service.data[ATTR_NAME] name = service.data[ATTR_NAME]
g_id = slugify(name) g_id = slugify(name)
try: try:
yield from face.call_api( await face.call_api(
'put', "persongroups/{0}".format(g_id), {'name': name}) 'put', "persongroups/{0}".format(g_id), {'name': name})
face.store[g_id] = {} face.store[g_id] = {}
entities[g_id] = MicrosoftFaceGroupEntity(hass, face, g_id, name) entities[g_id] = MicrosoftFaceGroupEntity(hass, face, g_id, name)
yield from entities[g_id].async_update_ha_state() await entities[g_id].async_update_ha_state()
except HomeAssistantError as err: except HomeAssistantError as err:
_LOGGER.error("Can't create group '%s' with error: %s", g_id, err) _LOGGER.error("Can't create group '%s' with error: %s", g_id, err)
@ -147,13 +145,12 @@ def async_setup(hass, config):
DOMAIN, SERVICE_CREATE_GROUP, async_create_group, DOMAIN, SERVICE_CREATE_GROUP, async_create_group,
schema=SCHEMA_GROUP_SERVICE) schema=SCHEMA_GROUP_SERVICE)
@asyncio.coroutine async def async_delete_group(service):
def async_delete_group(service):
"""Delete a person group.""" """Delete a person group."""
g_id = slugify(service.data[ATTR_NAME]) g_id = slugify(service.data[ATTR_NAME])
try: try:
yield from face.call_api('delete', "persongroups/{0}".format(g_id)) await face.call_api('delete', "persongroups/{0}".format(g_id))
face.store.pop(g_id) face.store.pop(g_id)
entity = entities.pop(g_id) entity = entities.pop(g_id)
@ -165,13 +162,12 @@ def async_setup(hass, config):
DOMAIN, SERVICE_DELETE_GROUP, async_delete_group, DOMAIN, SERVICE_DELETE_GROUP, async_delete_group,
schema=SCHEMA_GROUP_SERVICE) schema=SCHEMA_GROUP_SERVICE)
@asyncio.coroutine async def async_train_group(service):
def async_train_group(service):
"""Train a person group.""" """Train a person group."""
g_id = service.data[ATTR_GROUP] g_id = service.data[ATTR_GROUP]
try: try:
yield from face.call_api( await face.call_api(
'post', "persongroups/{0}/train".format(g_id)) 'post', "persongroups/{0}/train".format(g_id))
except HomeAssistantError as err: except HomeAssistantError as err:
_LOGGER.error("Can't train group '%s' with error: %s", g_id, err) _LOGGER.error("Can't train group '%s' with error: %s", g_id, err)
@ -180,19 +176,18 @@ def async_setup(hass, config):
DOMAIN, SERVICE_TRAIN_GROUP, async_train_group, DOMAIN, SERVICE_TRAIN_GROUP, async_train_group,
schema=SCHEMA_TRAIN_SERVICE) schema=SCHEMA_TRAIN_SERVICE)
@asyncio.coroutine async def async_create_person(service):
def async_create_person(service):
"""Create a person in a group.""" """Create a person in a group."""
name = service.data[ATTR_NAME] name = service.data[ATTR_NAME]
g_id = service.data[ATTR_GROUP] g_id = service.data[ATTR_GROUP]
try: try:
user_data = yield from face.call_api( user_data = await face.call_api(
'post', "persongroups/{0}/persons".format(g_id), {'name': name} 'post', "persongroups/{0}/persons".format(g_id), {'name': name}
) )
face.store[g_id][name] = user_data['personId'] face.store[g_id][name] = user_data['personId']
yield from entities[g_id].async_update_ha_state() await entities[g_id].async_update_ha_state()
except HomeAssistantError as err: except HomeAssistantError as err:
_LOGGER.error("Can't create person '%s' with error: %s", name, err) _LOGGER.error("Can't create person '%s' with error: %s", name, err)
@ -200,19 +195,18 @@ def async_setup(hass, config):
DOMAIN, SERVICE_CREATE_PERSON, async_create_person, DOMAIN, SERVICE_CREATE_PERSON, async_create_person,
schema=SCHEMA_PERSON_SERVICE) schema=SCHEMA_PERSON_SERVICE)
@asyncio.coroutine async def async_delete_person(service):
def async_delete_person(service):
"""Delete a person in a group.""" """Delete a person in a group."""
name = service.data[ATTR_NAME] name = service.data[ATTR_NAME]
g_id = service.data[ATTR_GROUP] g_id = service.data[ATTR_GROUP]
p_id = face.store[g_id].get(name) p_id = face.store[g_id].get(name)
try: try:
yield from face.call_api( await face.call_api(
'delete', "persongroups/{0}/persons/{1}".format(g_id, p_id)) 'delete', "persongroups/{0}/persons/{1}".format(g_id, p_id))
face.store[g_id].pop(name) face.store[g_id].pop(name)
yield from entities[g_id].async_update_ha_state() await entities[g_id].async_update_ha_state()
except HomeAssistantError as err: except HomeAssistantError as err:
_LOGGER.error("Can't delete person '%s' with error: %s", p_id, err) _LOGGER.error("Can't delete person '%s' with error: %s", p_id, err)
@ -220,8 +214,7 @@ def async_setup(hass, config):
DOMAIN, SERVICE_DELETE_PERSON, async_delete_person, DOMAIN, SERVICE_DELETE_PERSON, async_delete_person,
schema=SCHEMA_PERSON_SERVICE) schema=SCHEMA_PERSON_SERVICE)
@asyncio.coroutine async def async_face_person(service):
def async_face_person(service):
"""Add a new face picture to a person.""" """Add a new face picture to a person."""
g_id = service.data[ATTR_GROUP] g_id = service.data[ATTR_GROUP]
p_id = face.store[g_id].get(service.data[ATTR_PERSON]) p_id = face.store[g_id].get(service.data[ATTR_PERSON])
@ -230,9 +223,9 @@ def async_setup(hass, config):
camera = hass.components.camera camera = hass.components.camera
try: try:
image = yield from camera.async_get_image(hass, camera_entity) image = await camera.async_get_image(hass, camera_entity)
yield from face.call_api( await face.call_api(
'post', 'post',
"persongroups/{0}/persons/{1}/persistedFaces".format( "persongroups/{0}/persons/{1}/persistedFaces".format(
g_id, p_id), g_id, p_id),
@ -307,10 +300,9 @@ class MicrosoftFace:
"""Store group/person data and IDs.""" """Store group/person data and IDs."""
return self._store return self._store
@asyncio.coroutine async def update_store(self):
def update_store(self):
"""Load all group/person data into local store.""" """Load all group/person data into local store."""
groups = yield from self.call_api('get', 'persongroups') groups = await self.call_api('get', 'persongroups')
tasks = [] tasks = []
for group in groups: for group in groups:
@ -319,7 +311,7 @@ class MicrosoftFace:
self._entities[g_id] = MicrosoftFaceGroupEntity( self._entities[g_id] = MicrosoftFaceGroupEntity(
self.hass, self, g_id, group['name']) self.hass, self, g_id, group['name'])
persons = yield from self.call_api( persons = await self.call_api(
'get', "persongroups/{0}/persons".format(g_id)) 'get', "persongroups/{0}/persons".format(g_id))
for person in persons: for person in persons:
@ -328,10 +320,9 @@ class MicrosoftFace:
tasks.append(self._entities[g_id].async_update_ha_state()) tasks.append(self._entities[g_id].async_update_ha_state())
if tasks: if tasks:
yield from asyncio.wait(tasks, loop=self.hass.loop) await asyncio.wait(tasks, loop=self.hass.loop)
@asyncio.coroutine async def call_api(self, method, function, data=None, binary=False,
def call_api(self, method, function, data=None, binary=False,
params=None): params=None):
"""Make an api call.""" """Make an api call."""
headers = {"Ocp-Apim-Subscription-Key": self._api_key} headers = {"Ocp-Apim-Subscription-Key": self._api_key}
@ -350,10 +341,10 @@ class MicrosoftFace:
try: try:
with async_timeout.timeout(self.timeout, loop=self.hass.loop): with async_timeout.timeout(self.timeout, loop=self.hass.loop):
response = yield from getattr(self.websession, method)( response = await getattr(self.websession, method)(
url, data=payload, headers=headers, params=params) url, data=payload, headers=headers, params=params)
answer = yield from response.json() answer = await response.json()
_LOGGER.debug("Read from microsoft face api: %s", answer) _LOGGER.debug("Read from microsoft face api: %s", answer)
if response.status < 300: if response.status < 300:

View File

@ -4,7 +4,6 @@ Publish simple item state changes via MQTT.
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/mqtt_statestream/ https://home-assistant.io/components/mqtt_statestream/
""" """
import asyncio
import json import json
import voluptuous as vol import voluptuous as vol
@ -43,8 +42,7 @@ CONFIG_SCHEMA = vol.Schema({
}, extra=vol.ALLOW_EXTRA) }, extra=vol.ALLOW_EXTRA)
@asyncio.coroutine async def async_setup(hass, config):
def async_setup(hass, config):
"""Set up the MQTT state feed.""" """Set up the MQTT state feed."""
conf = config.get(DOMAIN, {}) conf = config.get(DOMAIN, {})
base_topic = conf.get(CONF_BASE_TOPIC) base_topic = conf.get(CONF_BASE_TOPIC)

View File

@ -4,7 +4,6 @@ Integrate with namecheap DNS services.
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/namecheapdns/ https://home-assistant.io/components/namecheapdns/
""" """
import asyncio
import logging import logging
from datetime import timedelta from datetime import timedelta
@ -32,8 +31,7 @@ CONFIG_SCHEMA = vol.Schema({
}, extra=vol.ALLOW_EXTRA) }, extra=vol.ALLOW_EXTRA)
@asyncio.coroutine async def async_setup(hass, config):
def async_setup(hass, config):
"""Initialize the namecheap DNS component.""" """Initialize the namecheap DNS component."""
host = config[DOMAIN][CONF_HOST] host = config[DOMAIN][CONF_HOST]
domain = config[DOMAIN][CONF_DOMAIN] domain = config[DOMAIN][CONF_DOMAIN]
@ -41,23 +39,21 @@ def async_setup(hass, config):
session = async_get_clientsession(hass) session = async_get_clientsession(hass)
result = yield from _update_namecheapdns(session, host, domain, password) result = await _update_namecheapdns(session, host, domain, password)
if not result: if not result:
return False return False
@asyncio.coroutine async def update_domain_interval(now):
def update_domain_interval(now):
"""Update the namecheap DNS entry.""" """Update the namecheap DNS entry."""
yield from _update_namecheapdns(session, host, domain, password) await _update_namecheapdns(session, host, domain, password)
async_track_time_interval(hass, update_domain_interval, INTERVAL) async_track_time_interval(hass, update_domain_interval, INTERVAL)
return result return result
@asyncio.coroutine async def _update_namecheapdns(session, host, domain, password):
def _update_namecheapdns(session, host, domain, password):
"""Update namecheap DNS entry.""" """Update namecheap DNS entry."""
import xml.etree.ElementTree as ET import xml.etree.ElementTree as ET
@ -67,8 +63,8 @@ def _update_namecheapdns(session, host, domain, password):
'password': password, 'password': password,
} }
resp = yield from session.get(UPDATE_URL, params=params) resp = await session.get(UPDATE_URL, params=params)
xml_string = yield from resp.text() xml_string = await resp.text()
root = ET.fromstring(xml_string) root = ET.fromstring(xml_string)
err_count = root.find('ErrCount').text err_count = root.find('ErrCount').text

View File

@ -53,8 +53,7 @@ CONFIG_SCHEMA = vol.Schema({
}, extra=vol.ALLOW_EXTRA) }, extra=vol.ALLOW_EXTRA)
@asyncio.coroutine async def async_setup(hass, config):
def async_setup(hass, config):
"""Initialize the NO-IP component.""" """Initialize the NO-IP component."""
domain = config[DOMAIN].get(CONF_DOMAIN) domain = config[DOMAIN].get(CONF_DOMAIN)
user = config[DOMAIN].get(CONF_USERNAME) user = config[DOMAIN].get(CONF_USERNAME)
@ -65,16 +64,15 @@ def async_setup(hass, config):
session = hass.helpers.aiohttp_client.async_get_clientsession() session = hass.helpers.aiohttp_client.async_get_clientsession()
result = yield from _update_no_ip( result = await _update_no_ip(
hass, session, domain, auth_str, timeout) hass, session, domain, auth_str, timeout)
if not result: if not result:
return False return False
@asyncio.coroutine async def update_domain_interval(now):
def update_domain_interval(now):
"""Update the NO-IP entry.""" """Update the NO-IP entry."""
yield from _update_no_ip(hass, session, domain, auth_str, timeout) await _update_no_ip(hass, session, domain, auth_str, timeout)
hass.helpers.event.async_track_time_interval( hass.helpers.event.async_track_time_interval(
update_domain_interval, INTERVAL) update_domain_interval, INTERVAL)
@ -82,8 +80,7 @@ def async_setup(hass, config):
return True return True
@asyncio.coroutine async def _update_no_ip(hass, session, domain, auth_str, timeout):
def _update_no_ip(hass, session, domain, auth_str, timeout):
"""Update NO-IP.""" """Update NO-IP."""
url = UPDATE_URL url = UPDATE_URL
@ -98,8 +95,8 @@ def _update_no_ip(hass, session, domain, auth_str, timeout):
try: try:
with async_timeout.timeout(timeout, loop=hass.loop): with async_timeout.timeout(timeout, loop=hass.loop):
resp = yield from session.get(url, params=params, headers=headers) resp = await session.get(url, params=params, headers=headers)
body = yield from resp.text() body = await resp.text()
if body.startswith('good') or body.startswith('nochg'): if body.startswith('good') or body.startswith('nochg'):
return True return True

View File

@ -4,7 +4,6 @@ A component which is collecting configuration errors.
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/persistent_notification/ https://home-assistant.io/components/persistent_notification/
""" """
import asyncio
import logging import logging
from collections import OrderedDict from collections import OrderedDict
from typing import Awaitable from typing import Awaitable
@ -99,8 +98,7 @@ def async_dismiss(hass: HomeAssistant, notification_id: str) -> None:
hass.async_add_job(hass.services.async_call(DOMAIN, SERVICE_DISMISS, data)) hass.async_add_job(hass.services.async_call(DOMAIN, SERVICE_DISMISS, data))
@asyncio.coroutine async def async_setup(hass: HomeAssistant, config: dict) -> Awaitable[bool]:
def async_setup(hass: HomeAssistant, config: dict) -> Awaitable[bool]:
"""Set up the persistent notification component.""" """Set up the persistent notification component."""
persistent_notifications = OrderedDict() persistent_notifications = OrderedDict()
hass.data[DOMAIN] = {'notifications': persistent_notifications} hass.data[DOMAIN] = {'notifications': persistent_notifications}

View File

@ -4,7 +4,6 @@ For more details about this component, please refer to the documentation at
https://home-assistant.io/components/plant/ https://home-assistant.io/components/plant/
""" """
import logging import logging
import asyncio
from datetime import datetime, timedelta from datetime import datetime, timedelta
from collections import deque from collections import deque
import voluptuous as vol import voluptuous as vol
@ -97,8 +96,7 @@ CONFIG_SCHEMA = vol.Schema({
ENABLE_LOAD_HISTORY = False ENABLE_LOAD_HISTORY = False
@asyncio.coroutine async def async_setup(hass, config):
def async_setup(hass, config):
"""Set up the Plant component.""" """Set up the Plant component."""
component = EntityComponent(_LOGGER, DOMAIN, hass, component = EntityComponent(_LOGGER, DOMAIN, hass,
group_name=GROUP_NAME_ALL_PLANTS) group_name=GROUP_NAME_ALL_PLANTS)
@ -112,7 +110,7 @@ def async_setup(hass, config):
async_track_state_change(hass, sensor_entity_ids, entity.state_changed) async_track_state_change(hass, sensor_entity_ids, entity.state_changed)
entities.append(entity) entities.append(entity)
yield from component.async_add_entities(entities) await component.async_add_entities(entities)
return True return True
@ -246,15 +244,13 @@ class Plant(Entity):
return '{} high'.format(sensor_name) return '{} high'.format(sensor_name)
return None return None
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""After being added to hass, load from history.""" """After being added to hass, load from history."""
if ENABLE_LOAD_HISTORY and 'recorder' in self.hass.config.components: if ENABLE_LOAD_HISTORY and 'recorder' in self.hass.config.components:
# only use the database if it's configured # only use the database if it's configured
self.hass.async_add_job(self._load_history_from_db) self.hass.async_add_job(self._load_history_from_db)
@asyncio.coroutine async def _load_history_from_db(self):
def _load_history_from_db(self):
"""Load the history of the brightness values from the database. """Load the history of the brightness values from the database.
This only needs to be done once during startup. This only needs to be done once during startup.

View File

@ -4,7 +4,6 @@ Support for Prometheus metrics export.
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/prometheus/ https://home-assistant.io/components/prometheus/
""" """
import asyncio
import logging import logging
import voluptuous as vol import voluptuous as vol
@ -265,8 +264,7 @@ class PrometheusView(HomeAssistantView):
"""Initialize Prometheus view.""" """Initialize Prometheus view."""
self.prometheus_client = prometheus_client self.prometheus_client = prometheus_client
@asyncio.coroutine async def get(self, request):
def get(self, request):
"""Handle request for Prometheus metrics.""" """Handle request for Prometheus metrics."""
_LOGGER.debug("Received Prometheus metrics request") _LOGGER.debug("Received Prometheus metrics request")

View File

@ -4,7 +4,6 @@ Support for Melnor RainCloud sprinkler water timer.
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/raincloud/ https://home-assistant.io/components/raincloud/
""" """
import asyncio
from datetime import timedelta from datetime import timedelta
import logging import logging
@ -148,8 +147,7 @@ class RainCloudEntity(Entity):
"""Return the name of the sensor.""" """Return the name of the sensor."""
return self._name return self._name
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Register callbacks.""" """Register callbacks."""
async_dispatcher_connect( async_dispatcher_connect(
self.hass, SIGNAL_UPDATE_RAINCLOUD, self._update_callback) self.hass, SIGNAL_UPDATE_RAINCLOUD, self._update_callback)

View File

@ -53,8 +53,7 @@ CONFIG_SCHEMA = vol.Schema({
}, extra=vol.ALLOW_EXTRA) }, extra=vol.ALLOW_EXTRA)
@asyncio.coroutine async def async_setup(hass, config):
def async_setup(hass, config):
"""Set up the REST command component.""" """Set up the REST command component."""
websession = async_get_clientsession(hass) websession = async_get_clientsession(hass)
@ -87,8 +86,7 @@ def async_setup(hass, config):
headers = {} headers = {}
headers[hdrs.CONTENT_TYPE] = content_type headers[hdrs.CONTENT_TYPE] = content_type
@asyncio.coroutine async def async_service_handler(service):
def async_service_handler(service):
"""Execute a shell command service.""" """Execute a shell command service."""
payload = None payload = None
if template_payload: if template_payload:
@ -98,7 +96,7 @@ def async_setup(hass, config):
try: try:
with async_timeout.timeout(timeout, loop=hass.loop): with async_timeout.timeout(timeout, loop=hass.loop):
request = yield from getattr(websession, method)( request = await getattr(websession, method)(
template_url.async_render(variables=service.data), template_url.async_render(variables=service.data),
data=payload, data=payload,
auth=auth, auth=auth,

View File

@ -105,8 +105,7 @@ def identify_event_type(event):
return 'unknown' return 'unknown'
@asyncio.coroutine async def async_setup(hass, config):
def async_setup(hass, config):
"""Set up the Rflink component.""" """Set up the Rflink component."""
from rflink.protocol import create_rflink_connection from rflink.protocol import create_rflink_connection
import serial import serial
@ -125,11 +124,10 @@ def async_setup(hass, config):
# Allow platform to specify function to register new unknown devices # Allow platform to specify function to register new unknown devices
hass.data[DATA_DEVICE_REGISTER] = {} hass.data[DATA_DEVICE_REGISTER] = {}
@asyncio.coroutine async def async_send_command(call):
def async_send_command(call):
"""Send Rflink command.""" """Send Rflink command."""
_LOGGER.debug('Rflink command for %s', str(call.data)) _LOGGER.debug('Rflink command for %s', str(call.data))
if not (yield from RflinkCommand.send_command( if not (await RflinkCommand.send_command(
call.data.get(CONF_DEVICE_ID), call.data.get(CONF_DEVICE_ID),
call.data.get(CONF_COMMAND))): call.data.get(CONF_COMMAND))):
_LOGGER.error('Failed Rflink command for %s', str(call.data)) _LOGGER.error('Failed Rflink command for %s', str(call.data))
@ -196,8 +194,7 @@ def async_setup(hass, config):
_LOGGER.warning('disconnected from Rflink, reconnecting') _LOGGER.warning('disconnected from Rflink, reconnecting')
hass.async_add_job(connect) hass.async_add_job(connect)
@asyncio.coroutine async def connect():
def connect():
"""Set up connection and hook it into HA for reconnect/shutdown.""" """Set up connection and hook it into HA for reconnect/shutdown."""
_LOGGER.info('Initiating Rflink connection') _LOGGER.info('Initiating Rflink connection')
@ -217,7 +214,7 @@ def async_setup(hass, config):
try: try:
with async_timeout.timeout(CONNECTION_TIMEOUT, with async_timeout.timeout(CONNECTION_TIMEOUT,
loop=hass.loop): loop=hass.loop):
transport, protocol = yield from connection transport, protocol = await connection
except (serial.serialutil.SerialException, ConnectionRefusedError, except (serial.serialutil.SerialException, ConnectionRefusedError,
TimeoutError, OSError, asyncio.TimeoutError) as exc: TimeoutError, OSError, asyncio.TimeoutError) as exc:
@ -330,8 +327,7 @@ class RflinkDevice(Entity):
self._available = availability self._available = availability
self.async_schedule_update_ha_state() self.async_schedule_update_ha_state()
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Register update callback.""" """Register update callback."""
async_dispatcher_connect(self.hass, SIGNAL_AVAILABILITY, async_dispatcher_connect(self.hass, SIGNAL_AVAILABILITY,
self.set_availability) self.set_availability)
@ -367,13 +363,11 @@ class RflinkCommand(RflinkDevice):
return bool(cls._protocol) return bool(cls._protocol)
@classmethod @classmethod
@asyncio.coroutine async def send_command(cls, device_id, action):
def send_command(cls, device_id, action):
"""Send device command to Rflink and wait for acknowledgement.""" """Send device command to Rflink and wait for acknowledgement."""
return (yield from cls._protocol.send_command_ack(device_id, action)) return await cls._protocol.send_command_ack(device_id, action)
@asyncio.coroutine async def _async_handle_command(self, command, *args):
def _async_handle_command(self, command, *args):
"""Do bookkeeping for command, send it to rflink and update state.""" """Do bookkeeping for command, send it to rflink and update state."""
self.cancel_queued_send_commands() self.cancel_queued_send_commands()
@ -412,10 +406,10 @@ class RflinkCommand(RflinkDevice):
# Send initial command and queue repetitions. # Send initial command and queue repetitions.
# This allows the entity state to be updated quickly and not having to # This allows the entity state to be updated quickly and not having to
# wait for all repetitions to be sent # wait for all repetitions to be sent
yield from self._async_send_command(cmd, self._signal_repetitions) await self._async_send_command(cmd, self._signal_repetitions)
# Update state of entity # Update state of entity
yield from self.async_update_ha_state() await self.async_update_ha_state()
def cancel_queued_send_commands(self): def cancel_queued_send_commands(self):
"""Cancel queued signal repetition commands. """Cancel queued signal repetition commands.
@ -428,8 +422,7 @@ class RflinkCommand(RflinkDevice):
if self._repetition_task: if self._repetition_task:
self._repetition_task.cancel() self._repetition_task.cancel()
@asyncio.coroutine async def _async_send_command(self, cmd, repetitions):
def _async_send_command(self, cmd, repetitions):
"""Send a command for device to Rflink gateway.""" """Send a command for device to Rflink gateway."""
_LOGGER.debug( _LOGGER.debug(
"Sending command: %s to Rflink device: %s", cmd, self._device_id) "Sending command: %s to Rflink device: %s", cmd, self._device_id)
@ -440,7 +433,7 @@ class RflinkCommand(RflinkDevice):
if self._wait_ack: if self._wait_ack:
# Puts command on outgoing buffer then waits for Rflink to confirm # Puts command on outgoing buffer then waits for Rflink to confirm
# the command has been send out in the ether. # the command has been send out in the ether.
yield from self._protocol.send_command_ack(self._device_id, cmd) await self._protocol.send_command_ack(self._device_id, cmd)
else: else:
# Puts command on outgoing buffer and returns straight away. # Puts command on outgoing buffer and returns straight away.
# Rflink protocol/transport handles asynchronous writing of buffer # Rflink protocol/transport handles asynchronous writing of buffer

View File

@ -4,7 +4,6 @@ Support for RFXtrx components.
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/rfxtrx/ https://home-assistant.io/components/rfxtrx/
""" """
import asyncio
from collections import OrderedDict from collections import OrderedDict
import logging import logging
@ -316,8 +315,7 @@ class RfxtrxDevice(Entity):
self._brightness = 0 self._brightness = 0
self.added_to_hass = False self.added_to_hass = False
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Subscribe RFXtrx events.""" """Subscribe RFXtrx events."""
self.added_to_hass = True self.added_to_hass = True

View File

@ -5,7 +5,6 @@ For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/rss_feed_template/ https://home-assistant.io/components/rss_feed_template/
""" """
import asyncio
from html import escape from html import escape
from aiohttp import web from aiohttp import web
@ -76,8 +75,7 @@ class RssView(HomeAssistantView):
self._title = title self._title = title
self._items = items self._items = items
@asyncio.coroutine async def get(self, request, entity_id=None):
def get(self, request, entity_id=None):
"""Generate the RSS view XML.""" """Generate the RSS view XML."""
response = '<?xml version="1.0" encoding="utf-8"?>\n\n' response = '<?xml version="1.0" encoding="utf-8"?>\n\n'

View File

@ -67,8 +67,7 @@ CONFIG_SCHEMA = vol.Schema({
}, extra=vol.ALLOW_EXTRA) }, extra=vol.ALLOW_EXTRA)
@asyncio.coroutine async def async_setup(hass, config):
def async_setup(hass, config):
"""Set up the Satel Integra component.""" """Set up the Satel Integra component."""
conf = config.get(DOMAIN) conf = config.get(DOMAIN)
@ -83,13 +82,12 @@ def async_setup(hass, config):
hass.data[DATA_SATEL] = controller hass.data[DATA_SATEL] = controller
result = yield from controller.connect() result = await controller.connect()
if not result: if not result:
return False return False
@asyncio.coroutine async def _close():
def _close():
controller.close() controller.close()
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _close()) hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _close())
@ -105,7 +103,7 @@ def async_setup(hass, config):
async_load_platform(hass, 'binary_sensor', DOMAIN, async_load_platform(hass, 'binary_sensor', DOMAIN,
{CONF_ZONES: zones}, config)) {CONF_ZONES: zones}, config))
yield from asyncio.wait([task_control_panel, task_zones], loop=hass.loop) await asyncio.wait([task_control_panel, task_zones], loop=hass.loop)
@callback @callback
def alarm_status_update_callback(status): def alarm_status_update_callback(status):

View File

@ -27,15 +27,13 @@ CONFIG_SCHEMA = vol.Schema({
}, extra=vol.ALLOW_EXTRA) }, extra=vol.ALLOW_EXTRA)
@asyncio.coroutine async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool:
def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool:
"""Set up the shell_command component.""" """Set up the shell_command component."""
conf = config.get(DOMAIN, {}) conf = config.get(DOMAIN, {})
cache = {} cache = {}
@asyncio.coroutine async def async_service_handler(service: ServiceCall) -> None:
def async_service_handler(service: ServiceCall) -> None:
"""Execute a shell command service.""" """Execute a shell command service."""
cmd = conf[service.service] cmd = conf[service.service]
@ -85,8 +83,8 @@ def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool:
stderr=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE,
) )
process = yield from create_process process = await create_process
stdout_data, stderr_data = yield from process.communicate() stdout_data, stderr_data = await process.communicate()
if stdout_data: if stdout_data:
_LOGGER.debug("Stdout of command: `%s`, return code: %s:\n%s", _LOGGER.debug("Stdout of command: `%s`, return code: %s:\n%s",

View File

@ -4,7 +4,6 @@ Support for functionality to keep track of the sun.
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/sun/ https://home-assistant.io/components/sun/
""" """
import asyncio
import logging import logging
from datetime import timedelta from datetime import timedelta
@ -36,8 +35,7 @@ STATE_ATTR_NEXT_RISING = 'next_rising'
STATE_ATTR_NEXT_SETTING = 'next_setting' STATE_ATTR_NEXT_SETTING = 'next_setting'
@asyncio.coroutine async def async_setup(hass, config):
def async_setup(hass, config):
"""Track the state of the sun.""" """Track the state of the sun."""
if config.get(CONF_ELEVATION) is not None: if config.get(CONF_ELEVATION) is not None:
_LOGGER.warning( _LOGGER.warning(

View File

@ -4,7 +4,6 @@ Support for system log.
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/system_log/ https://home-assistant.io/components/system_log/
""" """
import asyncio
from collections import deque from collections import deque
from io import StringIO from io import StringIO
import logging import logging
@ -134,8 +133,7 @@ class LogErrorHandler(logging.Handler):
self.hass.bus.fire(EVENT_SYSTEM_LOG, entry) self.hass.bus.fire(EVENT_SYSTEM_LOG, entry)
@asyncio.coroutine async def async_setup(hass, config):
def async_setup(hass, config):
"""Set up the logger component.""" """Set up the logger component."""
conf = config.get(DOMAIN) conf = config.get(DOMAIN)
if conf is None: if conf is None:
@ -147,8 +145,7 @@ def async_setup(hass, config):
hass.http.register_view(AllErrorsView(handler)) hass.http.register_view(AllErrorsView(handler))
@asyncio.coroutine async def async_service_handler(service):
def async_service_handler(service):
"""Handle logger services.""" """Handle logger services."""
if service.service == 'clear': if service.service == 'clear':
handler.records.clear() handler.records.clear()
@ -159,8 +156,7 @@ def async_setup(hass, config):
level = service.data[CONF_LEVEL] level = service.data[CONF_LEVEL]
getattr(logger, level)(service.data[CONF_MESSAGE]) getattr(logger, level)(service.data[CONF_MESSAGE])
@asyncio.coroutine async def async_shutdown_handler(event):
def async_shutdown_handler(event):
"""Remove logging handler when Home Assistant is shutdown.""" """Remove logging handler when Home Assistant is shutdown."""
# This is needed as older logger instances will remain # This is needed as older logger instances will remain
logging.getLogger().removeHandler(handler) logging.getLogger().removeHandler(handler)
@ -188,8 +184,7 @@ class AllErrorsView(HomeAssistantView):
"""Initialize a new AllErrorsView.""" """Initialize a new AllErrorsView."""
self.handler = handler self.handler = handler
@asyncio.coroutine async def get(self, request):
def get(self, request):
"""Get all errors and warnings.""" """Get all errors and warnings."""
# deque is not serializable (it's just "list-like") so it must be # deque is not serializable (it's just "list-like") so it must be
# converted to a list before it can be serialized to json # converted to a list before it can be serialized to json

View File

@ -4,7 +4,6 @@ Tellstick Component.
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/tellstick/ https://home-assistant.io/components/tellstick/
""" """
import asyncio
import logging import logging
import threading import threading
@ -158,8 +157,7 @@ class TellstickDevice(Entity):
self._tellcore_device = tellcore_device self._tellcore_device = tellcore_device
self._name = tellcore_device.name self._name = tellcore_device.name
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Register callbacks.""" """Register callbacks."""
self.hass.helpers.dispatcher.async_dispatcher_connect( self.hass.helpers.dispatcher.async_dispatcher_connect(
SIGNAL_TELLCORE_CALLBACK, SIGNAL_TELLCORE_CALLBACK,

View File

@ -4,7 +4,6 @@ Support for The Things network.
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/thethingsnetwork/ https://home-assistant.io/components/thethingsnetwork/
""" """
import asyncio
import logging import logging
import voluptuous as vol import voluptuous as vol
@ -32,8 +31,7 @@ CONFIG_SCHEMA = vol.Schema({
}, extra=vol.ALLOW_EXTRA) }, extra=vol.ALLOW_EXTRA)
@asyncio.coroutine async def async_setup(hass, config):
def async_setup(hass, config):
"""Initialize of The Things Network component.""" """Initialize of The Things Network component."""
conf = config[DOMAIN] conf = config[DOMAIN]
app_id = conf.get(CONF_APP_ID) app_id = conf.get(CONF_APP_ID)

View File

@ -4,7 +4,6 @@ Support for UpCloud.
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/upcloud/ https://home-assistant.io/components/upcloud/
""" """
import asyncio
import logging import logging
from datetime import timedelta from datetime import timedelta
@ -129,8 +128,7 @@ class UpCloudServerEntity(Entity):
except (AttributeError, KeyError, TypeError): except (AttributeError, KeyError, TypeError):
return DEFAULT_COMPONENT_NAME.format(self.uuid) return DEFAULT_COMPONENT_NAME.format(self.uuid)
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Register callbacks.""" """Register callbacks."""
async_dispatcher_connect( async_dispatcher_connect(
self.hass, SIGNAL_UPDATE_UPCLOUD, self._update_callback) self.hass, SIGNAL_UPDATE_UPCLOUD, self._update_callback)

View File

@ -4,7 +4,6 @@ Component to wake up devices sending Wake-On-LAN magic packets.
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/wake_on_lan/ https://home-assistant.io/components/wake_on_lan/
""" """
import asyncio
from functools import partial from functools import partial
import logging import logging
@ -29,24 +28,22 @@ WAKE_ON_LAN_SEND_MAGIC_PACKET_SCHEMA = vol.Schema({
}) })
@asyncio.coroutine async def async_setup(hass, config):
def async_setup(hass, config):
"""Set up the wake on LAN component.""" """Set up the wake on LAN component."""
import wakeonlan import wakeonlan
@asyncio.coroutine async def send_magic_packet(call):
def send_magic_packet(call):
"""Send magic packet to wake up a device.""" """Send magic packet to wake up a device."""
mac_address = call.data.get(CONF_MAC) mac_address = call.data.get(CONF_MAC)
broadcast_address = call.data.get(CONF_BROADCAST_ADDRESS) broadcast_address = call.data.get(CONF_BROADCAST_ADDRESS)
_LOGGER.info("Send magic packet to mac %s (broadcast: %s)", _LOGGER.info("Send magic packet to mac %s (broadcast: %s)",
mac_address, broadcast_address) mac_address, broadcast_address)
if broadcast_address is not None: if broadcast_address is not None:
yield from hass.async_add_job( await hass.async_add_job(
partial(wakeonlan.send_magic_packet, mac_address, partial(wakeonlan.send_magic_packet, mac_address,
ip_address=broadcast_address)) ip_address=broadcast_address))
else: else:
yield from hass.async_add_job( await hass.async_add_job(
partial(wakeonlan.send_magic_packet, mac_address)) partial(wakeonlan.send_magic_packet, mac_address))
hass.services.async_register( hass.services.async_register(

View File

@ -4,7 +4,6 @@ Weather component that handles meteorological data for your location.
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/weather/ https://home-assistant.io/components/weather/
""" """
import asyncio
import logging import logging
from homeassistant.helpers.entity_component import EntityComponent from homeassistant.helpers.entity_component import EntityComponent
@ -39,12 +38,11 @@ ATTR_WEATHER_WIND_BEARING = 'wind_bearing'
ATTR_WEATHER_WIND_SPEED = 'wind_speed' ATTR_WEATHER_WIND_SPEED = 'wind_speed'
@asyncio.coroutine async def async_setup(hass, config):
def async_setup(hass, config):
"""Set up the weather component.""" """Set up the weather component."""
component = EntityComponent(_LOGGER, DOMAIN, hass) component = EntityComponent(_LOGGER, DOMAIN, hass)
yield from component.async_setup(config) await component.async_setup(config)
return True return True

View File

@ -5,7 +5,6 @@ For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/weather.buienradar/ https://home-assistant.io/components/weather.buienradar/
""" """
import logging import logging
import asyncio
import voluptuous as vol import voluptuous as vol
@ -55,8 +54,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 buienradar platform.""" """Set up the buienradar platform."""
latitude = config.get(CONF_LATITUDE, hass.config.latitude) latitude = config.get(CONF_LATITUDE, hass.config.latitude)
@ -86,7 +84,7 @@ def async_setup_platform(hass, config, async_add_entities,
async_add_entities([BrWeather(data, config)]) async_add_entities([BrWeather(data, config)])
# schedule the first update in 1 minute from now: # schedule the first update in 1 minute from now:
yield from data.schedule_update(1) await data.schedule_update(1)
class BrWeather(WeatherEntity): class BrWeather(WeatherEntity):

View File

@ -4,7 +4,6 @@ Support for Wink hubs.
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/wink/ https://home-assistant.io/components/wink/
""" """
import asyncio
from datetime import timedelta from datetime import timedelta
import json import json
import logging import logging
@ -763,8 +762,7 @@ class WinkDevice(Entity):
class WinkSirenDevice(WinkDevice): class WinkSirenDevice(WinkDevice):
"""Representation of a Wink siren device.""" """Representation of a Wink siren device."""
@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']['switch'].append(self) self.hass.data[DOMAIN]['entities']['switch'].append(self)
@ -824,8 +822,7 @@ class WinkNimbusDialDevice(WinkDevice):
super().__init__(dial, hass) super().__init__(dial, hass)
self.parent = nimbus self.parent = nimbus
@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']['sensor'].append(self) self.hass.data[DOMAIN]['entities']['sensor'].append(self)

View File

@ -4,7 +4,6 @@ Support for Xiaomi Gateways.
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/xiaomi_aqara/ https://home-assistant.io/components/xiaomi_aqara/
""" """
import asyncio
import logging import logging
from datetime import timedelta from datetime import timedelta
@ -113,8 +112,7 @@ def setup(hass, config):
interface = config[DOMAIN][CONF_INTERFACE] interface = config[DOMAIN][CONF_INTERFACE]
discovery_retry = config[DOMAIN][CONF_DISCOVERY_RETRY] discovery_retry = config[DOMAIN][CONF_DISCOVERY_RETRY]
@asyncio.coroutine async def xiaomi_gw_discovered(service, discovery_info):
def xiaomi_gw_discovered(service, discovery_info):
"""Perform action when Xiaomi Gateway device(s) has been found.""" """Perform action when Xiaomi Gateway device(s) has been found."""
# We don't need to do anything here, the purpose of Home Assistant's # We don't need to do anything here, the purpose of Home Assistant's
# discovery service is to just trigger loading of this # discovery service is to just trigger loading of this
@ -233,8 +231,7 @@ class XiaomiDevice(Entity):
def _add_push_data_job(self, *args): def _add_push_data_job(self, *args):
self.hass.add_job(self.push_data, *args) self.hass.add_job(self.push_data, *args)
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Start unavailability tracking.""" """Start unavailability tracking."""
self._xiaomi_hub.callbacks[self._sid].append(self._add_push_data_job) self._xiaomi_hub.callbacks[self._sid].append(self._add_push_data_job)
self._async_track_unavailable() self._async_track_unavailable()

View File

@ -4,7 +4,6 @@ Support for ZigBee devices.
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/zigbee/ https://home-assistant.io/components/zigbee/
""" """
import asyncio
import logging import logging
from binascii import hexlify, unhexlify from binascii import hexlify, unhexlify
@ -277,8 +276,7 @@ class ZigBeeDigitalIn(Entity):
self._config = config self._config = config
self._state = False self._state = False
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Register callbacks.""" """Register callbacks."""
def handle_frame(frame): def handle_frame(frame):
"""Handle an incoming frame. """Handle an incoming frame.
@ -403,8 +401,7 @@ class ZigBeeAnalogIn(Entity):
self._config = config self._config = config
self._value = None self._value = None
@asyncio.coroutine async def async_added_to_hass(self):
def async_added_to_hass(self):
"""Register callbacks.""" """Register callbacks."""
def handle_frame(frame): def handle_frame(frame):
"""Handle an incoming frame. """Handle an incoming frame.