Don't pass in loop (#23984)

* Don't pass in loop

* Revert some changes

* Lint + Axis revert

* reinstate loop

* Fix a test

* Set loop

* Update camera.py

* Lint
This commit is contained in:
Paulus Schoutsen 2019-05-22 21:09:59 -07:00 committed by GitHub
parent 9e96397e6a
commit f995ab9d54
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
117 changed files with 179 additions and 187 deletions

View file

@ -118,7 +118,7 @@ async def async_setup(hass, config):
tasks = [alert.async_update_ha_state() for alert in entities] tasks = [alert.async_update_ha_state() for alert in entities]
if tasks: if tasks:
await asyncio.wait(tasks, loop=hass.loop) await asyncio.wait(tasks)
return True return True

View file

@ -39,7 +39,7 @@ class Auth:
self._prefs = None self._prefs = None
self._store = hass.helpers.storage.Store(STORAGE_VERSION, STORAGE_KEY) self._store = hass.helpers.storage.Store(STORAGE_VERSION, STORAGE_KEY)
self._get_token_lock = asyncio.Lock(loop=hass.loop) self._get_token_lock = asyncio.Lock()
async def async_do_auth(self, accept_grant_code): async def async_do_auth(self, accept_grant_code):
"""Do authentication with an AcceptGrant code.""" """Do authentication with an AcceptGrant code."""
@ -97,7 +97,7 @@ class Auth:
try: try:
session = aiohttp_client.async_get_clientsession(self.hass) session = aiohttp_client.async_get_clientsession(self.hass)
with async_timeout.timeout(DEFAULT_TIMEOUT, loop=self.hass.loop): with async_timeout.timeout(DEFAULT_TIMEOUT):
response = await session.post(LWA_TOKEN_URI, response = await session.post(LWA_TOKEN_URI,
headers=LWA_HEADERS, headers=LWA_HEADERS,
data=lwa_params, data=lwa_params,

View file

@ -1432,7 +1432,7 @@ async def async_send_changereport_message(hass, config, alexa_entity):
try: try:
session = aiohttp_client.async_get_clientsession(hass) session = aiohttp_client.async_get_clientsession(hass)
with async_timeout.timeout(DEFAULT_TIMEOUT, loop=hass.loop): with async_timeout.timeout(DEFAULT_TIMEOUT):
response = await session.post(config.endpoint, response = await session.post(config.endpoint,
headers=headers, headers=headers,
json=message_serialized, json=message_serialized,

View file

@ -233,7 +233,7 @@ async 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:
await asyncio.wait(tasks, loop=hass.loop) await asyncio.wait(tasks)
return True return True

View file

@ -47,7 +47,7 @@ async def async_setup_platform(hass, config, async_add_entities,
hass.async_create_task(device.async_update_ha_state()) hass.async_create_task(device.async_update_ha_state())
avr = await anthemav.Connection.create( avr = await anthemav.Connection.create(
host=host, port=port, loop=hass.loop, host=host, port=port,
update_callback=async_anthemav_update_callback) update_callback=async_anthemav_update_callback)
device = AnthemAVR(avr, name) device = AnthemAVR(avr, name)

View file

@ -82,7 +82,7 @@ class APIEventStream(HomeAssistantView):
raise Unauthorized() raise Unauthorized()
hass = request.app['hass'] hass = request.app['hass']
stop_obj = object() stop_obj = object()
to_write = asyncio.Queue(loop=hass.loop) to_write = asyncio.Queue()
restrict = request.query.get('restrict') restrict = request.query.get('restrict')
if restrict: if restrict:
@ -119,8 +119,7 @@ class APIEventStream(HomeAssistantView):
while True: while True:
try: try:
with async_timeout.timeout(STREAM_PING_INTERVAL, with async_timeout.timeout(STREAM_PING_INTERVAL):
loop=hass.loop):
payload = await to_write.get() payload = await to_write.get()
if payload is stop_obj: if payload is stop_obj:

View file

@ -167,7 +167,7 @@ async def async_setup(hass, config):
tasks = [_setup_atv(hass, config, conf) for conf in config.get(DOMAIN, [])] tasks = [_setup_atv(hass, config, conf) for conf in config.get(DOMAIN, [])]
if tasks: if tasks:
await asyncio.wait(tasks, loop=hass.loop) await asyncio.wait(tasks)
hass.services.async_register( hass.services.async_register(
DOMAIN, SERVICE_SCAN, async_service_handler, DOMAIN, SERVICE_SCAN, async_service_handler,

View file

@ -124,7 +124,7 @@ async def async_setup(hass, config):
context=service_call.context)) context=service_call.context))
if tasks: if tasks:
await asyncio.wait(tasks, loop=hass.loop) await asyncio.wait(tasks)
async def turn_onoff_service_handler(service_call): async def turn_onoff_service_handler(service_call):
"""Handle automation turn on/off service calls.""" """Handle automation turn on/off service calls."""
@ -134,7 +134,7 @@ async def async_setup(hass, config):
tasks.append(getattr(entity, method)()) tasks.append(getattr(entity, method)())
if tasks: if tasks:
await asyncio.wait(tasks, loop=hass.loop) await asyncio.wait(tasks)
async def toggle_service_handler(service_call): async def toggle_service_handler(service_call):
"""Handle automation toggle service calls.""" """Handle automation toggle service calls."""
@ -146,7 +146,7 @@ async def async_setup(hass, config):
tasks.append(entity.async_turn_on()) tasks.append(entity.async_turn_on())
if tasks: if tasks:
await asyncio.wait(tasks, loop=hass.loop) await asyncio.wait(tasks)
async def reload_service_handler(service_call): async def reload_service_handler(service_call):
"""Remove all automations and load new ones from config.""" """Remove all automations and load new ones from config."""

View file

@ -166,14 +166,14 @@ async def _validate_aws_credentials(hass, credential):
profile = aws_config.get(CONF_PROFILE_NAME) profile = aws_config.get(CONF_PROFILE_NAME)
if profile is not None: if profile is not None:
session = aiobotocore.AioSession(profile=profile, loop=hass.loop) session = aiobotocore.AioSession(profile=profile)
del aws_config[CONF_PROFILE_NAME] del aws_config[CONF_PROFILE_NAME]
if CONF_ACCESS_KEY_ID in aws_config: if CONF_ACCESS_KEY_ID in aws_config:
del aws_config[CONF_ACCESS_KEY_ID] del aws_config[CONF_ACCESS_KEY_ID]
if CONF_SECRET_ACCESS_KEY in aws_config: if CONF_SECRET_ACCESS_KEY in aws_config:
del aws_config[CONF_SECRET_ACCESS_KEY] del aws_config[CONF_SECRET_ACCESS_KEY]
else: else:
session = aiobotocore.AioSession(loop=hass.loop) session = aiobotocore.AioSession()
if credential[CONF_VALIDATE]: if credential[CONF_VALIDATE]:
async with session.create_client("iam", **aws_config) as client: async with session.create_client("iam", **aws_config) as client:

View file

@ -94,10 +94,10 @@ async def async_get_service(hass, config, discovery_info=None):
if session is None: if session is None:
profile = aws_config.get(CONF_PROFILE_NAME) profile = aws_config.get(CONF_PROFILE_NAME)
if profile is not None: if profile is not None:
session = aiobotocore.AioSession(profile=profile, loop=hass.loop) session = aiobotocore.AioSession(profile=profile)
del aws_config[CONF_PROFILE_NAME] del aws_config[CONF_PROFILE_NAME]
else: else:
session = aiobotocore.AioSession(loop=hass.loop) session = aiobotocore.AioSession()
aws_config[CONF_REGION] = region_name aws_config[CONF_REGION] = region_name

View file

@ -255,7 +255,7 @@ class BluesoundPlayer(MediaPlayerDevice):
BluesoundPlayer._TimeoutException): BluesoundPlayer._TimeoutException):
_LOGGER.info("Node %s is offline, retrying later", self._name) _LOGGER.info("Node %s is offline, retrying later", self._name)
await asyncio.sleep( await asyncio.sleep(
NODE_OFFLINE_CHECK_TIMEOUT, loop=self._hass.loop) NODE_OFFLINE_CHECK_TIMEOUT)
self.start_polling() self.start_polling()
except CancelledError: except CancelledError:
@ -318,7 +318,7 @@ class BluesoundPlayer(MediaPlayerDevice):
try: try:
websession = async_get_clientsession(self._hass) websession = async_get_clientsession(self._hass)
with async_timeout.timeout(10, loop=self._hass.loop): with async_timeout.timeout(10):
response = await websession.get(url) response = await websession.get(url)
if response.status == 200: if response.status == 200:
@ -361,7 +361,7 @@ class BluesoundPlayer(MediaPlayerDevice):
try: try:
with async_timeout.timeout(125, loop=self._hass.loop): with async_timeout.timeout(125):
response = await self._polling_session.get( response = await self._polling_session.get(
url, headers={CONNECTION: KEEP_ALIVE}) url, headers={CONNECTION: KEEP_ALIVE})
@ -378,7 +378,7 @@ class BluesoundPlayer(MediaPlayerDevice):
self._group_name = group_name self._group_name = group_name
# the sleep is needed to make sure that the # the sleep is needed to make sure that the
# devices is synced # devices is synced
await asyncio.sleep(1, loop=self._hass.loop) await asyncio.sleep(1)
await self.async_trigger_sync_on_all() await self.async_trigger_sync_on_all()
elif self.is_grouped: elif self.is_grouped:
# when player is grouped we need to fetch volume from # when player is grouped we need to fetch volume from

View file

@ -388,7 +388,7 @@ class BrData:
tasks.append(dev.async_update_ha_state()) tasks.append(dev.async_update_ha_state())
if tasks: if tasks:
await asyncio.wait(tasks, loop=self.hass.loop) await asyncio.wait(tasks)
async def schedule_update(self, minute=1): async def schedule_update(self, minute=1):
"""Schedule an update after minute minutes.""" """Schedule an update after minute minutes."""
@ -407,7 +407,7 @@ class BrData:
resp = None resp = None
try: try:
websession = async_get_clientsession(self.hass) websession = async_get_clientsession(self.hass)
with async_timeout.timeout(10, loop=self.hass.loop): with async_timeout.timeout(10):
resp = await websession.get(url) resp = await websession.get(url)
result[STATUS_CODE] = resp.status result[STATUS_CODE] = resp.status

View file

@ -121,7 +121,7 @@ async def async_get_image(hass, entity_id, timeout=10):
camera = _get_camera_from_entity_id(hass, entity_id) camera = _get_camera_from_entity_id(hass, entity_id)
with suppress(asyncio.CancelledError, asyncio.TimeoutError): with suppress(asyncio.CancelledError, asyncio.TimeoutError):
with async_timeout.timeout(timeout, loop=hass.loop): with async_timeout.timeout(timeout):
image = await camera.async_camera_image() image = await camera.async_camera_image()
if image: if image:
@ -481,7 +481,7 @@ class CameraImageView(CameraView):
async def handle(self, request, camera): async def handle(self, request, camera):
"""Serve camera image.""" """Serve camera image."""
with suppress(asyncio.CancelledError, asyncio.TimeoutError): with suppress(asyncio.CancelledError, asyncio.TimeoutError):
with async_timeout.timeout(10, loop=request.app['hass'].loop): with async_timeout.timeout(10):
image = await camera.async_camera_image() image = await camera.async_camera_image()
if image: if image:

View file

@ -79,7 +79,7 @@ class CanaryCamera(Camera):
image = await asyncio.shield(ffmpeg.get_image( image = await asyncio.shield(ffmpeg.get_image(
self._live_stream_session.live_stream_url, self._live_stream_session.live_stream_url,
output_format=IMAGE_JPEG, output_format=IMAGE_JPEG,
extra_cmd=self._ffmpeg_arguments), loop=self.hass.loop) extra_cmd=self._ffmpeg_arguments))
return image return image
async def handle_async_mjpeg_stream(self, request): async def handle_async_mjpeg_stream(self, request):

View file

@ -106,7 +106,7 @@ async def async_citybikes_request(hass, uri, schema):
try: try:
session = async_get_clientsession(hass) session = async_get_clientsession(hass)
with async_timeout.timeout(REQUEST_TIMEOUT, loop=hass.loop): with async_timeout.timeout(REQUEST_TIMEOUT):
req = await session.get(DEFAULT_ENDPOINT.format(uri=uri)) req = await session.get(DEFAULT_ENDPOINT.format(uri=uri))
json_response = await req.json() json_response = await req.json()
@ -181,7 +181,7 @@ class CityBikesNetworks:
"""Initialize the networks instance.""" """Initialize the networks instance."""
self.hass = hass self.hass = hass
self.networks = None self.networks = None
self.networks_loading = asyncio.Condition(loop=hass.loop) self.networks_loading = asyncio.Condition()
async def get_closest_network_id(self, latitude, longitude): async def get_closest_network_id(self, latitude, longitude):
"""Return the id of the network closest to provided location.""" """Return the id of the network closest to provided location."""
@ -217,7 +217,7 @@ class CityBikesNetwork:
self.hass = hass self.hass = hass
self.network_id = network_id self.network_id = network_id
self.stations = [] self.stations = []
self.ready = asyncio.Event(loop=hass.loop) self.ready = asyncio.Event()
async def async_refresh(self, now=None): async def async_refresh(self, now=None):
"""Refresh the state of the network.""" """Refresh the state of the network."""

View file

@ -164,10 +164,10 @@ class GoogleActionsSyncView(HomeAssistantView):
cloud = hass.data[DOMAIN] cloud = hass.data[DOMAIN]
websession = hass.helpers.aiohttp_client.async_get_clientsession() websession = hass.helpers.aiohttp_client.async_get_clientsession()
with async_timeout.timeout(REQUEST_TIMEOUT, loop=hass.loop): with async_timeout.timeout(REQUEST_TIMEOUT):
await hass.async_add_job(cloud.auth.check_token) await hass.async_add_job(cloud.auth.check_token)
with async_timeout.timeout(REQUEST_TIMEOUT, loop=hass.loop): with async_timeout.timeout(REQUEST_TIMEOUT):
req = await websession.post( req = await websession.post(
cloud.google_actions_sync_url, headers={ cloud.google_actions_sync_url, headers={
'authorization': cloud.id_token 'authorization': cloud.id_token
@ -192,7 +192,7 @@ class CloudLoginView(HomeAssistantView):
hass = request.app['hass'] hass = request.app['hass']
cloud = hass.data[DOMAIN] cloud = hass.data[DOMAIN]
with async_timeout.timeout(REQUEST_TIMEOUT, loop=hass.loop): with async_timeout.timeout(REQUEST_TIMEOUT):
await hass.async_add_job(cloud.auth.login, data['email'], await hass.async_add_job(cloud.auth.login, data['email'],
data['password']) data['password'])
@ -212,7 +212,7 @@ class CloudLogoutView(HomeAssistantView):
hass = request.app['hass'] hass = request.app['hass']
cloud = hass.data[DOMAIN] cloud = hass.data[DOMAIN]
with async_timeout.timeout(REQUEST_TIMEOUT, loop=hass.loop): with async_timeout.timeout(REQUEST_TIMEOUT):
await cloud.logout() await cloud.logout()
return self.json_message('ok') return self.json_message('ok')
@ -234,7 +234,7 @@ class CloudRegisterView(HomeAssistantView):
hass = request.app['hass'] hass = request.app['hass']
cloud = hass.data[DOMAIN] cloud = hass.data[DOMAIN]
with async_timeout.timeout(REQUEST_TIMEOUT, loop=hass.loop): with async_timeout.timeout(REQUEST_TIMEOUT):
await hass.async_add_job( await hass.async_add_job(
cloud.auth.register, data['email'], data['password']) cloud.auth.register, data['email'], data['password'])
@ -256,7 +256,7 @@ class CloudResendConfirmView(HomeAssistantView):
hass = request.app['hass'] hass = request.app['hass']
cloud = hass.data[DOMAIN] cloud = hass.data[DOMAIN]
with async_timeout.timeout(REQUEST_TIMEOUT, loop=hass.loop): with async_timeout.timeout(REQUEST_TIMEOUT):
await hass.async_add_job( await hass.async_add_job(
cloud.auth.resend_email_confirm, data['email']) cloud.auth.resend_email_confirm, data['email'])
@ -278,7 +278,7 @@ class CloudForgotPasswordView(HomeAssistantView):
hass = request.app['hass'] hass = request.app['hass']
cloud = hass.data[DOMAIN] cloud = hass.data[DOMAIN]
with async_timeout.timeout(REQUEST_TIMEOUT, loop=hass.loop): with async_timeout.timeout(REQUEST_TIMEOUT):
await hass.async_add_job( await hass.async_add_job(
cloud.auth.forgot_password, data['email']) cloud.auth.forgot_password, data['email'])
@ -320,7 +320,7 @@ async def websocket_subscription(hass, connection, msg):
from hass_nabucasa.const import STATE_DISCONNECTED from hass_nabucasa.const import STATE_DISCONNECTED
cloud = hass.data[DOMAIN] cloud = hass.data[DOMAIN]
with async_timeout.timeout(REQUEST_TIMEOUT, loop=hass.loop): with async_timeout.timeout(REQUEST_TIMEOUT):
response = await cloud.fetch_subscription_info() response = await cloud.fetch_subscription_info()
if response.status != 200: if response.status != 200:

View file

@ -106,7 +106,7 @@ class ComedHourlyPricingSensor(Entity):
else: else:
url_string += '?type=currenthouraverage' url_string += '?type=currenthouraverage'
with async_timeout.timeout(60, loop=self.loop): with async_timeout.timeout(60):
response = await self.websession.get(url_string) response = await self.websession.get(url_string)
# The API responds with MIME type 'text/html' # The API responds with MIME type 'text/html'
text = await response.text() text = await response.text()

View file

@ -62,7 +62,7 @@ async def async_setup(hass, config):
tasks.append(setup_panel(panel_name)) tasks.append(setup_panel(panel_name))
if tasks: if tasks:
await asyncio.wait(tasks, loop=hass.loop) await asyncio.wait(tasks)
return True return True

View file

@ -144,7 +144,7 @@ async def async_setup(hass: HomeAssistantType, config: ConfigType):
})) }))
if setup_tasks: if setup_tasks:
await asyncio.wait(setup_tasks, loop=hass.loop) await asyncio.wait(setup_tasks)
tracker.async_setup_group() tracker.async_setup_group()

View file

@ -82,7 +82,7 @@ class DeviceTracker:
else defaults.get(CONF_TRACK_NEW, DEFAULT_TRACK_NEW) else defaults.get(CONF_TRACK_NEW, DEFAULT_TRACK_NEW)
self.defaults = defaults self.defaults = defaults
self.group = None self.group = None
self._is_updating = asyncio.Lock(loop=hass.loop) self._is_updating = asyncio.Lock()
for dev in devices: for dev in devices:
if self.devices[dev.dev_id] is not dev: if self.devices[dev.dev_id] is not dev:
@ -229,7 +229,7 @@ class DeviceTracker:
async_init_single_device(device))) async_init_single_device(device)))
if tasks: if tasks:
await asyncio.wait(tasks, loop=self.hass.loop) await asyncio.wait(tasks)
class Device(RestoreEntity): class Device(RestoreEntity):

View file

@ -147,7 +147,7 @@ def async_setup_scanner_platform(hass: HomeAssistantType, config: ConfigType,
This method must be run in the event loop. This method must be run in the event loop.
""" """
interval = config.get(CONF_SCAN_INTERVAL, SCAN_INTERVAL) interval = config.get(CONF_SCAN_INTERVAL, SCAN_INTERVAL)
update_lock = asyncio.Lock(loop=hass.loop) update_lock = asyncio.Lock()
scanner.hass = hass scanner.hass = hass
# Initial scan of each mac we also tell about host name for config # Initial scan of each mac we also tell about host name for config

View file

@ -46,7 +46,7 @@ class DiscordNotificationService(BaseNotificationService):
import discord import discord
discord.VoiceClient.warn_nacl = False discord.VoiceClient.warn_nacl = False
discord_bot = discord.Client(loop=self.hass.loop) discord_bot = discord.Client()
images = None images = None
if ATTR_TARGET not in kwargs: if ATTR_TARGET not in kwargs:

View file

@ -103,7 +103,6 @@ async def async_start_event_handler(
requester, requester,
listen_port=server_port, listen_port=server_port,
listen_host=server_host, listen_host=server_host,
loop=hass.loop,
callback_url=callback_url_override) callback_url=callback_url_override)
await server.start_server() await server.start_server()
_LOGGER.info( _LOGGER.info(

View file

@ -63,7 +63,7 @@ class WanIpSensor(Entity):
self.hass = hass self.hass = hass
self._name = name self._name = name
self.hostname = hostname self.hostname = hostname
self.resolver = aiodns.DNSResolver(loop=self.hass.loop) self.resolver = aiodns.DNSResolver()
self.resolver.nameservers = [resolver] self.resolver.nameservers = [resolver]
self.querytype = 'AAAA' if ipv6 else 'A' self.querytype = 'AAAA' if ipv6 else 'A'
self._state = None self._state = None

View file

@ -81,7 +81,7 @@ class DoorBirdCamera(Camera):
try: try:
websession = async_get_clientsession(self.hass) websession = async_get_clientsession(self.hass)
with async_timeout.timeout(_TIMEOUT, loop=self.hass.loop): with async_timeout.timeout(_TIMEOUT):
response = await websession.get(self._url) response = await websession.get(self._url)
self._last_image = await response.read() self._last_image = await response.read()

View file

@ -183,12 +183,11 @@ async def async_setup_platform(hass, config, async_add_entities,
if CONF_HOST in config: if CONF_HOST in config:
reader_factory = partial( reader_factory = partial(
create_tcp_dsmr_reader, config[CONF_HOST], config[CONF_PORT], create_tcp_dsmr_reader, config[CONF_HOST], config[CONF_PORT],
config[CONF_DSMR_VERSION], update_entities_telegram, config[CONF_DSMR_VERSION], update_entities_telegram)
loop=hass.loop)
else: else:
reader_factory = partial( reader_factory = partial(
create_dsmr_reader, config[CONF_PORT], config[CONF_DSMR_VERSION], create_dsmr_reader, config[CONF_PORT], config[CONF_DSMR_VERSION],
update_entities_telegram, loop=hass.loop) update_entities_telegram)
async def connect_and_reconnect(): async def connect_and_reconnect():
"""Connect to DSMR and keep reconnecting until Home Assistant stops.""" """Connect to DSMR and keep reconnecting until Home Assistant stops."""
@ -223,8 +222,7 @@ async def async_setup_platform(hass, config, async_add_entities,
update_entities_telegram({}) update_entities_telegram({})
# throttle reconnect attempts # throttle reconnect attempts
await asyncio.sleep(config[CONF_RECONNECT_INTERVAL], await asyncio.sleep(config[CONF_RECONNECT_INTERVAL])
loop=hass.loop)
# Can't be hass.async_add_job because job runs forever # Can't be hass.async_add_job because job runs forever
hass.loop.create_task(connect_and_reconnect()) hass.loop.create_task(connect_and_reconnect())

View file

@ -106,7 +106,7 @@ async def async_setup(hass, config):
zones = conf.get(CONF_ZONES) zones = conf.get(CONF_ZONES)
partitions = conf.get(CONF_PARTITIONS) partitions = conf.get(CONF_PARTITIONS)
connection_timeout = conf.get(CONF_TIMEOUT) connection_timeout = conf.get(CONF_TIMEOUT)
sync_connect = asyncio.Future(loop=hass.loop) sync_connect = asyncio.Future()
controller = EnvisalinkAlarmPanel( controller = EnvisalinkAlarmPanel(
host, port, panel_type, version, user, password, zone_dump, host, port, panel_type, version, user, password, zone_dump,

View file

@ -59,7 +59,7 @@ class FFmpegCamera(Camera):
image = await asyncio.shield(ffmpeg.get_image( image = await asyncio.shield(ffmpeg.get_image(
self._input, output_format=IMAGE_JPEG, self._input, output_format=IMAGE_JPEG,
extra_cmd=self._extra_arguments), loop=self.hass.loop) extra_cmd=self._extra_arguments))
return image return image
async def handle_async_mjpeg_stream(self, request): async def handle_async_mjpeg_stream(self, request):

View file

@ -26,15 +26,14 @@ async def get_service(hass, config, discovery_info=None):
url = '{}{}'.format(_RESOURCE, access_token) url = '{}{}'.format(_RESOURCE, access_token)
session = async_get_clientsession(hass) session = async_get_clientsession(hass)
return FlockNotificationService(url, session, hass.loop) return FlockNotificationService(url, session)
class FlockNotificationService(BaseNotificationService): class FlockNotificationService(BaseNotificationService):
"""Implement the notification service for Flock.""" """Implement the notification service for Flock."""
def __init__(self, url, session, loop): def __init__(self, url, session):
"""Initialize the Flock notification service.""" """Initialize the Flock notification service."""
self._loop = loop
self._url = url self._url = url
self._session = session self._session = session
@ -45,7 +44,7 @@ class FlockNotificationService(BaseNotificationService):
_LOGGER.debug("Attempting to call Flock at %s", self._url) _LOGGER.debug("Attempting to call Flock at %s", self._url)
try: try:
with async_timeout.timeout(10, loop=self._loop): with async_timeout.timeout(10):
response = await self._session.post(self._url, json=payload) response = await self._session.post(self._url, json=payload)
result = await response.json() result = await response.json()

View file

@ -68,7 +68,7 @@ async def _update_freedns(hass, session, url, auth_token):
params[auth_token] = "" params[auth_token] = ""
try: try:
with async_timeout.timeout(TIMEOUT, loop=hass.loop): with async_timeout.timeout(TIMEOUT):
resp = await session.get(url, params=params) resp = await session.get(url, params=params)
body = await resp.text() body = await resp.text()

View file

@ -243,11 +243,11 @@ async def async_setup(hass, config):
await asyncio.wait( await asyncio.wait(
[async_register_built_in_panel(hass, panel) for panel in ( [async_register_built_in_panel(hass, panel) for panel in (
'kiosk', 'states', 'profile')], loop=hass.loop) 'kiosk', 'states', 'profile')])
await asyncio.wait( await asyncio.wait(
[async_register_built_in_panel(hass, panel, require_admin=True) [async_register_built_in_panel(hass, panel, require_admin=True)
for panel in ('dev-event', 'dev-info', 'dev-service', 'dev-state', for panel in ('dev-event', 'dev-info', 'dev-service', 'dev-state',
'dev-template', 'dev-mqtt')], loop=hass.loop) 'dev-template', 'dev-mqtt')])
hass.data[DATA_FINALIZE_PANEL] = async_finalize_panel hass.data[DATA_FINALIZE_PANEL] = async_finalize_panel

View file

@ -127,7 +127,7 @@ class GenericCamera(Camera):
try: try:
websession = async_get_clientsession( websession = async_get_clientsession(
self.hass, verify_ssl=self.verify_ssl) self.hass, verify_ssl=self.verify_ssl)
with async_timeout.timeout(10, loop=self.hass.loop): with async_timeout.timeout(10):
response = await websession.get( response = await websession.get(
url, auth=self._auth) url, auth=self._auth)
self._last_image = await response.read() self._last_image = await response.read()

View file

@ -65,7 +65,7 @@ async def async_setup(hass: HomeAssistant, yaml_config: Dict[str, Any]):
"""Handle request sync service calls.""" """Handle request sync service calls."""
websession = async_get_clientsession(hass) websession = async_get_clientsession(hass)
try: try:
with async_timeout.timeout(15, loop=hass.loop): with async_timeout.timeout(15):
agent_user_id = call.data.get('agent_user_id') or \ agent_user_id = call.data.get('agent_user_id') or \
call.context.user_id call.context.user_id
res = await websession.post( res = await websession.post(

View file

@ -67,7 +67,7 @@ async def _update_google_domains(
} }
try: try:
with async_timeout.timeout(timeout, loop=hass.loop): with async_timeout.timeout(timeout):
resp = await session.get(url, params=params) resp = await session.get(url, params=params)
body = await resp.text() body = await resp.text()

View file

@ -87,7 +87,7 @@ class GoogleProvider(Provider):
} }
try: try:
with async_timeout.timeout(10, loop=self.hass.loop): with async_timeout.timeout(10):
request = await websession.get( request = await websession.get(
GOOGLE_SPEECH_URL, params=url_param, GOOGLE_SPEECH_URL, params=url_param,
headers=self.headers headers=self.headers

View file

@ -306,7 +306,7 @@ async def async_setup(hass, config):
tasks.append(group.async_update_ha_state()) tasks.append(group.async_update_ha_state())
if tasks: if tasks:
await asyncio.wait(tasks, loop=hass.loop) await asyncio.wait(tasks)
hass.services.async_register( hass.services.async_register(
DOMAIN, SERVICE_SET_VISIBILITY, visibility_service_handler, DOMAIN, SERVICE_SET_VISIBILITY, visibility_service_handler,

View file

@ -65,4 +65,4 @@ class GroupNotifyPlatform(BaseNotificationService):
DOMAIN, entity.get(ATTR_SERVICE), sending_payload)) DOMAIN, entity.get(ATTR_SERVICE), sending_payload))
if tasks: if tasks:
await asyncio.wait(tasks, loop=self.hass.loop) await asyncio.wait(tasks)

View file

@ -156,7 +156,7 @@ class HassIO:
This method is a coroutine. This method is a coroutine.
""" """
try: try:
with async_timeout.timeout(timeout, loop=self.loop): with async_timeout.timeout(timeout):
request = await self.websession.request( request = await self.websession.request(
method, "http://{}{}".format(self._ip, command), method, "http://{}{}".format(self._ip, command),
json=payload, headers={ json=payload, headers={

View file

@ -71,13 +71,11 @@ class HassIOView(HomeAssistantView):
This method is a coroutine. This method is a coroutine.
""" """
read_timeout = _get_timeout(path) read_timeout = _get_timeout(path)
hass = request.app['hass']
data = None data = None
headers = _init_header(request) headers = _init_header(request)
try: try:
with async_timeout.timeout(10, loop=hass.loop): with async_timeout.timeout(10):
data = await request.read() data = await request.read()
method = getattr(self._websession, request.method.lower()) method = getattr(self._websession, request.method.lower())

View file

@ -64,7 +64,7 @@ async 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))
await asyncio.wait(tasks, loop=hass.loop) await asyncio.wait(tasks)
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)

View file

@ -79,7 +79,7 @@ class HKDevice():
# There are multiple entities sharing a single connection - only # There are multiple entities sharing a single connection - only
# allow one entity to use pairing at once. # allow one entity to use pairing at once.
self.pairing_lock = asyncio.Lock(loop=hass.loop) self.pairing_lock = asyncio.Lock()
async def async_setup(self): async def async_setup(self):
"""Prepare to use a paired HomeKit device in homeassistant.""" """Prepare to use a paired HomeKit device in homeassistant."""

View file

@ -180,7 +180,7 @@ class HomematicipHAP:
try: try:
self._retry_task = self.hass.async_create_task(asyncio.sleep( self._retry_task = self.hass.async_create_task(asyncio.sleep(
retry_delay, loop=self.hass.loop)) retry_delay))
await self._retry_task await self._retry_task
except asyncio.CancelledError: except asyncio.CancelledError:
break break

View file

@ -36,7 +36,7 @@ async def async_setup_platform(hass, config, async_add_entities,
# If password is set in config, prefer it over token # If password is set in config, prefer it over token
if username is not None and password is not None: if username is not None and password is not None:
try: try:
with async_timeout.timeout(TIMEOUT, loop=hass.loop): with async_timeout.timeout(TIMEOUT):
response = await websession.post( response = await websession.post(
'{}{}'.format(HOOK_ENDPOINT, 'user/login'), '{}{}'.format(HOOK_ENDPOINT, 'user/login'),
data={ data={
@ -56,7 +56,7 @@ async def async_setup_platform(hass, config, async_add_entities,
return False return False
try: try:
with async_timeout.timeout(TIMEOUT, loop=hass.loop): with async_timeout.timeout(TIMEOUT):
response = await websession.get( response = await websession.get(
'{}{}'.format(HOOK_ENDPOINT, 'device'), '{}{}'.format(HOOK_ENDPOINT, 'device'),
params={"token": token}) params={"token": token})
@ -103,7 +103,7 @@ class HookSmartHome(SwitchDevice):
try: try:
_LOGGER.debug("Sending: %s", url) _LOGGER.debug("Sending: %s", url)
websession = async_get_clientsession(self.hass) websession = async_get_clientsession(self.hass)
with async_timeout.timeout(TIMEOUT, loop=self.hass.loop): with async_timeout.timeout(TIMEOUT):
response = await websession.get( response = await websession.get(
url, params={"token": self._token}) url, params={"token": self._token})
data = await response.json(content_type=None) data = await response.json(content_type=None)

View file

@ -77,7 +77,7 @@ async def async_setup(hass, config):
entity.async_update_ha_state(True)) entity.async_update_ha_state(True))
if update_tasks: if update_tasks:
await asyncio.wait(update_tasks, loop=hass.loop) await asyncio.wait(update_tasks)
hass.services.async_register( hass.services.async_register(
DOMAIN, SERVICE_SCAN, async_scan_service, DOMAIN, SERVICE_SCAN, async_scan_service,

View file

@ -82,7 +82,7 @@ async def async_get_station(hass, latitude, longitude):
from pyipma import Station from pyipma import Station
websession = async_get_clientsession(hass) websession = async_get_clientsession(hass)
with async_timeout.timeout(10, loop=hass.loop): with async_timeout.timeout(10):
station = await Station.get(websession, float(latitude), station = await Station.get(websession, float(latitude),
float(longitude)) float(longitude))
@ -106,7 +106,7 @@ class IPMAWeather(WeatherEntity):
@Throttle(MIN_TIME_BETWEEN_UPDATES) @Throttle(MIN_TIME_BETWEEN_UPDATES)
async def async_update(self): async def async_update(self):
"""Update Condition and Forecast.""" """Update Condition and Forecast."""
with async_timeout.timeout(10, loop=self.hass.loop): with async_timeout.timeout(10):
_new_condition = await self._station.observation() _new_condition = await self._station.observation()
if _new_condition is None: if _new_condition is None:
_LOGGER.warning("Could not update weather conditions") _LOGGER.warning("Could not update weather conditions")

View file

@ -231,7 +231,7 @@ async def async_setup_platform(hass, config, async_add_entities,
update_tasks.append(update_coro) update_tasks.append(update_coro)
if update_tasks: if update_tasks:
await asyncio.wait(update_tasks, loop=hass.loop) await asyncio.wait(update_tasks)
if hass.services.has_service(DOMAIN, SERVICE_ADD_MEDIA): if hass.services.has_service(DOMAIN, SERVICE_ADD_MEDIA):
return return

View file

@ -202,7 +202,7 @@ class LIFXManager:
self.entities = {} self.entities = {}
self.hass = hass self.hass = hass
self.async_add_entities = async_add_entities self.async_add_entities = async_add_entities
self.effects_conductor = aiolifx_effects().Conductor(loop=hass.loop) self.effects_conductor = aiolifx_effects().Conductor(hass.loop)
self.discoveries = [] self.discoveries = []
self.cleanup_unsub = self.hass.bus.async_listen( self.cleanup_unsub = self.hass.bus.async_listen(
EVENT_HOMEASSISTANT_STOP, EVENT_HOMEASSISTANT_STOP,
@ -253,7 +253,7 @@ class LIFXManager:
task = light.set_state(**service.data) task = light.set_state(**service.data)
tasks.append(self.hass.async_create_task(task)) tasks.append(self.hass.async_create_task(task))
if tasks: if tasks:
await asyncio.wait(tasks, loop=self.hass.loop) await asyncio.wait(tasks)
self.hass.services.async_register( self.hass.services.async_register(
DOMAIN, SERVICE_LIFX_SET_STATE, service_handler, DOMAIN, SERVICE_LIFX_SET_STATE, service_handler,

View file

@ -38,7 +38,7 @@ async def async_setup_platform(hass, config, async_add_entities,
try: try:
httpsession = async_get_clientsession(hass) httpsession = async_get_clientsession(hass)
with async_timeout.timeout(timeout, loop=hass.loop): with async_timeout.timeout(timeout):
scenes_resp = await httpsession.get(url, headers=headers) scenes_resp = await httpsession.get(url, headers=headers)
except (asyncio.TimeoutError, aiohttp.ClientError): except (asyncio.TimeoutError, aiohttp.ClientError):
@ -83,7 +83,7 @@ class LifxCloudScene(Scene):
try: try:
httpsession = async_get_clientsession(self.hass) httpsession = async_get_clientsession(self.hass)
with async_timeout.timeout(self._timeout, loop=self.hass.loop): with async_timeout.timeout(self._timeout):
await httpsession.put(url, headers=self._headers) await httpsession.put(url, headers=self._headers)
except (asyncio.TimeoutError, aiohttp.ClientError): except (asyncio.TimeoutError, aiohttp.ClientError):

View file

@ -303,7 +303,7 @@ async def async_setup(hass, config):
light.async_update_ha_state(True)) light.async_update_ha_state(True))
if update_tasks: if update_tasks:
await asyncio.wait(update_tasks, loop=hass.loop) await asyncio.wait(update_tasks)
# Listen for light on and light off service calls. # Listen for light on and light off service calls.
hass.services.async_register( hass.services.async_register(

View file

@ -118,7 +118,7 @@ async def async_setup_entry(hass, entry):
return False return False
try: try:
with async_timeout.timeout(_TIMEOUT, loop=hass.loop): with async_timeout.timeout(_TIMEOUT):
# Ensure the cameras property returns the same Camera objects for # Ensure the cameras property returns the same Camera objects for
# all devices. Performs implicit login and session validation. # all devices. Performs implicit login and session validation.
await logi_circle.synchronize_cameras() await logi_circle.synchronize_cameras()

View file

@ -160,7 +160,7 @@ class LogiCircleFlowHandler(config_entries.ConfigFlow):
cache_file=DEFAULT_CACHEDB) cache_file=DEFAULT_CACHEDB)
try: try:
with async_timeout.timeout(_TIMEOUT, loop=self.hass.loop): with async_timeout.timeout(_TIMEOUT):
await logi_session.authorize(code) await logi_session.authorize(code)
except AuthorizationFailed: except AuthorizationFailed:
(self.hass.data[DATA_FLOW_IMPL][DOMAIN] (self.hass.data[DATA_FLOW_IMPL][DOMAIN]

View file

@ -82,7 +82,7 @@ async def async_setup(hass, config):
in config_per_platform(config, DOMAIN)] in config_per_platform(config, DOMAIN)]
if setup_tasks: if setup_tasks:
await asyncio.wait(setup_tasks, loop=hass.loop) await asyncio.wait(setup_tasks)
async def async_platform_discovered(platform, info): async def async_platform_discovered(platform, info):
"""Handle for discovered platform.""" """Handle for discovered platform."""
@ -241,9 +241,8 @@ class MailboxMediaView(MailboxView):
"""Retrieve media.""" """Retrieve media."""
mailbox = self.get_mailbox(platform) mailbox = self.get_mailbox(platform)
hass = request.app['hass']
with suppress(asyncio.CancelledError, asyncio.TimeoutError): with suppress(asyncio.CancelledError, asyncio.TimeoutError):
with async_timeout.timeout(10, loop=hass.loop): with async_timeout.timeout(10):
try: try:
stream = await mailbox.async_get_media(msgid) stream = await mailbox.async_get_media(msgid)
except StreamError as err: except StreamError as err:

View file

@ -75,7 +75,7 @@ class MaryTTSProvider(Provider):
actual_language = re.sub('-', '_', language) actual_language = re.sub('-', '_', language)
try: try:
with async_timeout.timeout(10, loop=self.hass.loop): with async_timeout.timeout(10):
url = 'http://{}:{}/process?'.format(self._host, self._port) url = 'http://{}:{}/process?'.format(self._host, self._port)
audio = self._codec.upper() audio = self._codec.upper()

View file

@ -777,7 +777,7 @@ async def _async_fetch_image(hass, url):
url = hass.config.api.base_url + url url = hass.config.api.base_url + url
if url not in cache_images: if url not in cache_images:
cache_images[url] = {CACHE_LOCK: asyncio.Lock(loop=hass.loop)} cache_images[url] = {CACHE_LOCK: asyncio.Lock()}
async with cache_images[url][CACHE_LOCK]: async with cache_images[url][CACHE_LOCK]:
if CACHE_CONTENT in cache_images[url]: if CACHE_CONTENT in cache_images[url]:
@ -786,7 +786,7 @@ async def _async_fetch_image(hass, url):
content, content_type = (None, None) content, content_type = (None, None)
websession = async_get_clientsession(hass) websession = async_get_clientsession(hass)
try: try:
with async_timeout.timeout(10, loop=hass.loop): with async_timeout.timeout(10):
response = await websession.get(url) response = await websession.get(url)
if response.status == 200: if response.status == 200:

View file

@ -277,7 +277,7 @@ 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:
await asyncio.wait(tasks, loop=self.hass.loop) await asyncio.wait(tasks)
async def call_api(self, method, function, data=None, binary=False, async def call_api(self, method, function, data=None, binary=False,
params=None): params=None):
@ -297,7 +297,7 @@ class MicrosoftFace:
payload = None payload = None
try: try:
with async_timeout.timeout(self.timeout, loop=self.hass.loop): with async_timeout.timeout(self.timeout):
response = await getattr(self.websession, method)( response = await getattr(self.websession, method)(
url, data=payload, headers=headers, params=params) url, data=payload, headers=headers, params=params)

View file

@ -112,7 +112,7 @@ class MjpegCamera(Camera):
verify_ssl=self._verify_ssl verify_ssl=self._verify_ssl
) )
try: try:
with async_timeout.timeout(10, loop=self.hass.loop): with async_timeout.timeout(10):
response = await websession.get( response = await websession.get(
self._still_image_url, auth=self._auth) self._still_image_url, auth=self._auth)

View file

@ -115,7 +115,7 @@ class MobileAppNotificationService(BaseNotificationService):
data['registration_info'] = reg_info data['registration_info'] = reg_info
try: try:
with async_timeout.timeout(10, loop=self.hass.loop): with async_timeout.timeout(10):
response = await self._session.post(push_url, json=data) response = await self._session.post(push_url, json=data)
result = await response.json() result = await response.json()

View file

@ -651,7 +651,7 @@ class MQTT:
self.birth_message = birth_message self.birth_message = birth_message
self.connected = False self.connected = False
self._mqttc = None # type: mqtt.Client self._mqttc = None # type: mqtt.Client
self._paho_lock = asyncio.Lock(loop=hass.loop) self._paho_lock = asyncio.Lock()
if protocol == PROTOCOL_31: if protocol == PROTOCOL_31:
proto = mqtt.MQTTv31 # type: int proto = mqtt.MQTTv31 # type: int

View file

@ -151,9 +151,9 @@ async def finish_setup(hass, hass_config, gateways):
start_tasks.append(_gw_start(hass, gateway)) start_tasks.append(_gw_start(hass, gateway))
if discover_tasks: if discover_tasks:
# Make sure all devices and platforms are loaded before gateway start. # Make sure all devices and platforms are loaded before gateway start.
await asyncio.wait(discover_tasks, loop=hass.loop) await asyncio.wait(discover_tasks)
if start_tasks: if start_tasks:
await asyncio.wait(start_tasks, loop=hass.loop) await asyncio.wait(start_tasks)
async def _discover_persistent_devices(hass, hass_config, gateway): async def _discover_persistent_devices(hass, hass_config, gateway):
@ -172,7 +172,7 @@ async def _discover_persistent_devices(hass, hass_config, gateway):
tasks.append(discover_mysensors_platform( tasks.append(discover_mysensors_platform(
hass, hass_config, platform, dev_ids)) hass, hass_config, platform, dev_ids))
if tasks: if tasks:
await asyncio.wait(tasks, loop=hass.loop) await asyncio.wait(tasks)
async def _gw_start(hass, gateway): async def _gw_start(hass, gateway):
@ -196,7 +196,7 @@ async def _gw_start(hass, gateway):
hass.data[gateway_ready_key] = gateway_ready hass.data[gateway_ready_key] = gateway_ready
try: try:
with async_timeout.timeout(GATEWAY_READY_TIMEOUT, loop=hass.loop): with async_timeout.timeout(GATEWAY_READY_TIMEOUT):
await gateway_ready await gateway_ready
except asyncio.TimeoutError: except asyncio.TimeoutError:
_LOGGER.warning( _LOGGER.warning(

View file

@ -89,7 +89,7 @@ async 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):
resp = await session.get(url, params=params, headers=headers) resp = await session.get(url, params=params, headers=headers)
body = await resp.text() body = await resp.text()

View file

@ -139,7 +139,7 @@ async def async_setup(hass, config):
in config_per_platform(config, DOMAIN)] in config_per_platform(config, DOMAIN)]
if setup_tasks: if setup_tasks:
await asyncio.wait(setup_tasks, loop=hass.loop) await asyncio.wait(setup_tasks)
async def async_platform_discovered(platform, info): async def async_platform_discovered(platform, info):
"""Handle for discovered platform.""" """Handle for discovered platform."""

View file

@ -308,7 +308,7 @@ class ONVIFHassCamera(Camera):
image = await asyncio.shield(ffmpeg.get_image( image = await asyncio.shield(ffmpeg.get_image(
self._input, output_format=IMAGE_JPEG, self._input, output_format=IMAGE_JPEG,
extra_cmd=self._ffmpeg_arguments), loop=self.hass.loop) extra_cmd=self._ffmpeg_arguments))
return image return image
async def handle_async_mjpeg_stream(self, request): async def handle_async_mjpeg_stream(self, request):

View file

@ -108,7 +108,7 @@ class OpenAlprCloudEntity(ImageProcessingAlprEntity):
} }
try: try:
with async_timeout.timeout(self.timeout, loop=self.hass.loop): with async_timeout.timeout(self.timeout):
request = await websession.post( request = await websession.post(
OPENALPR_API_URL, params=params, data=body OPENALPR_API_URL, params=params, data=body
) )

View file

@ -52,7 +52,7 @@ class ProwlNotificationService(BaseNotificationService):
session = async_get_clientsession(self._hass) session = async_get_clientsession(self._hass)
try: try:
with async_timeout.timeout(10, loop=self._hass.loop): with async_timeout.timeout(10):
response = await session.post(url, data=payload) response = await session.post(url, data=payload)
result = await response.text() result = await response.text()

View file

@ -60,7 +60,7 @@ async def async_setup_platform(hass, config, async_add_entities,
async def handle_webhook(hass, webhook_id, request): async def handle_webhook(hass, webhook_id, request):
"""Handle incoming webhook POST with image files.""" """Handle incoming webhook POST with image files."""
try: try:
with async_timeout.timeout(5, loop=hass.loop): with async_timeout.timeout(5):
data = dict(await request.post()) data = dict(await request.post())
except (asyncio.TimeoutError, aiohttp.web.HTTPException) as error: except (asyncio.TimeoutError, aiohttp.web.HTTPException) as error:
_LOGGER.error("Could not get information from POST <%s>", error) _LOGGER.error("Could not get information from POST <%s>", error)

View file

@ -141,7 +141,7 @@ class Recorder(threading.Thread):
self.queue = queue.Queue() # type: Any self.queue = queue.Queue() # type: Any
self.recording_start = dt_util.utcnow() self.recording_start = dt_util.utcnow()
self.db_url = uri self.db_url = uri
self.async_db_ready = asyncio.Future(loop=hass.loop) self.async_db_ready = asyncio.Future()
self.engine = None # type: Any self.engine = None # type: Any
self.run_info = None # type: Any self.run_info = None # type: Any

View file

@ -33,7 +33,7 @@ async def async_setup_platform(hass, config, async_add_entities,
if not hass.data.get(DATA_RSN): if not hass.data.get(DATA_RSN):
hass.data[DATA_RSN] = RSNetwork() hass.data[DATA_RSN] = RSNetwork()
job = hass.data[DATA_RSN].create_datagram_endpoint(loop=hass.loop) job = hass.data[DATA_RSN].create_datagram_endpoint()
hass.async_create_task(job) hass.async_create_task(job)
device = hass.data[DATA_RSN].register_device(mac_address, host) device = hass.data[DATA_RSN].register_device(mac_address, host)

View file

@ -149,7 +149,7 @@ class RestSwitch(SwitchDevice):
"""Send a state update to the device.""" """Send a state update to the device."""
websession = async_get_clientsession(self.hass, self._verify_ssl) websession = async_get_clientsession(self.hass, self._verify_ssl)
with async_timeout.timeout(self._timeout, loop=self.hass.loop): with async_timeout.timeout(self._timeout):
req = await getattr(websession, self._method)( req = await getattr(websession, self._method)(
self._resource, auth=self._auth, data=bytes(body, 'utf-8'), self._resource, auth=self._auth, data=bytes(body, 'utf-8'),
headers=self._headers) headers=self._headers)
@ -168,7 +168,7 @@ class RestSwitch(SwitchDevice):
"""Get the latest data from REST API and update the state.""" """Get the latest data from REST API and update the state."""
websession = async_get_clientsession(hass, self._verify_ssl) websession = async_get_clientsession(hass, self._verify_ssl)
with async_timeout.timeout(self._timeout, loop=hass.loop): with async_timeout.timeout(self._timeout):
req = await websession.get(self._resource, auth=self._auth, req = await websession.get(self._resource, auth=self._auth,
headers=self._headers) headers=self._headers)
text = await req.text() text = await req.text()

View file

@ -92,7 +92,7 @@ async def async_setup(hass, config):
'utf-8') 'utf-8')
try: try:
with async_timeout.timeout(timeout, loop=hass.loop): with async_timeout.timeout(timeout):
request = await 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,

View file

@ -116,7 +116,7 @@ class RingCam(Camera):
image = await asyncio.shield(ffmpeg.get_image( image = await asyncio.shield(ffmpeg.get_image(
self._video_url, output_format=IMAGE_JPEG, self._video_url, output_format=IMAGE_JPEG,
extra_cmd=self._ffmpeg_arguments), loop=self.hass.loop) extra_cmd=self._ffmpeg_arguments))
return image return image
async def handle_async_mjpeg_stream(self, request): async def handle_async_mjpeg_stream(self, request):

View file

@ -70,7 +70,7 @@ async def async_setup(hass, config):
tasks = [scene.async_activate() for scene in target_scenes] tasks = [scene.async_activate() for scene in target_scenes]
if tasks: if tasks:
await asyncio.wait(tasks, loop=hass.loop) await asyncio.wait(tasks)
hass.services.async_register( hass.services.async_register(
DOMAIN, SERVICE_TURN_ON, async_handle_scene_service, DOMAIN, SERVICE_TURN_ON, async_handle_scene_service,

View file

@ -82,7 +82,7 @@ async def async_setup(hass, config):
await asyncio.wait([ await asyncio.wait([
script.async_turn_off() for script script.async_turn_off() for script
in await component.async_extract_from_service(service) in await component.async_extract_from_service(service)
], loop=hass.loop) ])
async def toggle_service(service): async def toggle_service(service):
"""Toggle a script.""" """Toggle a script."""

View file

@ -101,7 +101,7 @@ async def async_setup_platform(hass, config, async_add_entities,
update_tasks.append(climate.async_update_ha_state(True)) update_tasks.append(climate.async_update_ha_state(True))
if update_tasks: if update_tasks:
await asyncio.wait(update_tasks, loop=hass.loop) await asyncio.wait(update_tasks)
hass.services.async_register( hass.services.async_register(
DOMAIN, SERVICE_ASSUME_STATE, async_assume_state, DOMAIN, SERVICE_ASSUME_STATE, async_assume_state,
schema=ASSUME_STATE_SCHEMA) schema=ASSUME_STATE_SCHEMA)

View file

@ -141,7 +141,7 @@ async def async_setup_platform(
if task: if task:
tasks.append(task) tasks.append(task)
if tasks: if tasks:
await asyncio.wait(tasks, loop=hass.loop) await asyncio.wait(tasks)
interval = config.get(CONF_SCAN_INTERVAL) or timedelta(seconds=5) interval = config.get(CONF_SCAN_INTERVAL) or timedelta(seconds=5)
async_track_time_interval(hass, async_sma, interval) async_track_time_interval(hass, async_sma, interval)

View file

@ -107,7 +107,7 @@ class SmhiWeather(WeatherEntity):
RETRY_TIMEOUT, self.retry_update()) RETRY_TIMEOUT, self.retry_update())
try: try:
with async_timeout.timeout(10, loop=self.hass.loop): with async_timeout.timeout(10):
self._forecasts = await self.get_weather_forecast() self._forecasts = await self.get_weather_forecast()
self._fail_count = 0 self._fail_count = 0

View file

@ -63,7 +63,7 @@ class SonosData:
def __init__(self, hass): def __init__(self, hass):
"""Initialize the data.""" """Initialize the data."""
self.entities = [] self.entities = []
self.topology_condition = asyncio.Condition(loop=hass.loop) self.topology_condition = asyncio.Condition()
async def async_setup_platform(hass, async def async_setup_platform(hass,

View file

@ -128,7 +128,7 @@ async def async_setup_platform(hass, config, async_add_entities,
update_tasks.append(player.async_update_ha_state(True)) update_tasks.append(player.async_update_ha_state(True))
if update_tasks: if update_tasks:
await asyncio.wait(update_tasks, loop=hass.loop) await asyncio.wait(update_tasks)
for service in SERVICE_TO_METHOD: for service in SERVICE_TO_METHOD:
schema = SERVICE_TO_METHOD[service]['schema'] schema = SERVICE_TO_METHOD[service]['schema']
@ -179,7 +179,7 @@ class LogitechMediaServer:
try: try:
websession = async_get_clientsession(self.hass) websession = async_get_clientsession(self.hass)
with async_timeout.timeout(TIMEOUT, loop=self.hass.loop): with async_timeout.timeout(TIMEOUT):
response = await websession.post( response = await websession.post(
url, url,
data=data, data=data,

View file

@ -138,7 +138,7 @@ class StartcaData:
_LOGGER.debug("Updating Start.ca usage data") _LOGGER.debug("Updating Start.ca usage data")
url = 'https://www.start.ca/support/usage/api?key=' + \ url = 'https://www.start.ca/support/usage/api?key=' + \
self.api_key self.api_key
with async_timeout.timeout(REQUEST_TIMEOUT, loop=self.loop): with async_timeout.timeout(REQUEST_TIMEOUT):
req = await self.websession.get(url) req = await self.websession.get(url)
if req.status != 200: if req.status != 200:
_LOGGER.error("Request failed with status: %u", req.status) _LOGGER.error("Request failed with status: %u", req.status)

View file

@ -62,8 +62,7 @@ async def async_setup(hass: HomeAssistantType, config: Dict) -> bool:
EVENT_HOMEASSISTANT_STOP, async_stop_bridge)) EVENT_HOMEASSISTANT_STOP, async_stop_bridge))
try: try:
device_data = await wait_for( device_data = await wait_for(v2bridge.queue.get(), timeout=10.0)
v2bridge.queue.get(), timeout=10.0, loop=hass.loop)
except (Asyncio_TimeoutError, RuntimeError): except (Asyncio_TimeoutError, RuntimeError):
_LOGGER.exception("failed to get response from device") _LOGGER.exception("failed to get response from device")
await v2bridge.stop() await v2bridge.stop()

View file

@ -61,7 +61,7 @@ class TadoDeviceScanner(DeviceScanner):
self.tadoapiurl += '?username={username}&password={password}' self.tadoapiurl += '?username={username}&password={password}'
self.websession = async_create_clientsession( self.websession = async_create_clientsession(
hass, cookie_jar=aiohttp.CookieJar(unsafe=True, loop=hass.loop)) hass, cookie_jar=aiohttp.CookieJar(unsafe=True))
self.success_init = asyncio.run_coroutine_threadsafe( self.success_init = asyncio.run_coroutine_threadsafe(
self._async_update_info(), hass.loop self._async_update_info(), hass.loop

View file

@ -132,7 +132,7 @@ class TekSavvyData:
_LOGGER.debug("Updating TekSavvy data") _LOGGER.debug("Updating TekSavvy data")
url = "https://api.teksavvy.com/"\ url = "https://api.teksavvy.com/"\
"web/Usage/UsageSummaryRecords?$filter=IsCurrent%20eq%20true" "web/Usage/UsageSummaryRecords?$filter=IsCurrent%20eq%20true"
with async_timeout.timeout(REQUEST_TIMEOUT, loop=self.loop): with async_timeout.timeout(REQUEST_TIMEOUT):
req = await self.websession.get(url, headers=headers) req = await self.websession.get(url, headers=headers)
if req.status != 200: if req.status != 200:
_LOGGER.error("Request failed with status: %u", req.status) _LOGGER.error("Request failed with status: %u", req.status)

View file

@ -124,7 +124,7 @@ class TtnDataStorage:
"""Get the current state from The Things Network Data Storage.""" """Get the current state from The Things Network Data Storage."""
try: try:
session = async_get_clientsession(self._hass) session = async_get_clientsession(self._hass)
with async_timeout.timeout(DEFAULT_TIMEOUT, loop=self._hass.loop): with async_timeout.timeout(DEFAULT_TIMEOUT):
response = await session.get(self._url, headers=self._headers) response = await session.get(self._url, headers=self._headers)
except (asyncio.TimeoutError, aiohttp.ClientError): except (asyncio.TimeoutError, aiohttp.ClientError):

View file

@ -143,7 +143,7 @@ async def authenticate(hass, host, security_code):
identity = uuid4().hex identity = uuid4().hex
api_factory = APIFactory(host, psk_id=identity, loop=hass.loop) api_factory = APIFactory(host, psk_id=identity)
try: try:
with async_timeout.timeout(5): with async_timeout.timeout(5):

View file

@ -165,7 +165,7 @@ async def async_setup(hass, config):
in config_per_platform(config, DOMAIN)] in config_per_platform(config, DOMAIN)]
if setup_tasks: if setup_tasks:
await asyncio.wait(setup_tasks, loop=hass.loop) await asyncio.wait(setup_tasks)
async def async_clear_cache_handle(service): async def async_clear_cache_handle(service):
"""Handle clear cache service call.""" """Handle clear cache service call."""

View file

@ -81,7 +81,7 @@ class UPCDeviceScanner(DeviceScanner):
"""Get first token.""" """Get first token."""
try: try:
# get first token # get first token
with async_timeout.timeout(10, loop=self.hass.loop): with async_timeout.timeout(10):
response = await self.websession.get( response = await self.websession.get(
"http://{}/common_page/login.html".format(self.host), "http://{}/common_page/login.html".format(self.host),
headers=self.headers) headers=self.headers)
@ -99,7 +99,7 @@ class UPCDeviceScanner(DeviceScanner):
async def _async_ws_function(self, function): async def _async_ws_function(self, function):
"""Execute a command on UPC firmware webservice.""" """Execute a command on UPC firmware webservice."""
try: try:
with async_timeout.timeout(10, loop=self.hass.loop): with async_timeout.timeout(10):
# The 'token' parameter has to be first, and 'fun' second # The 'token' parameter has to be first, and 'fun' second
# or the UPC firmware will return an error # or the UPC firmware will return an error
response = await self.websession.post( response = await self.websession.post(

View file

@ -136,7 +136,7 @@ async def get_newest_version(hass, huuid, include_components):
session = async_get_clientsession(hass) session = async_get_clientsession(hass)
try: try:
with async_timeout.timeout(5, loop=hass.loop): with async_timeout.timeout(5):
req = await session.post(UPDATER_URL, json=info_object) req = await session.post(UPDATER_URL, json=info_object)
_LOGGER.info(("Submitted analytics to Home Assistant servers. " _LOGGER.info(("Submitted analytics to Home Assistant servers. "
"Information submitted includes %s"), info_object) "Information submitted includes %s"), info_object)

View file

@ -67,7 +67,7 @@ async def async_http_request(hass, uri):
"""Perform actual request.""" """Perform actual request."""
try: try:
session = hass.helpers.aiohttp_client.async_get_clientsession(hass) session = hass.helpers.aiohttp_client.async_get_clientsession(hass)
with async_timeout.timeout(REQUEST_TIMEOUT, loop=hass.loop): with async_timeout.timeout(REQUEST_TIMEOUT):
req = await session.get(uri) req = await session.get(uri)
if req.status != 200: if req.status != 200:
return {'error': req.status} return {'error': req.status}

View file

@ -116,7 +116,7 @@ class VoiceRSSProvider(Provider):
form_data['hl'] = language form_data['hl'] = language
try: try:
with async_timeout.timeout(10, loop=self.hass.loop): with async_timeout.timeout(10):
request = await websession.post( request = await websession.post(
VOICERSS_API_URL, data=form_data VOICERSS_API_URL, data=form_data
) )

View file

@ -40,7 +40,7 @@ class WebSocketHandler:
self.hass = hass self.hass = hass
self.request = request self.request = request
self.wsock = None self.wsock = None
self._to_write = asyncio.Queue(maxsize=MAX_PENDING_MSG, loop=hass.loop) self._to_write = asyncio.Queue(maxsize=MAX_PENDING_MSG)
self._handle_task = None self._handle_task = None
self._writer_task = None self._writer_task = None
self._logger = logging.getLogger( self._logger = logging.getLogger(
@ -101,7 +101,7 @@ class WebSocketHandler:
# pylint: disable=no-member # pylint: disable=no-member
self._handle_task = asyncio.current_task() self._handle_task = asyncio.current_task()
else: else:
self._handle_task = asyncio.Task.current_task(loop=self.hass.loop) self._handle_task = asyncio.Task.current_task()
@callback @callback
def handle_hass_stop(event): def handle_hass_stop(event):

View file

@ -88,7 +88,7 @@ class WorxLandroidSensor(Entity):
try: try:
session = async_get_clientsession(self.hass) session = async_get_clientsession(self.hass)
with async_timeout.timeout(self.timeout, loop=self.hass.loop): with async_timeout.timeout(self.timeout):
auth = aiohttp.helpers.BasicAuth('admin', self.pin) auth = aiohttp.helpers.BasicAuth('admin', self.pin)
mower_response = await session.get(self.url, auth=auth) mower_response = await session.get(self.url, auth=auth)
except (asyncio.TimeoutError, aiohttp.ClientError): except (asyncio.TimeoutError, aiohttp.ClientError):

View file

@ -807,7 +807,7 @@ class WUndergroundData:
async def async_update(self): async def async_update(self):
"""Get the latest data from WUnderground.""" """Get the latest data from WUnderground."""
try: try:
with async_timeout.timeout(10, loop=self._hass.loop): with async_timeout.timeout(10):
response = await self._session.get(self._build_url()) response = await self._session.get(self._build_url())
result = await response.json() result = await response.json()
if "error" in result['response']: if "error" in result['response']:

View file

@ -140,7 +140,7 @@ class XiaomiCamera(Camera):
ffmpeg = ImageFrame(self._manager.binary, loop=self.hass.loop) ffmpeg = ImageFrame(self._manager.binary, loop=self.hass.loop)
self._last_image = await asyncio.shield(ffmpeg.get_image( self._last_image = await asyncio.shield(ffmpeg.get_image(
url, output_format=IMAGE_JPEG, url, output_format=IMAGE_JPEG,
extra_cmd=self._extra_arguments), loop=self.hass.loop) extra_cmd=self._extra_arguments))
self._last_url = url self._last_url = url
return self._last_image return self._last_image

View file

@ -467,7 +467,7 @@ async def async_setup_platform(hass, config, async_add_entities,
update_tasks.append(device.async_update_ha_state(True)) update_tasks.append(device.async_update_ha_state(True))
if update_tasks: if update_tasks:
await asyncio.wait(update_tasks, loop=hass.loop) await asyncio.wait(update_tasks)
for air_purifier_service in SERVICE_TO_METHOD: for air_purifier_service in SERVICE_TO_METHOD:
schema = SERVICE_TO_METHOD[air_purifier_service].get( schema = SERVICE_TO_METHOD[air_purifier_service].get(

View file

@ -203,7 +203,7 @@ async def async_setup_platform(hass, config, async_add_entities,
update_tasks.append(target_device.async_update_ha_state(True)) update_tasks.append(target_device.async_update_ha_state(True))
if update_tasks: if update_tasks:
await asyncio.wait(update_tasks, loop=hass.loop) await asyncio.wait(update_tasks)
for xiaomi_miio_service in SERVICE_TO_METHOD: for xiaomi_miio_service in SERVICE_TO_METHOD:
schema = SERVICE_TO_METHOD[xiaomi_miio_service].get( schema = SERVICE_TO_METHOD[xiaomi_miio_service].get(

View file

@ -142,7 +142,7 @@ async def async_setup_platform(hass, config, async_add_entities,
message['error']['message'] == "learn timeout"): message['error']['message'] == "learn timeout"):
await hass.async_add_executor_job(device.learn, slot) await hass.async_add_executor_job(device.learn, slot)
await asyncio.sleep(1, loop=hass.loop) await asyncio.sleep(1)
_LOGGER.error("Timeout. No infrared command captured") _LOGGER.error("Timeout. No infrared command captured")
hass.components.persistent_notification.async_create( hass.components.persistent_notification.async_create(

View file

@ -185,7 +185,7 @@ async def async_setup_platform(hass, config, async_add_entities,
update_tasks.append(device.async_update_ha_state(True)) update_tasks.append(device.async_update_ha_state(True))
if update_tasks: if update_tasks:
await asyncio.wait(update_tasks, loop=hass.loop) await asyncio.wait(update_tasks)
for plug_service in SERVICE_TO_METHOD: for plug_service in SERVICE_TO_METHOD:
schema = SERVICE_TO_METHOD[plug_service].get('schema', SERVICE_SCHEMA) schema = SERVICE_TO_METHOD[plug_service].get('schema', SERVICE_SCHEMA)

View file

@ -165,7 +165,7 @@ async def async_setup_platform(hass, config, async_add_entities,
update_tasks.append(update_coro) update_tasks.append(update_coro)
if update_tasks: if update_tasks:
await asyncio.wait(update_tasks, loop=hass.loop) await asyncio.wait(update_tasks)
for vacuum_service in SERVICE_TO_METHOD: for vacuum_service in SERVICE_TO_METHOD:
schema = SERVICE_TO_METHOD[vacuum_service].get( schema = SERVICE_TO_METHOD[vacuum_service].get(

View file

@ -111,7 +111,7 @@ class YandexSpeechKitProvider(Provider):
options = options or {} options = options or {}
try: try:
with async_timeout.timeout(10, loop=self.hass.loop): with async_timeout.timeout(10):
url_param = { url_param = {
'text': message, 'text': message,
'lang': actual_language, 'lang': actual_language,

View file

@ -77,7 +77,7 @@ class YiCamera(Camera):
"""Retrieve the latest video file from the customized Yi FTP server.""" """Retrieve the latest video file from the customized Yi FTP server."""
from aioftp import Client, StatusCodeError from aioftp import Client, StatusCodeError
ftp = Client(loop=self.hass.loop) ftp = Client()
try: try:
await ftp.connect(self.host) await ftp.connect(self.host)
await ftp.login(self.user, self.passwd) await ftp.login(self.user, self.passwd)

View file

@ -160,7 +160,7 @@ class YrData:
async_call_later(self.hass, minutes*60, self.fetching_data) async_call_later(self.hass, minutes*60, self.fetching_data)
try: try:
websession = async_get_clientsession(self.hass) websession = async_get_clientsession(self.hass)
with async_timeout.timeout(10, loop=self.hass.loop): with async_timeout.timeout(10):
resp = await websession.get( resp = await websession.get(
self._url, params=self._urlparams) self._url, params=self._urlparams)
if resp.status != 200: if resp.status != 200:
@ -247,4 +247,4 @@ class YrData:
tasks.append(dev.async_update_ha_state()) tasks.append(dev.async_update_ha_state())
if tasks: if tasks:
await asyncio.wait(tasks, loop=self.hass.loop) await asyncio.wait(tasks)

Some files were not shown because too many files have changed in this diff Show more