Use asyncio.timeout [f-h] (#98449)

This commit is contained in:
Marc Mueller 2023-08-15 15:37:06 +02:00 committed by GitHub
parent a9ade1f84d
commit 5dd3f05db8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
28 changed files with 48 additions and 61 deletions

View File

@ -1,9 +1,9 @@
"""The FAA Delays integration."""
import asyncio
from datetime import timedelta
import logging
from aiohttp import ClientConnectionError
from async_timeout import timeout
from faadelays import Airport
from homeassistant.config_entries import ConfigEntry
@ -56,7 +56,7 @@ class FAADataUpdateCoordinator(DataUpdateCoordinator):
async def _async_update_data(self):
try:
async with timeout(10):
async with asyncio.timeout(10):
await self.data.update()
except ClientConnectionError as err:
raise UpdateFailed(err) from err

View File

@ -2,7 +2,6 @@
import asyncio
import logging
import async_timeout
from pyflick.authentication import AuthException, SimpleFlickAuth
from pyflick.const import DEFAULT_CLIENT_ID, DEFAULT_CLIENT_SECRET
import voluptuous as vol
@ -45,7 +44,7 @@ class FlickConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
)
try:
async with async_timeout.timeout(60):
async with asyncio.timeout(60):
token = await auth.async_get_access_token()
except asyncio.TimeoutError as err:
raise CannotConnect() from err

View File

@ -1,9 +1,9 @@
"""Support for Flick Electric Pricing data."""
import asyncio
from datetime import timedelta
import logging
from typing import Any
import async_timeout
from pyflick import FlickAPI, FlickPrice
from homeassistant.components.sensor import SensorEntity
@ -58,7 +58,7 @@ class FlickPricingSensor(SensorEntity):
if self._price and self._price.end_at >= utcnow():
return # Power price data is still valid
async with async_timeout.timeout(60):
async with asyncio.timeout(60):
self._price = await self._api.getPricing()
_LOGGER.debug("Pricing data: %s", self._price)

View File

@ -1,12 +1,12 @@
"""Flo device object."""
from __future__ import annotations
import asyncio
from datetime import datetime, timedelta
from typing import Any
from aioflo.api import API
from aioflo.errors import RequestError
from async_timeout import timeout
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
@ -39,7 +39,7 @@ class FloDeviceDataUpdateCoordinator(DataUpdateCoordinator):
async def _async_update_data(self):
"""Update data via library."""
try:
async with timeout(20):
async with asyncio.timeout(20):
await self.send_presence_ping()
await self._update_device()
await self._update_consumption_data()

View File

@ -5,7 +5,6 @@ import asyncio
from http import HTTPStatus
import logging
import async_timeout
import voluptuous as vol
from homeassistant.components.notify import PLATFORM_SCHEMA, BaseNotificationService
@ -49,7 +48,7 @@ class FlockNotificationService(BaseNotificationService):
_LOGGER.debug("Attempting to call Flock at %s", self._url)
try:
async with async_timeout.timeout(10):
async with asyncio.timeout(10):
response = await self._session.post(self._url, json=payload)
result = await response.json()

View File

@ -6,7 +6,6 @@ from collections import defaultdict
import logging
from typing import Any
import async_timeout
from pyforked_daapd import ForkedDaapdAPI
from pylibrespot_java import LibrespotJavaAPI
@ -667,7 +666,7 @@ class ForkedDaapdMaster(MediaPlayerEntity):
self._pause_requested = True
await self.async_media_pause()
try:
async with async_timeout.timeout(CALLBACK_TIMEOUT):
async with asyncio.timeout(CALLBACK_TIMEOUT):
await self._paused_event.wait() # wait for paused
except asyncio.TimeoutError:
self._pause_requested = False
@ -762,7 +761,7 @@ class ForkedDaapdMaster(MediaPlayerEntity):
await sleep_future
await self.api.add_to_queue(uris=media_id, playback="start", clear=True)
try:
async with async_timeout.timeout(TTS_TIMEOUT):
async with asyncio.timeout(TTS_TIMEOUT):
await self._tts_playing_event.wait()
# we have started TTS, now wait for completion
except asyncio.TimeoutError:

View File

@ -4,7 +4,6 @@ from datetime import datetime, timedelta
import logging
import aiohttp
import async_timeout
import voluptuous as vol
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_SCAN_INTERVAL, CONF_URL
@ -76,7 +75,7 @@ async def _update_freedns(hass, session, url, auth_token):
params[auth_token] = ""
try:
async with async_timeout.timeout(TIMEOUT):
async with asyncio.timeout(TIMEOUT):
resp = await session.get(url, params=params)
body = await resp.text()

View File

@ -6,7 +6,6 @@ import json
from typing import Any
from aiohttp.client_exceptions import ClientConnectorError
from async_timeout import timeout
from fullykiosk import FullyKiosk
from fullykiosk.exceptions import FullyKioskError
import voluptuous as vol
@ -42,7 +41,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
)
try:
async with timeout(15):
async with asyncio.timeout(15):
device_info = await fully.getDeviceInfo()
except (
ClientConnectorError,

View File

@ -2,7 +2,6 @@
import asyncio
from typing import Any, cast
from async_timeout import timeout
from fullykiosk import FullyKiosk
from fullykiosk.exceptions import FullyKioskError
@ -36,7 +35,7 @@ class FullyKioskDataUpdateCoordinator(DataUpdateCoordinator):
async def _async_update_data(self) -> dict[str, Any]:
"""Update data via library."""
try:
async with timeout(15):
async with asyncio.timeout(15):
# Get device info and settings in parallel
result = await asyncio.gather(
self.fully.getDeviceInfo(), self.fully.getSettings()

View File

@ -1,8 +1,8 @@
"""The Garages Amsterdam integration."""
import asyncio
from datetime import timedelta
import logging
import async_timeout
from odp_amsterdam import ODPAmsterdam
from homeassistant.config_entries import ConfigEntry
@ -40,7 +40,7 @@ async def get_coordinator(
return hass.data[DOMAIN]
async def async_get_garages():
async with async_timeout.timeout(10):
async with asyncio.timeout(10):
return {
garage.garage_name: garage
for garage in await ODPAmsterdam(

View File

@ -1,6 +1,7 @@
"""Config flow for generic (IP Camera)."""
from __future__ import annotations
import asyncio
from collections.abc import Mapping
import contextlib
from datetime import datetime
@ -10,7 +11,6 @@ import logging
from typing import Any
from aiohttp import web
from async_timeout import timeout
from httpx import HTTPStatusError, RequestError, TimeoutException
import PIL.Image
import voluptuous as vol
@ -171,7 +171,7 @@ async def async_test_still(
auth = generate_auth(info)
try:
async_client = get_async_client(hass, verify_ssl=verify_ssl)
async with timeout(GET_IMAGE_TIMEOUT):
async with asyncio.timeout(GET_IMAGE_TIMEOUT):
response = await async_client.get(url, auth=auth, timeout=GET_IMAGE_TIMEOUT)
response.raise_for_status()
image = response.content

View File

@ -1,11 +1,11 @@
"""The GIOS component."""
from __future__ import annotations
import asyncio
import logging
from aiohttp import ClientSession
from aiohttp.client_exceptions import ClientConnectorError
from async_timeout import timeout
from gios import Gios
from gios.exceptions import GiosError
from gios.model import GiosSensors
@ -88,7 +88,7 @@ class GiosDataUpdateCoordinator(DataUpdateCoordinator[GiosSensors]):
async def _async_update_data(self) -> GiosSensors:
"""Update data via library."""
try:
async with timeout(API_TIMEOUT):
async with asyncio.timeout(API_TIMEOUT):
return await self.gios.async_update()
except (GiosError, ClientConnectorError) as error:
raise UpdateFailed(error) from error

View File

@ -5,7 +5,6 @@ import asyncio
from typing import Any
from aiohttp.client_exceptions import ClientConnectorError
from async_timeout import timeout
from gios import ApiError, Gios, InvalidSensorsDataError, NoStationError
import voluptuous as vol
@ -37,7 +36,7 @@ class GiosFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
websession = async_get_clientsession(self.hass)
async with timeout(API_TIMEOUT):
async with asyncio.timeout(API_TIMEOUT):
gios = Gios(user_input[CONF_STATION_ID], websession)
await gios.async_update()

View File

@ -3,7 +3,6 @@ import asyncio
import logging
import os
import async_timeout
from google.cloud import texttospeech
import voluptuous as vol
@ -286,7 +285,7 @@ class GoogleCloudTTSProvider(Provider):
"input": synthesis_input,
}
async with async_timeout.timeout(10):
async with asyncio.timeout(10):
assert self.hass
response = await self.hass.async_add_executor_job(
self._client.synthesize_speech, request

View File

@ -4,7 +4,6 @@ from datetime import timedelta
import logging
import aiohttp
import async_timeout
import voluptuous as vol
from homeassistant.const import CONF_DOMAIN, CONF_PASSWORD, CONF_TIMEOUT, CONF_USERNAME
@ -69,7 +68,7 @@ async def _update_google_domains(hass, session, domain, user, password, timeout)
params = {"hostname": domain}
try:
async with async_timeout.timeout(timeout):
async with asyncio.timeout(timeout):
resp = await session.get(url, params=params)
body = await resp.text()

View File

@ -1,7 +1,6 @@
"""Config flow for HLK-SW16."""
import asyncio
import async_timeout
from hlk_sw16 import create_hlk_sw16_connection
import voluptuous as vol
@ -36,7 +35,7 @@ async def connect_client(hass, user_input):
reconnect_interval=DEFAULT_RECONNECT_INTERVAL,
keep_alive_interval=DEFAULT_KEEP_ALIVE_INTERVAL,
)
async with async_timeout.timeout(CONNECTION_TIMEOUT):
async with asyncio.timeout(CONNECTION_TIMEOUT):
return await client_aw

View File

@ -1,8 +1,8 @@
"""The Legrand Home+ Control integration."""
import asyncio
from datetime import timedelta
import logging
import async_timeout
from homepluscontrol.homeplusapi import HomePlusControlApiError
import voluptuous as vol
@ -100,7 +100,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
try:
# Note: asyncio.TimeoutError and aiohttp.ClientError are already
# handled by the data update coordinator.
async with async_timeout.timeout(10):
async with asyncio.timeout(10):
return await api.async_get_modules()
except HomePlusControlApiError as err:
raise UpdateFailed(

View File

@ -1,11 +1,11 @@
"""Config flow for the Home Assistant Yellow integration."""
from __future__ import annotations
import asyncio
import logging
from typing import Any
import aiohttp
import async_timeout
import voluptuous as vol
from homeassistant.components.hassio import (
@ -80,7 +80,7 @@ class HomeAssistantYellowOptionsFlow(silabs_multiprotocol_addon.OptionsFlowHandl
if self._hw_settings == user_input:
return self.async_create_entry(data={})
try:
async with async_timeout.timeout(10):
async with asyncio.timeout(10):
await async_set_yellow_settings(self.hass, user_input)
except (aiohttp.ClientError, TimeoutError, HassioAPIError) as err:
_LOGGER.warning("Failed to write hardware settings", exc_info=err)
@ -88,7 +88,7 @@ class HomeAssistantYellowOptionsFlow(silabs_multiprotocol_addon.OptionsFlowHandl
return await self.async_step_confirm_reboot()
try:
async with async_timeout.timeout(10):
async with asyncio.timeout(10):
self._hw_settings: dict[str, bool] = await async_get_yellow_settings(
self.hass
)

View File

@ -10,7 +10,6 @@ import aiohttp
from aiohttp import client_exceptions
from aiohue import HueBridgeV1, HueBridgeV2, LinkButtonNotPressed, Unauthorized
from aiohue.errors import AiohueException, BridgeBusy
import async_timeout
from homeassistant import core
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
@ -73,7 +72,7 @@ class HueBridge:
async def async_initialize_bridge(self) -> bool:
"""Initialize Connection with the Hue API."""
try:
async with async_timeout.timeout(10):
async with asyncio.timeout(10):
await self.api.initialize()
except (LinkButtonNotPressed, Unauthorized):

View File

@ -9,7 +9,6 @@ import aiohttp
from aiohue import LinkButtonNotPressed, create_app_key
from aiohue.discovery import DiscoveredHueBridge, discover_bridge, discover_nupnp
from aiohue.util import normalize_bridge_id
import async_timeout
import slugify as unicode_slug
import voluptuous as vol
@ -110,7 +109,7 @@ class HueFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
# Find / discover bridges
try:
async with async_timeout.timeout(5):
async with asyncio.timeout(5):
bridges = await discover_nupnp(
websession=aiohttp_client.async_get_clientsession(self.hass)
)

View File

@ -1,13 +1,13 @@
"""Support for the Philips Hue lights."""
from __future__ import annotations
import asyncio
from datetime import timedelta
from functools import partial
import logging
import random
import aiohue
import async_timeout
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
@ -262,7 +262,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
async def async_safe_fetch(bridge, fetch_method):
"""Safely fetch data."""
try:
async with async_timeout.timeout(4):
async with asyncio.timeout(4):
return await bridge.async_request_call(fetch_method)
except aiohue.Unauthorized as err:
await bridge.handle_unauthorized_error()

View File

@ -1,13 +1,13 @@
"""Support for the Philips Hue sensors as a platform."""
from __future__ import annotations
import asyncio
from datetime import timedelta
import logging
from typing import Any
from aiohue import AiohueException, Unauthorized
from aiohue.v1.sensors import TYPE_ZLL_PRESENCE
import async_timeout
from homeassistant.components.sensor import SensorStateClass
from homeassistant.core import callback
@ -61,7 +61,7 @@ class SensorManager:
async def async_update_data(self):
"""Update sensor data."""
try:
async with async_timeout.timeout(4):
async with asyncio.timeout(4):
return await self.bridge.async_request_call(
self.bridge.api.sensors.update
)

View File

@ -1,9 +1,9 @@
"""The Huisbaasje integration."""
import asyncio
from datetime import timedelta
import logging
from typing import Any
import async_timeout
from energyflip import EnergyFlip, EnergyFlipException
from homeassistant.config_entries import ConfigEntry
@ -86,7 +86,7 @@ async def async_update_huisbaasje(energyflip: EnergyFlip) -> dict[str, dict[str,
try:
# Note: asyncio.TimeoutError and aiohttp.ClientError are already
# handled by the data update coordinator.
async with async_timeout.timeout(FETCH_TIMEOUT):
async with asyncio.timeout(FETCH_TIMEOUT):
if not energyflip.is_authenticated():
_LOGGER.warning("Huisbaasje is unauthenticated. Reauthenticating")
await energyflip.authenticate()

View File

@ -1,4 +1,5 @@
"""The Hunter Douglas PowerView integration."""
import asyncio
import logging
from aiopvapi.helpers.aiorequest import AioRequest
@ -8,7 +9,6 @@ from aiopvapi.rooms import Rooms
from aiopvapi.scenes import Scenes
from aiopvapi.shades import Shades
from aiopvapi.userdata import UserData
import async_timeout
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_HOST, Platform
@ -63,20 +63,20 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
pv_request = AioRequest(hub_address, loop=hass.loop, websession=websession)
try:
async with async_timeout.timeout(10):
async with asyncio.timeout(10):
device_info = await async_get_device_info(pv_request, hub_address)
async with async_timeout.timeout(10):
async with asyncio.timeout(10):
rooms = Rooms(pv_request)
room_data = async_map_data_by_id((await rooms.get_resources())[ROOM_DATA])
async with async_timeout.timeout(10):
async with asyncio.timeout(10):
scenes = Scenes(pv_request)
scene_data = async_map_data_by_id(
(await scenes.get_resources())[SCENE_DATA]
)
async with async_timeout.timeout(10):
async with asyncio.timeout(10):
shades = Shades(pv_request)
shade_entries = await shades.get_resources()
shade_data = async_map_data_by_id(shade_entries[SHADE_DATA])

View File

@ -1,10 +1,10 @@
"""Config flow for Hunter Douglas PowerView integration."""
from __future__ import annotations
import asyncio
import logging
from aiopvapi.helpers.aiorequest import AioRequest
import async_timeout
import voluptuous as vol
from homeassistant import config_entries, core, exceptions
@ -34,7 +34,7 @@ async def validate_input(hass: core.HomeAssistant, hub_address: str) -> dict[str
pv_request = AioRequest(hub_address, loop=hass.loop, websession=websession)
try:
async with async_timeout.timeout(10):
async with asyncio.timeout(10):
device_info = await async_get_device_info(pv_request, hub_address)
except HUB_EXCEPTIONS as err:
raise CannotConnect from err

View File

@ -1,11 +1,11 @@
"""Coordinate data for powerview devices."""
from __future__ import annotations
import asyncio
from datetime import timedelta
import logging
from aiopvapi.shades import Shades
import async_timeout
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
@ -37,7 +37,7 @@ class PowerviewShadeUpdateCoordinator(DataUpdateCoordinator[PowerviewShadeData])
async def _async_update_data(self) -> PowerviewShadeData:
"""Fetch data from shade endpoint."""
async with async_timeout.timeout(10):
async with asyncio.timeout(10):
shade_entries = await self.shades.get_resources()
if isinstance(shade_entries, bool):

View File

@ -19,7 +19,6 @@ from aiopvapi.helpers.constants import (
MIN_POSITION,
)
from aiopvapi.resources.shade import BaseShade, factory as PvShade
import async_timeout
from homeassistant.components.cover import (
ATTR_POSITION,
@ -84,7 +83,7 @@ async def async_setup_entry(
shade: BaseShade = PvShade(raw_shade, pv_entry.api)
name_before_refresh = shade.name
with suppress(asyncio.TimeoutError):
async with async_timeout.timeout(1):
async with asyncio.timeout(1):
await shade.refresh()
if ATTR_POSITION_DATA not in shade.raw_data:

View File

@ -1,12 +1,12 @@
"""Binary sensor platform for hvv_departures."""
from __future__ import annotations
import asyncio
from datetime import timedelta
import logging
from typing import Any
from aiohttp import ClientConnectorError
import async_timeout
from pygti.exceptions import InvalidAuth
from homeassistant.components.binary_sensor import (
@ -90,7 +90,7 @@ async def async_setup_entry(
payload = {"station": {"id": station["id"], "type": station["type"]}}
try:
async with async_timeout.timeout(10):
async with asyncio.timeout(10):
return get_elevator_entities_from_station_information(
station_name, await hub.gti.stationInformation(payload)
)