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)
@asyncio.coroutine
def async_reload_core_config(hass):
async def async_reload_core_config(hass):
"""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
def async_setup(hass: ha.HomeAssistant, config: dict) -> Awaitable[bool]:
async def async_setup(hass: ha.HomeAssistant, config: dict) -> Awaitable[bool]:
"""Set up general services related to Home Assistant."""
@asyncio.coroutine
def async_handle_turn_service(service):
async def async_handle_turn_service(service):
"""Handle calls to homeassistant.turn_on/off."""
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(
domain, service.service, data, blocking))
yield from asyncio.wait(tasks, loop=hass.loop)
await asyncio.wait(tasks, loop=hass.loop)
hass.services.async_register(
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(
intent.INTENT_TOGGLE, ha.DOMAIN, SERVICE_TOGGLE, "Toggled {}"))
@asyncio.coroutine
def async_handle_core_service(call):
async def async_handle_core_service(call):
"""Service handler for handling core services."""
if call.service == SERVICE_HOMEASSISTANT_STOP:
hass.async_create_task(hass.async_stop())
return
try:
errors = yield from conf_util.async_check_ha_config_file(hass)
errors = await conf_util.async_check_ha_config_file(hass)
except HomeAssistantError:
return
@ -193,16 +189,15 @@ def async_setup(hass: ha.HomeAssistant, config: dict) -> Awaitable[bool]:
hass.services.async_register(
ha.DOMAIN, SERVICE_CHECK_CONFIG, async_handle_core_service)
@asyncio.coroutine
def async_handle_reload_config(call):
async def async_handle_reload_config(call):
"""Service handler for reloading core config."""
try:
conf = yield from conf_util.async_hass_config_yaml(hass)
conf = await conf_util.async_hass_config_yaml(hass)
except HomeAssistantError as err:
_LOGGER.error(err)
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.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
https://home-assistant.io/components/abode/
"""
import asyncio
import logging
from functools import partial
from requests.exceptions import HTTPError, ConnectTimeout
@ -261,8 +260,7 @@ class AbodeDevice(Entity):
self._data = data
self._device = device
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Subscribe Abode events."""
self.hass.async_add_job(
self._data.abode.events.add_device_callback,
@ -308,8 +306,7 @@ class AbodeAutomation(Entity):
self._automation = automation
self._event = event
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Subscribe Abode events."""
if self._event:
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
https://home-assistant.io/components/alexa/
"""
import asyncio
import logging
import voluptuous as vol
@ -53,8 +52,7 @@ CONFIG_SCHEMA = vol.Schema({
}, extra=vol.ALLOW_EXTRA)
@asyncio.coroutine
def async_setup(hass, config):
async def async_setup(hass, config):
"""Activate Alexa component."""
config = config.get(DOMAIN, {})
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
https://home-assistant.io/components/alexa/
"""
import asyncio
import enum
import logging
@ -59,16 +58,15 @@ class AlexaIntentsView(http.HomeAssistantView):
url = INTENTS_API_ENDPOINT
name = 'api:alexa'
@asyncio.coroutine
def post(self, request):
async def post(self, request):
"""Handle Alexa."""
hass = request.app['hass']
message = yield from request.json()
message = await request.json()
_LOGGER.debug("Received Alexa request: %s", message)
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)
except UnknownRequest as err:
_LOGGER.warning(str(err))
@ -101,8 +99,7 @@ def intent_error_response(hass, message, error):
return alexa_response.as_dict()
@asyncio.coroutine
def async_handle_message(hass, message):
async def async_handle_message(hass, message):
"""Handle an Alexa intent.
Raises:
@ -120,20 +117,18 @@ def async_handle_message(hass, message):
if not handler:
raise UnknownRequest('Received unknown request {}'.format(req_type))
return (yield from handler(hass, message))
return await handler(hass, message)
@HANDLERS.register('SessionEndedRequest')
@asyncio.coroutine
def async_handle_session_end(hass, message):
async def async_handle_session_end(hass, message):
"""Handle a session end request."""
return None
@HANDLERS.register('IntentRequest')
@HANDLERS.register('LaunchRequest')
@asyncio.coroutine
def async_handle_intent(hass, message):
async def async_handle_intent(hass, message):
"""Handle an intent request.
Raises:
@ -153,7 +148,7 @@ def async_handle_intent(hass, message):
else:
intent_name = alexa_intent_info['name']
intent_response = yield from intent.async_handle(
intent_response = await intent.async_handle(
hass, DOMAIN, intent_name,
{key: {'value': value} for key, value
in alexa_response.variables.items()})

View file

@ -1,5 +1,4 @@
"""Support for alexa Smart Home Skill API."""
import asyncio
import logging
import math
from datetime import datetime
@ -695,8 +694,7 @@ class SmartHomeView(http.HomeAssistantView):
"""Initialize."""
self.smart_home_config = smart_home_config
@asyncio.coroutine
def post(self, request):
async def post(self, request):
"""Handle Alexa Smart Home requests.
The Smart Home API requires the endpoint to be implemented in AWS
@ -704,11 +702,11 @@ class SmartHomeView(http.HomeAssistantView):
the response.
"""
hass = request.app['hass']
message = yield from request.json()
message = await request.json()
_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)
_LOGGER.debug("Sending Alexa Smart Home response: %s", 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)
@asyncio.coroutine
def async_setup(hass, config):
async def async_setup(hass, config):
"""Set up the IP Webcam component."""
from pydroid_ipcam import PyDroidIPCam
webcams = hass.data[DATA_IP_WEBCAM] = {}
websession = async_get_clientsession(hass)
@asyncio.coroutine
def async_setup_ipcamera(cam_config):
async def async_setup_ipcamera(cam_config):
"""Set up an IP camera."""
host = cam_config[CONF_HOST]
username = cam_config.get(CONF_USERNAME)
@ -188,16 +186,15 @@ def async_setup(hass, config):
if motion is None:
motion = 'motion_active' in cam.enabled_sensors
@asyncio.coroutine
def async_update_data(now):
async def async_update_data(now):
"""Update data from IP camera in SCAN_INTERVAL."""
yield from cam.update()
await cam.update()
async_dispatcher_send(hass, SIGNAL_UPDATE_DATA, host)
async_track_point_in_utc_time(
hass, async_update_data, utcnow() + interval)
yield from async_update_data(None)
await async_update_data(None)
# Load platforms
webcams[host] = cam
@ -242,7 +239,7 @@ def async_setup(hass, config):
tasks = [async_setup_ipcamera(conf) for conf in config[DOMAIN]]
if tasks:
yield from asyncio.wait(tasks, loop=hass.loop)
await asyncio.wait(tasks, loop=hass.loop)
return True
@ -255,8 +252,7 @@ class AndroidIPCamEntity(Entity):
self._host = host
self._ipcam = ipcam
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Register update dispatcher."""
@callback
def async_ipcam_update(host):

View file

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

View file

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

View file

@ -35,8 +35,7 @@ COMPONENTS_WITH_DEMO_PLATFORM = [
]
@asyncio.coroutine
def async_setup(hass, config):
async def async_setup(hass, config):
"""Set up the demo environment."""
group = hass.components.group
configurator = hass.components.configurator
@ -101,7 +100,7 @@ def async_setup(hass, config):
{'weblink': {'entities': [{'name': 'Router',
'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):
return False
@ -192,7 +191,7 @@ def async_setup(hass, config):
'climate.ecobee',
], 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):
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
https://home-assistant.io/components/device_sun_light_trigger/
"""
import asyncio
import logging
from datetime import timedelta
@ -45,8 +44,7 @@ CONFIG_SCHEMA = vol.Schema({
}, extra=vol.ALLOW_EXTRA)
@asyncio.coroutine
def async_setup(hass, config):
async def async_setup(hass, config):
"""Set up the triggers to control lights based on device presence."""
logger = logging.getLogger(__name__)
device_tracker = hass.components.device_tracker

View file

@ -6,7 +6,6 @@ https://home-assistant.io/components/doorbird/
"""
import logging
import asyncio
import voluptuous as vol
from homeassistant.components.http import HomeAssistantView
@ -170,8 +169,7 @@ class DoorbirdRequestView(HomeAssistantView):
extra_urls = [API_URL + '/{sensor}']
# pylint: disable=no-self-use
@asyncio.coroutine
def get(self, request, sensor):
async def get(self, request, sensor):
"""Respond to requests from the device."""
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
https://home-assistant.io/components/duckdns/
"""
import asyncio
from datetime import timedelta
import logging
@ -39,27 +38,24 @@ SERVICE_TXT_SCHEMA = vol.Schema({
})
@asyncio.coroutine
def async_setup(hass, config):
async def async_setup(hass, config):
"""Initialize the DuckDNS component."""
domain = config[DOMAIN][CONF_DOMAIN]
token = config[DOMAIN][CONF_ACCESS_TOKEN]
session = async_get_clientsession(hass)
result = yield from _update_duckdns(session, domain, token)
result = await _update_duckdns(session, domain, token)
if not result:
return False
@asyncio.coroutine
def update_domain_interval(now):
async def update_domain_interval(now):
"""Update the DuckDNS entry."""
yield from _update_duckdns(session, domain, token)
await _update_duckdns(session, domain, token)
@asyncio.coroutine
def update_domain_service(call):
async def update_domain_service(call):
"""Update the DuckDNS entry."""
yield from _update_duckdns(
await _update_duckdns(
session, domain, token, txt=call.data[ATTR_TXT])
async_track_time_interval(hass, update_domain_interval, INTERVAL)
@ -73,8 +69,8 @@ def async_setup(hass, config):
_SENTINEL = object()
@asyncio.coroutine
def _update_duckdns(session, domain, token, *, txt=_SENTINEL, clear=False):
async def _update_duckdns(session, domain, token, *, txt=_SENTINEL,
clear=False):
"""Update DuckDNS."""
params = {
'domains': domain,
@ -92,8 +88,8 @@ def _update_duckdns(session, domain, token, *, txt=_SENTINEL, clear=False):
if clear:
params['clear'] = 'true'
resp = yield from session.get(UPDATE_URL, params=params)
body = yield from resp.text()
resp = await session.get(UPDATE_URL, params=params)
body = await resp.text()
if body != 'OK':
_LOGGER.warning("Updating DuckDNS domain failed: %s", domain)

View file

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

View file

@ -81,8 +81,7 @@ CONFIG_SCHEMA = vol.Schema({
}, extra=vol.ALLOW_EXTRA)
@asyncio.coroutine
def async_setup(hass, config):
async def async_setup(hass, config):
"""Set up for Envisalink devices."""
from pyenvisalink import EnvisalinkAlarmPanel
@ -165,7 +164,7 @@ def async_setup(hass, config):
_LOGGER.info("Start envisalink.")
controller.start()
result = yield from sync_connect
result = await sync_connect
if not result:
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
https://home-assistant.io/components/ffmpeg/
"""
import asyncio
import logging
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))
@asyncio.coroutine
def async_setup(hass, config):
async def async_setup(hass, config):
"""Set up the FFmpeg component."""
conf = config.get(DOMAIN, {})
@ -88,8 +86,7 @@ def async_setup(hass, config):
)
# Register service
@asyncio.coroutine
def async_service_handle(service):
async def async_service_handle(service):
"""Handle service ffmpeg process."""
entity_ids = service.data.get(ATTR_ENTITY_ID)
@ -131,8 +128,7 @@ class FFmpegManager:
"""Return ffmpeg binary from config."""
return self._bin
@asyncio.coroutine
def async_run_test(self, input_source):
async def async_run_test(self, input_source):
"""Run test on this input. TRUE is deactivate or run correct.
This method must be run in the event loop.
@ -146,7 +142,7 @@ class FFmpegManager:
# run test
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:
_LOGGER.error("FFmpeg '%s' test fails!", input_source)
self._cache[input_source] = False
@ -163,8 +159,7 @@ class FFmpegBase(Entity):
self.ffmpeg = None
self.initial_state = initial_state
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Register dispatcher & events.
This method is a coroutine.
@ -189,40 +184,36 @@ class FFmpegBase(Entity):
"""Return True if entity has to be polled for state."""
return False
@asyncio.coroutine
def _async_start_ffmpeg(self, entity_ids):
async def _async_start_ffmpeg(self, entity_ids):
"""Start a FFmpeg process.
This method is a coroutine.
"""
raise NotImplementedError()
@asyncio.coroutine
def _async_stop_ffmpeg(self, entity_ids):
async def _async_stop_ffmpeg(self, entity_ids):
"""Stop a FFmpeg process.
This method is a coroutine.
"""
if entity_ids is None or self.entity_id in entity_ids:
yield from self.ffmpeg.close()
await self.ffmpeg.close()
@asyncio.coroutine
def _async_restart_ffmpeg(self, entity_ids):
async def _async_restart_ffmpeg(self, entity_ids):
"""Stop a FFmpeg process.
This method is a coroutine.
"""
if entity_ids is None or self.entity_id in entity_ids:
yield from self._async_stop_ffmpeg(None)
yield from self._async_start_ffmpeg(None)
await self._async_stop_ffmpeg(None)
await self._async_start_ffmpeg(None)
@callback
def _async_register_events(self):
"""Register a FFmpeg process/device."""
@asyncio.coroutine
def async_shutdown_handle(event):
async def async_shutdown_handle(event):
"""Stop FFmpeg process."""
yield from self._async_stop_ffmpeg(None)
await self._async_stop_ffmpeg(None)
self.hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, async_shutdown_handle)
@ -231,10 +222,9 @@ class FFmpegBase(Entity):
if not self.initial_state:
return
@asyncio.coroutine
def async_start_handle(event):
async def async_start_handle(event):
"""Start FFmpeg process."""
yield from self._async_start_ffmpeg(None)
await self._async_start_ffmpeg(None)
self.async_schedule_update_ha_state()
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
https://home-assistant.io/components/foursquare/
"""
import asyncio
import logging
import requests
@ -85,11 +84,10 @@ class FoursquarePushReceiver(HomeAssistantView):
"""Initialize the OAuth callback view."""
self.push_secret = push_secret
@asyncio.coroutine
def post(self, request):
async def post(self, request):
"""Accept the POST from Foursquare."""
try:
data = yield from request.json()
data = await request.json()
except ValueError:
return self.json_message('Invalid JSON', HTTP_BAD_REQUEST)

View file

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

View file

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

View file

@ -4,7 +4,6 @@ Support for HomeMatic devices.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/homematic/
"""
import asyncio
from datetime import timedelta
from functools import partial
import logging
@ -715,10 +714,9 @@ class HMDevice(Entity):
if self._state:
self._state = self._state.upper()
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Load data init callbacks."""
yield from self.hass.async_add_job(self.link_homematic)
await self.hass.async_add_job(self.link_homematic)
@property
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
https://home-assistant.io/components/hydrawise/
"""
import asyncio
from datetime import timedelta
import logging
@ -127,8 +126,7 @@ class HydrawiseEntity(Entity):
"""Return the name of the sensor."""
return self._name
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Register callbacks."""
async_dispatcher_connect(
self.hass, SIGNAL_UPDATE_HYDRAWISE, self._update_callback)

View file

@ -1,5 +1,4 @@
"""Implementation of a base class for all IHC devices."""
import asyncio
from homeassistant.helpers.entity import Entity
@ -28,8 +27,7 @@ class IHCDevice(Entity):
self.ihc_note = ''
self.ihc_position = ''
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Add callback for IHC changes."""
self.ihc_controller.add_notify_event(
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
https://home-assistant.io/components/insteon/
"""
import asyncio
import collections
import logging
from typing import Dict
@ -149,8 +148,7 @@ X10_HOUSECODE_SCHEMA = vol.Schema({
})
@asyncio.coroutine
def async_setup(hass, config):
async def async_setup(hass, config):
"""Set up the connection to the modem."""
import insteonplm
@ -292,7 +290,7 @@ def async_setup(hass, config):
if host:
_LOGGER.info('Connecting to Insteon Hub on %s', host)
conn = yield from insteonplm.Connection.create(
conn = await insteonplm.Connection.create(
host=host,
port=ip_port,
username=username,
@ -302,7 +300,7 @@ def async_setup(hass, config):
workdir=hass.config.config_dir)
else:
_LOGGER.info("Looking for Insteon PLM on %s", port)
conn = yield from insteonplm.Connection.create(
conn = await insteonplm.Connection.create(
device=port,
loop=hass.loop,
workdir=hass.config.config_dir)
@ -494,8 +492,7 @@ class InsteonEntity(Entity):
deviceid.human, group, val)
self.async_schedule_update_ha_state()
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Register INSTEON update events."""
_LOGGER.debug('Tracking updates for device %s group %d statename %s',
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
https://home-assistant.io/components/insteon_plm/
"""
import asyncio
import logging
_LOGGER = logging.getLogger(__name__)
@asyncio.coroutine
def async_setup(hass, config):
async def async_setup(hass, config):
"""Set up the insteon_plm component.
This component is deprecated as of release 0.77 and should be removed in

View file

@ -1,5 +1,4 @@
"""Handle intents with scripts."""
import asyncio
import copy
import logging
@ -45,8 +44,7 @@ CONFIG_SCHEMA = vol.Schema({
_LOGGER = logging.getLogger(__name__)
@asyncio.coroutine
def async_setup(hass, config):
async def async_setup(hass, config):
"""Activate Alexa component."""
intents = copy.deepcopy(config[DOMAIN])
template.attach(hass, intents)
@ -69,8 +67,7 @@ class ScriptIntentHandler(intent.IntentHandler):
self.intent_type = intent_type
self.config = config
@asyncio.coroutine
def async_handle(self, intent_obj):
async def async_handle(self, intent_obj):
"""Handle the intent."""
speech = self.config.get(CONF_SPEECH)
card = self.config.get(CONF_CARD)
@ -83,7 +80,7 @@ class ScriptIntentHandler(intent.IntentHandler):
if is_async_action:
intent_obj.hass.async_add_job(action.async_run(slots))
else:
yield from action.async_run(slots)
await action.async_run(slots)
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
https://home-assistant.io/components/introduction/
"""
import asyncio
import logging
import voluptuous as vol
@ -16,8 +15,7 @@ CONFIG_SCHEMA = vol.Schema({
}, extra=vol.ALLOW_EXTRA)
@asyncio.coroutine
def async_setup(hass, config=None):
async def async_setup(hass, config=None):
"""Set up the introduction component."""
log = logging.getLogger(__name__)
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
https://home-assistant.io/ecosystem/ios/
"""
import asyncio
import logging
import datetime
@ -259,11 +258,10 @@ class iOSIdentifyDeviceView(HomeAssistantView):
"""Initiliaze the view."""
self._config_path = config_path
@asyncio.coroutine
def post(self, request):
async def post(self, request):
"""Handle the POST request for device identification."""
try:
data = yield from request.json()
data = await request.json()
except ValueError:
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
https://home-assistant.io/components/isy994/
"""
import asyncio
from collections import namedtuple
import logging
from urllib.parse import urlparse
@ -414,8 +413,7 @@ class ISYDevice(Entity):
self._change_handler = None
self._control_handler = None
@asyncio.coroutine
def async_added_to_hass(self) -> None:
async def async_added_to_hass(self) -> None:
"""Subscribe to the node change events."""
self._change_handler = self._node.status.subscribe(
'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
https://home-assistant.io/components/lutron/
"""
import asyncio
import logging
import voluptuous as vol
@ -69,8 +68,7 @@ class LutronDevice(Entity):
self._controller = controller
self._area_name = area_name
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Register callbacks."""
self.hass.async_add_job(
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
https://home-assistant.io/components/lutron_caseta/
"""
import asyncio
import logging
import voluptuous as vol
@ -40,8 +39,7 @@ LUTRON_CASETA_COMPONENTS = [
]
@asyncio.coroutine
def async_setup(hass, base_config):
async def async_setup(hass, base_config):
"""Set up the Lutron component."""
from pylutron_caseta.smartbridge import Smartbridge
@ -54,7 +52,7 @@ def async_setup(hass, base_config):
certfile=certfile,
ca_certs=ca_certs)
hass.data[LUTRON_CASETA_SMARTBRIDGE] = bridge
yield from bridge.connect()
await bridge.connect()
if not hass.data[LUTRON_CASETA_SMARTBRIDGE].is_connected():
_LOGGER.error("Unable to connect to Lutron smartbridge at %s",
config[CONF_HOST])
@ -85,8 +83,7 @@ class LutronCasetaDevice(Entity):
self._state = None
self._smartbridge = bridge
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Register callbacks."""
self._smartbridge.add_subscriber(self._device_id,
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)
@asyncio.coroutine
def async_setup(hass, config):
async def async_setup(hass, config):
"""Set up Microsoft Face."""
entities = {}
face = MicrosoftFace(
@ -120,26 +119,25 @@ def async_setup(hass, config):
try:
# read exists group/person from cloud and create entities
yield from face.update_store()
await face.update_store()
except HomeAssistantError as err:
_LOGGER.error("Can't load data from face api: %s", err)
return False
hass.data[DATA_MICROSOFT_FACE] = face
@asyncio.coroutine
def async_create_group(service):
async def async_create_group(service):
"""Create a new person group."""
name = service.data[ATTR_NAME]
g_id = slugify(name)
try:
yield from face.call_api(
await face.call_api(
'put', "persongroups/{0}".format(g_id), {'name': name})
face.store[g_id] = {}
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:
_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,
schema=SCHEMA_GROUP_SERVICE)
@asyncio.coroutine
def async_delete_group(service):
async def async_delete_group(service):
"""Delete a person group."""
g_id = slugify(service.data[ATTR_NAME])
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)
entity = entities.pop(g_id)
@ -165,13 +162,12 @@ def async_setup(hass, config):
DOMAIN, SERVICE_DELETE_GROUP, async_delete_group,
schema=SCHEMA_GROUP_SERVICE)
@asyncio.coroutine
def async_train_group(service):
async def async_train_group(service):
"""Train a person group."""
g_id = service.data[ATTR_GROUP]
try:
yield from face.call_api(
await face.call_api(
'post', "persongroups/{0}/train".format(g_id))
except HomeAssistantError as 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,
schema=SCHEMA_TRAIN_SERVICE)
@asyncio.coroutine
def async_create_person(service):
async def async_create_person(service):
"""Create a person in a group."""
name = service.data[ATTR_NAME]
g_id = service.data[ATTR_GROUP]
try:
user_data = yield from face.call_api(
user_data = await face.call_api(
'post', "persongroups/{0}/persons".format(g_id), {'name': name}
)
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:
_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,
schema=SCHEMA_PERSON_SERVICE)
@asyncio.coroutine
def async_delete_person(service):
async def async_delete_person(service):
"""Delete a person in a group."""
name = service.data[ATTR_NAME]
g_id = service.data[ATTR_GROUP]
p_id = face.store[g_id].get(name)
try:
yield from face.call_api(
await face.call_api(
'delete', "persongroups/{0}/persons/{1}".format(g_id, p_id))
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:
_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,
schema=SCHEMA_PERSON_SERVICE)
@asyncio.coroutine
def async_face_person(service):
async def async_face_person(service):
"""Add a new face picture to a person."""
g_id = service.data[ATTR_GROUP]
p_id = face.store[g_id].get(service.data[ATTR_PERSON])
@ -230,9 +223,9 @@ def async_setup(hass, config):
camera = hass.components.camera
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',
"persongroups/{0}/persons/{1}/persistedFaces".format(
g_id, p_id),
@ -307,10 +300,9 @@ class MicrosoftFace:
"""Store group/person data and IDs."""
return self._store
@asyncio.coroutine
def update_store(self):
async def update_store(self):
"""Load all group/person data into local store."""
groups = yield from self.call_api('get', 'persongroups')
groups = await self.call_api('get', 'persongroups')
tasks = []
for group in groups:
@ -319,7 +311,7 @@ class MicrosoftFace:
self._entities[g_id] = MicrosoftFaceGroupEntity(
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))
for person in persons:
@ -328,11 +320,10 @@ class MicrosoftFace:
tasks.append(self._entities[g_id].async_update_ha_state())
if tasks:
yield from asyncio.wait(tasks, loop=self.hass.loop)
await asyncio.wait(tasks, loop=self.hass.loop)
@asyncio.coroutine
def call_api(self, method, function, data=None, binary=False,
params=None):
async def call_api(self, method, function, data=None, binary=False,
params=None):
"""Make an api call."""
headers = {"Ocp-Apim-Subscription-Key": self._api_key}
url = self._server_url.format(function)
@ -350,10 +341,10 @@ class MicrosoftFace:
try:
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)
answer = yield from response.json()
answer = await response.json()
_LOGGER.debug("Read from microsoft face api: %s", answer)
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
https://home-assistant.io/components/mqtt_statestream/
"""
import asyncio
import json
import voluptuous as vol
@ -43,8 +42,7 @@ CONFIG_SCHEMA = vol.Schema({
}, extra=vol.ALLOW_EXTRA)
@asyncio.coroutine
def async_setup(hass, config):
async def async_setup(hass, config):
"""Set up the MQTT state feed."""
conf = config.get(DOMAIN, {})
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
https://home-assistant.io/components/namecheapdns/
"""
import asyncio
import logging
from datetime import timedelta
@ -32,8 +31,7 @@ CONFIG_SCHEMA = vol.Schema({
}, extra=vol.ALLOW_EXTRA)
@asyncio.coroutine
def async_setup(hass, config):
async def async_setup(hass, config):
"""Initialize the namecheap DNS component."""
host = config[DOMAIN][CONF_HOST]
domain = config[DOMAIN][CONF_DOMAIN]
@ -41,23 +39,21 @@ def async_setup(hass, config):
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:
return False
@asyncio.coroutine
def update_domain_interval(now):
async def update_domain_interval(now):
"""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)
return result
@asyncio.coroutine
def _update_namecheapdns(session, host, domain, password):
async def _update_namecheapdns(session, host, domain, password):
"""Update namecheap DNS entry."""
import xml.etree.ElementTree as ET
@ -67,8 +63,8 @@ def _update_namecheapdns(session, host, domain, password):
'password': password,
}
resp = yield from session.get(UPDATE_URL, params=params)
xml_string = yield from resp.text()
resp = await session.get(UPDATE_URL, params=params)
xml_string = await resp.text()
root = ET.fromstring(xml_string)
err_count = root.find('ErrCount').text

View file

@ -53,8 +53,7 @@ CONFIG_SCHEMA = vol.Schema({
}, extra=vol.ALLOW_EXTRA)
@asyncio.coroutine
def async_setup(hass, config):
async def async_setup(hass, config):
"""Initialize the NO-IP component."""
domain = config[DOMAIN].get(CONF_DOMAIN)
user = config[DOMAIN].get(CONF_USERNAME)
@ -65,16 +64,15 @@ def async_setup(hass, config):
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)
if not result:
return False
@asyncio.coroutine
def update_domain_interval(now):
async def update_domain_interval(now):
"""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(
update_domain_interval, INTERVAL)
@ -82,8 +80,7 @@ def async_setup(hass, config):
return True
@asyncio.coroutine
def _update_no_ip(hass, session, domain, auth_str, timeout):
async def _update_no_ip(hass, session, domain, auth_str, timeout):
"""Update NO-IP."""
url = UPDATE_URL
@ -98,8 +95,8 @@ def _update_no_ip(hass, session, domain, auth_str, timeout):
try:
with async_timeout.timeout(timeout, loop=hass.loop):
resp = yield from session.get(url, params=params, headers=headers)
body = yield from resp.text()
resp = await session.get(url, params=params, headers=headers)
body = await resp.text()
if body.startswith('good') or body.startswith('nochg'):
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
https://home-assistant.io/components/persistent_notification/
"""
import asyncio
import logging
from collections import OrderedDict
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))
@asyncio.coroutine
def async_setup(hass: HomeAssistant, config: dict) -> Awaitable[bool]:
async def async_setup(hass: HomeAssistant, config: dict) -> Awaitable[bool]:
"""Set up the persistent notification component."""
persistent_notifications = OrderedDict()
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/
"""
import logging
import asyncio
from datetime import datetime, timedelta
from collections import deque
import voluptuous as vol
@ -97,8 +96,7 @@ CONFIG_SCHEMA = vol.Schema({
ENABLE_LOAD_HISTORY = False
@asyncio.coroutine
def async_setup(hass, config):
async def async_setup(hass, config):
"""Set up the Plant component."""
component = EntityComponent(_LOGGER, DOMAIN, hass,
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)
entities.append(entity)
yield from component.async_add_entities(entities)
await component.async_add_entities(entities)
return True
@ -246,15 +244,13 @@ class Plant(Entity):
return '{} high'.format(sensor_name)
return None
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""After being added to hass, load from history."""
if ENABLE_LOAD_HISTORY and 'recorder' in self.hass.config.components:
# only use the database if it's configured
self.hass.async_add_job(self._load_history_from_db)
@asyncio.coroutine
def _load_history_from_db(self):
async def _load_history_from_db(self):
"""Load the history of the brightness values from the database.
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
https://home-assistant.io/components/prometheus/
"""
import asyncio
import logging
import voluptuous as vol
@ -265,8 +264,7 @@ class PrometheusView(HomeAssistantView):
"""Initialize Prometheus view."""
self.prometheus_client = prometheus_client
@asyncio.coroutine
def get(self, request):
async def get(self, request):
"""Handle request for Prometheus metrics."""
_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
https://home-assistant.io/components/raincloud/
"""
import asyncio
from datetime import timedelta
import logging
@ -148,8 +147,7 @@ class RainCloudEntity(Entity):
"""Return the name of the sensor."""
return self._name
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Register callbacks."""
async_dispatcher_connect(
self.hass, SIGNAL_UPDATE_RAINCLOUD, self._update_callback)

View file

@ -53,8 +53,7 @@ CONFIG_SCHEMA = vol.Schema({
}, extra=vol.ALLOW_EXTRA)
@asyncio.coroutine
def async_setup(hass, config):
async def async_setup(hass, config):
"""Set up the REST command component."""
websession = async_get_clientsession(hass)
@ -87,8 +86,7 @@ def async_setup(hass, config):
headers = {}
headers[hdrs.CONTENT_TYPE] = content_type
@asyncio.coroutine
def async_service_handler(service):
async def async_service_handler(service):
"""Execute a shell command service."""
payload = None
if template_payload:
@ -98,7 +96,7 @@ def async_setup(hass, config):
try:
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),
data=payload,
auth=auth,

View file

@ -105,8 +105,7 @@ def identify_event_type(event):
return 'unknown'
@asyncio.coroutine
def async_setup(hass, config):
async def async_setup(hass, config):
"""Set up the Rflink component."""
from rflink.protocol import create_rflink_connection
import serial
@ -125,11 +124,10 @@ def async_setup(hass, config):
# Allow platform to specify function to register new unknown devices
hass.data[DATA_DEVICE_REGISTER] = {}
@asyncio.coroutine
def async_send_command(call):
async def async_send_command(call):
"""Send Rflink command."""
_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_COMMAND))):
_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')
hass.async_add_job(connect)
@asyncio.coroutine
def connect():
async def connect():
"""Set up connection and hook it into HA for reconnect/shutdown."""
_LOGGER.info('Initiating Rflink connection')
@ -217,7 +214,7 @@ def async_setup(hass, config):
try:
with async_timeout.timeout(CONNECTION_TIMEOUT,
loop=hass.loop):
transport, protocol = yield from connection
transport, protocol = await connection
except (serial.serialutil.SerialException, ConnectionRefusedError,
TimeoutError, OSError, asyncio.TimeoutError) as exc:
@ -330,8 +327,7 @@ class RflinkDevice(Entity):
self._available = availability
self.async_schedule_update_ha_state()
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Register update callback."""
async_dispatcher_connect(self.hass, SIGNAL_AVAILABILITY,
self.set_availability)
@ -367,13 +363,11 @@ class RflinkCommand(RflinkDevice):
return bool(cls._protocol)
@classmethod
@asyncio.coroutine
def send_command(cls, device_id, action):
async def send_command(cls, device_id, action):
"""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
def _async_handle_command(self, command, *args):
async def _async_handle_command(self, command, *args):
"""Do bookkeeping for command, send it to rflink and update state."""
self.cancel_queued_send_commands()
@ -412,10 +406,10 @@ class RflinkCommand(RflinkDevice):
# Send initial command and queue repetitions.
# This allows the entity state to be updated quickly and not having to
# 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
yield from self.async_update_ha_state()
await self.async_update_ha_state()
def cancel_queued_send_commands(self):
"""Cancel queued signal repetition commands.
@ -428,8 +422,7 @@ class RflinkCommand(RflinkDevice):
if self._repetition_task:
self._repetition_task.cancel()
@asyncio.coroutine
def _async_send_command(self, cmd, repetitions):
async def _async_send_command(self, cmd, repetitions):
"""Send a command for device to Rflink gateway."""
_LOGGER.debug(
"Sending command: %s to Rflink device: %s", cmd, self._device_id)
@ -440,7 +433,7 @@ class RflinkCommand(RflinkDevice):
if self._wait_ack:
# Puts command on outgoing buffer then waits for Rflink to confirm
# 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:
# Puts command on outgoing buffer and returns straight away.
# 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
https://home-assistant.io/components/rfxtrx/
"""
import asyncio
from collections import OrderedDict
import logging
@ -316,8 +315,7 @@ class RfxtrxDevice(Entity):
self._brightness = 0
self.added_to_hass = False
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Subscribe RFXtrx events."""
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/
"""
import asyncio
from html import escape
from aiohttp import web
@ -76,8 +75,7 @@ class RssView(HomeAssistantView):
self._title = title
self._items = items
@asyncio.coroutine
def get(self, request, entity_id=None):
async def get(self, request, entity_id=None):
"""Generate the RSS view XML."""
response = '<?xml version="1.0" encoding="utf-8"?>\n\n'

View file

@ -67,8 +67,7 @@ CONFIG_SCHEMA = vol.Schema({
}, extra=vol.ALLOW_EXTRA)
@asyncio.coroutine
def async_setup(hass, config):
async def async_setup(hass, config):
"""Set up the Satel Integra component."""
conf = config.get(DOMAIN)
@ -83,13 +82,12 @@ def async_setup(hass, config):
hass.data[DATA_SATEL] = controller
result = yield from controller.connect()
result = await controller.connect()
if not result:
return False
@asyncio.coroutine
def _close():
async def _close():
controller.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,
{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
def alarm_status_update_callback(status):

View file

@ -27,15 +27,13 @@ CONFIG_SCHEMA = vol.Schema({
}, extra=vol.ALLOW_EXTRA)
@asyncio.coroutine
def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool:
async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool:
"""Set up the shell_command component."""
conf = config.get(DOMAIN, {})
cache = {}
@asyncio.coroutine
def async_service_handler(service: ServiceCall) -> None:
async def async_service_handler(service: ServiceCall) -> None:
"""Execute a shell command service."""
cmd = conf[service.service]
@ -85,8 +83,8 @@ def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool:
stderr=asyncio.subprocess.PIPE,
)
process = yield from create_process
stdout_data, stderr_data = yield from process.communicate()
process = await create_process
stdout_data, stderr_data = await process.communicate()
if stdout_data:
_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
https://home-assistant.io/components/sun/
"""
import asyncio
import logging
from datetime import timedelta
@ -36,8 +35,7 @@ STATE_ATTR_NEXT_RISING = 'next_rising'
STATE_ATTR_NEXT_SETTING = 'next_setting'
@asyncio.coroutine
def async_setup(hass, config):
async def async_setup(hass, config):
"""Track the state of the sun."""
if config.get(CONF_ELEVATION) is not None:
_LOGGER.warning(

View file

@ -4,7 +4,6 @@ Support for system log.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/system_log/
"""
import asyncio
from collections import deque
from io import StringIO
import logging
@ -134,8 +133,7 @@ class LogErrorHandler(logging.Handler):
self.hass.bus.fire(EVENT_SYSTEM_LOG, entry)
@asyncio.coroutine
def async_setup(hass, config):
async def async_setup(hass, config):
"""Set up the logger component."""
conf = config.get(DOMAIN)
if conf is None:
@ -147,8 +145,7 @@ def async_setup(hass, config):
hass.http.register_view(AllErrorsView(handler))
@asyncio.coroutine
def async_service_handler(service):
async def async_service_handler(service):
"""Handle logger services."""
if service.service == 'clear':
handler.records.clear()
@ -159,8 +156,7 @@ def async_setup(hass, config):
level = service.data[CONF_LEVEL]
getattr(logger, level)(service.data[CONF_MESSAGE])
@asyncio.coroutine
def async_shutdown_handler(event):
async def async_shutdown_handler(event):
"""Remove logging handler when Home Assistant is shutdown."""
# This is needed as older logger instances will remain
logging.getLogger().removeHandler(handler)
@ -188,8 +184,7 @@ class AllErrorsView(HomeAssistantView):
"""Initialize a new AllErrorsView."""
self.handler = handler
@asyncio.coroutine
def get(self, request):
async def get(self, request):
"""Get all errors and warnings."""
# deque is not serializable (it's just "list-like") so it must be
# 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
https://home-assistant.io/components/tellstick/
"""
import asyncio
import logging
import threading
@ -158,8 +157,7 @@ class TellstickDevice(Entity):
self._tellcore_device = tellcore_device
self._name = tellcore_device.name
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Register callbacks."""
self.hass.helpers.dispatcher.async_dispatcher_connect(
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
https://home-assistant.io/components/thethingsnetwork/
"""
import asyncio
import logging
import voluptuous as vol
@ -32,8 +31,7 @@ CONFIG_SCHEMA = vol.Schema({
}, extra=vol.ALLOW_EXTRA)
@asyncio.coroutine
def async_setup(hass, config):
async def async_setup(hass, config):
"""Initialize of The Things Network component."""
conf = config[DOMAIN]
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
https://home-assistant.io/components/upcloud/
"""
import asyncio
import logging
from datetime import timedelta
@ -129,8 +128,7 @@ class UpCloudServerEntity(Entity):
except (AttributeError, KeyError, TypeError):
return DEFAULT_COMPONENT_NAME.format(self.uuid)
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Register callbacks."""
async_dispatcher_connect(
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
https://home-assistant.io/components/wake_on_lan/
"""
import asyncio
from functools import partial
import logging
@ -29,24 +28,22 @@ WAKE_ON_LAN_SEND_MAGIC_PACKET_SCHEMA = vol.Schema({
})
@asyncio.coroutine
def async_setup(hass, config):
async def async_setup(hass, config):
"""Set up the wake on LAN component."""
import wakeonlan
@asyncio.coroutine
def send_magic_packet(call):
async def send_magic_packet(call):
"""Send magic packet to wake up a device."""
mac_address = call.data.get(CONF_MAC)
broadcast_address = call.data.get(CONF_BROADCAST_ADDRESS)
_LOGGER.info("Send magic packet to mac %s (broadcast: %s)",
mac_address, broadcast_address)
if broadcast_address is not None:
yield from hass.async_add_job(
await hass.async_add_job(
partial(wakeonlan.send_magic_packet, mac_address,
ip_address=broadcast_address))
else:
yield from hass.async_add_job(
await hass.async_add_job(
partial(wakeonlan.send_magic_packet, mac_address))
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
https://home-assistant.io/components/weather/
"""
import asyncio
import logging
from homeassistant.helpers.entity_component import EntityComponent
@ -39,12 +38,11 @@ ATTR_WEATHER_WIND_BEARING = 'wind_bearing'
ATTR_WEATHER_WIND_SPEED = 'wind_speed'
@asyncio.coroutine
def async_setup(hass, config):
async def async_setup(hass, config):
"""Set up the weather component."""
component = EntityComponent(_LOGGER, DOMAIN, hass)
yield from component.async_setup(config)
await component.async_setup(config)
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/
"""
import logging
import asyncio
import voluptuous as vol
@ -55,9 +54,8 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
})
@asyncio.coroutine
def async_setup_platform(hass, config, async_add_entities,
discovery_info=None):
async def async_setup_platform(hass, config, async_add_entities,
discovery_info=None):
"""Set up the buienradar platform."""
latitude = config.get(CONF_LATITUDE, hass.config.latitude)
longitude = config.get(CONF_LONGITUDE, hass.config.longitude)
@ -86,7 +84,7 @@ def async_setup_platform(hass, config, async_add_entities,
async_add_entities([BrWeather(data, config)])
# schedule the first update in 1 minute from now:
yield from data.schedule_update(1)
await data.schedule_update(1)
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
https://home-assistant.io/components/wink/
"""
import asyncio
from datetime import timedelta
import json
import logging
@ -763,8 +762,7 @@ class WinkDevice(Entity):
class WinkSirenDevice(WinkDevice):
"""Representation of a Wink siren device."""
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Call when entity is added to hass."""
self.hass.data[DOMAIN]['entities']['switch'].append(self)
@ -824,8 +822,7 @@ class WinkNimbusDialDevice(WinkDevice):
super().__init__(dial, hass)
self.parent = nimbus
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Call when entity is added to hass."""
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
https://home-assistant.io/components/xiaomi_aqara/
"""
import asyncio
import logging
from datetime import timedelta
@ -113,8 +112,7 @@ def setup(hass, config):
interface = config[DOMAIN][CONF_INTERFACE]
discovery_retry = config[DOMAIN][CONF_DISCOVERY_RETRY]
@asyncio.coroutine
def xiaomi_gw_discovered(service, discovery_info):
async def xiaomi_gw_discovered(service, discovery_info):
"""Perform action when Xiaomi Gateway device(s) has been found."""
# We don't need to do anything here, the purpose of Home Assistant's
# discovery service is to just trigger loading of this
@ -233,8 +231,7 @@ class XiaomiDevice(Entity):
def _add_push_data_job(self, *args):
self.hass.add_job(self.push_data, *args)
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Start unavailability tracking."""
self._xiaomi_hub.callbacks[self._sid].append(self._add_push_data_job)
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
https://home-assistant.io/components/zigbee/
"""
import asyncio
import logging
from binascii import hexlify, unhexlify
@ -277,8 +276,7 @@ class ZigBeeDigitalIn(Entity):
self._config = config
self._state = False
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Register callbacks."""
def handle_frame(frame):
"""Handle an incoming frame.
@ -403,8 +401,7 @@ class ZigBeeAnalogIn(Entity):
self._config = config
self._value = None
@asyncio.coroutine
def async_added_to_hass(self):
async def async_added_to_hass(self):
"""Register callbacks."""
def handle_frame(frame):
"""Handle an incoming frame.