Use asyncio.timeout [b-e] (#98448)

This commit is contained in:
Marc Mueller 2023-08-15 15:30:20 +02:00 committed by GitHub
parent 346a7292d7
commit e2d2ec8817
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
26 changed files with 53 additions and 71 deletions

View file

@ -1,9 +1,9 @@
"""Websocket API for blueprint."""
from __future__ import annotations
import asyncio
from typing import Any, cast
import async_timeout
import voluptuous as vol
from homeassistant.components import websocket_api
@ -72,7 +72,7 @@ async def ws_import_blueprint(
msg: dict[str, Any],
) -> None:
"""Import a blueprint."""
async with async_timeout.timeout(10):
async with asyncio.timeout(10):
imported_blueprint = await importer.fetch_blueprint_from_url(hass, msg["url"])
if imported_blueprint is None:

View file

@ -1,11 +1,11 @@
"""Provides the Canary DataUpdateCoordinator."""
from __future__ import annotations
import asyncio
from collections.abc import ValuesView
from datetime import timedelta
import logging
from async_timeout import timeout
from canary.api import Api
from canary.model import Location, Reading
from requests.exceptions import ConnectTimeout, HTTPError
@ -58,7 +58,7 @@ class CanaryDataUpdateCoordinator(DataUpdateCoordinator[CanaryData]):
"""Fetch data from Canary."""
try:
async with timeout(15):
async with asyncio.timeout(15):
return await self.hass.async_add_executor_job(self._update_data)
except (ConnectTimeout, HTTPError) as error:
raise UpdateFailed(f"Invalid response from API: {error}") from error

View file

@ -6,7 +6,6 @@ from datetime import timedelta
import logging
import aiohttp
import async_timeout
import voluptuous as vol
from homeassistant.components.sensor import (
@ -140,7 +139,7 @@ async def async_citybikes_request(hass, uri, schema):
try:
session = async_get_clientsession(hass)
async with async_timeout.timeout(REQUEST_TIMEOUT):
async with asyncio.timeout(REQUEST_TIMEOUT):
req = await session.get(DEFAULT_ENDPOINT.format(uri=uri))
json_response = await req.json()

View file

@ -4,7 +4,6 @@ import io
import logging
import aiohttp
import async_timeout
from colorthief import ColorThief
from PIL import UnidentifiedImageError
import voluptuous as vol
@ -120,7 +119,7 @@ async def async_setup(hass: HomeAssistant, hass_config: ConfigType) -> bool:
try:
session = aiohttp_client.async_get_clientsession(hass)
async with async_timeout.timeout(10):
async with asyncio.timeout(10):
response = await session.get(url)
except (asyncio.TimeoutError, aiohttp.ClientError) as err:

View file

@ -7,7 +7,6 @@ import json
import logging
import aiohttp
import async_timeout
import voluptuous as vol
from homeassistant.components.sensor import (
@ -112,7 +111,7 @@ class ComedHourlyPricingSensor(SensorEntity):
else:
url_string += "?type=currenthouraverage"
async with async_timeout.timeout(60):
async with asyncio.timeout(60):
response = await self.websession.get(url_string)
# The API responds with MIME type 'text/html'
text = await response.text()

View file

@ -4,7 +4,6 @@ from datetime import timedelta
import logging
from aiohttp import ClientConnectionError
from async_timeout import timeout
from pydaikin.daikin_base import Appliance
from homeassistant.config_entries import ConfigEntry
@ -74,7 +73,7 @@ async def daikin_api_setup(hass: HomeAssistant, host, key, uuid, password):
session = async_get_clientsession(hass)
try:
async with timeout(TIMEOUT):
async with asyncio.timeout(TIMEOUT):
device = await Appliance.factory(
host, session, key=key, uuid=uuid, password=password
)

View file

@ -4,7 +4,6 @@ import logging
from uuid import uuid4
from aiohttp import ClientError, web_exceptions
from async_timeout import timeout
from pydaikin.daikin_base import Appliance, DaikinException
from pydaikin.discovery import Discovery
import voluptuous as vol
@ -70,7 +69,7 @@ class FlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
password = None
try:
async with timeout(TIMEOUT):
async with asyncio.timeout(TIMEOUT):
device = await Appliance.factory(
host,
async_get_clientsession(self.hass),

View file

@ -9,7 +9,6 @@ from pprint import pformat
from typing import Any, cast
from urllib.parse import urlparse
import async_timeout
from pydeconz.errors import LinkButtonNotPressed, RequestError, ResponseError
from pydeconz.gateway import DeconzSession
from pydeconz.utils import (
@ -101,7 +100,7 @@ class DeconzFlowHandler(ConfigFlow, domain=DOMAIN):
session = aiohttp_client.async_get_clientsession(self.hass)
try:
async with async_timeout.timeout(10):
async with asyncio.timeout(10):
self.bridges = await deconz_discovery(session)
except (asyncio.TimeoutError, ResponseError):
@ -159,7 +158,7 @@ class DeconzFlowHandler(ConfigFlow, domain=DOMAIN):
deconz_session = DeconzSession(session, self.host, self.port)
try:
async with async_timeout.timeout(10):
async with asyncio.timeout(10):
api_key = await deconz_session.get_api_key()
except LinkButtonNotPressed:
@ -180,7 +179,7 @@ class DeconzFlowHandler(ConfigFlow, domain=DOMAIN):
session = aiohttp_client.async_get_clientsession(self.hass)
try:
async with async_timeout.timeout(10):
async with asyncio.timeout(10):
self.bridge_id = await deconz_get_bridge_id(
session, self.host, self.port, self.api_key
)

View file

@ -7,7 +7,6 @@ from collections.abc import Callable
from types import MappingProxyType
from typing import TYPE_CHECKING, Any, cast
import async_timeout
from pydeconz import DeconzSession, errors
from pydeconz.interfaces import sensors
from pydeconz.interfaces.api_handlers import APIHandler, GroupedAPIHandler
@ -353,7 +352,7 @@ async def get_deconz_session(
config[CONF_API_KEY],
)
try:
async with async_timeout.timeout(10):
async with asyncio.timeout(10):
await deconz_session.refresh_state()
return deconz_session

View file

@ -1,10 +1,10 @@
"""The devolo Home Network integration."""
from __future__ import annotations
import asyncio
import logging
from typing import Any
import async_timeout
from devolo_plc_api import Device
from devolo_plc_api.device_api import (
ConnectedStationInfo,
@ -70,7 +70,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Fetch data from API endpoint."""
assert device.plcnet
try:
async with async_timeout.timeout(10):
async with asyncio.timeout(10):
return await device.plcnet.async_get_network_overview()
except DeviceUnavailable as err:
raise UpdateFailed(err) from err
@ -79,7 +79,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Fetch data from API endpoint."""
assert device.device
try:
async with async_timeout.timeout(10):
async with asyncio.timeout(10):
return await device.device.async_get_wifi_guest_access()
except DeviceUnavailable as err:
raise UpdateFailed(err) from err
@ -90,7 +90,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Fetch data from API endpoint."""
assert device.device
try:
async with async_timeout.timeout(10):
async with asyncio.timeout(10):
return await device.device.async_get_led_setting()
except DeviceUnavailable as err:
raise UpdateFailed(err) from err
@ -99,7 +99,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Fetch data from API endpoint."""
assert device.device
try:
async with async_timeout.timeout(10):
async with asyncio.timeout(10):
return await device.device.async_get_wifi_connected_station()
except DeviceUnavailable as err:
raise UpdateFailed(err) from err
@ -108,7 +108,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Fetch data from API endpoint."""
assert device.device
try:
async with async_timeout.timeout(30):
async with asyncio.timeout(30):
return await device.device.async_get_wifi_neighbor_access_points()
except DeviceUnavailable as err:
raise UpdateFailed(err) from err

View file

@ -6,7 +6,6 @@ import datetime
import logging
import aiohttp
import async_timeout
from homeassistant.components.camera import Camera, CameraEntityFeature
from homeassistant.config_entries import ConfigEntry
@ -118,7 +117,7 @@ class DoorBirdCamera(DoorBirdEntity, Camera):
try:
websession = async_get_clientsession(self.hass)
async with async_timeout.timeout(_TIMEOUT):
async with asyncio.timeout(_TIMEOUT):
response = await websession.get(self._url)
self._last_image = await response.read()

View file

@ -6,7 +6,6 @@ from functools import partial
import os
from typing import Any
from async_timeout import timeout
from dsmr_parser import obis_references as obis_ref
from dsmr_parser.clients.protocol import create_dsmr_reader, create_tcp_dsmr_reader
from dsmr_parser.clients.rfxtrx_protocol import (
@ -121,7 +120,7 @@ class DSMRConnection:
if transport:
try:
async with timeout(30):
async with asyncio.timeout(30):
await protocol.wait_closed()
except asyncio.TimeoutError:
# Timeout (no data received), close transport and return True (if telegram is empty, will result in CannotCommunicate error)

View file

@ -1,9 +1,9 @@
"""Support for gauges from flood monitoring API."""
import asyncio
from datetime import timedelta
import logging
from aioeafm import get_station
import async_timeout
from homeassistant.components.sensor import SensorEntity, SensorStateClass
from homeassistant.config_entries import ConfigEntry
@ -48,7 +48,7 @@ async def async_setup_entry(
async def async_update_data():
# DataUpdateCoordinator will handle aiohttp ClientErrors and timeouts
async with async_timeout.timeout(30):
async with asyncio.timeout(30):
data = await get_station(session, station_key)
measures = get_measures(data)

View file

@ -1,9 +1,9 @@
"""Electric Kiwi coordinators."""
import asyncio
from collections import OrderedDict
from datetime import timedelta
import logging
import async_timeout
from electrickiwi_api import ElectricKiwiApi
from electrickiwi_api.exceptions import ApiException, AuthException
from electrickiwi_api.model import Hop, HopIntervals
@ -61,7 +61,7 @@ class ElectricKiwiHOPDataCoordinator(DataUpdateCoordinator[Hop]):
filters the intervals to remove ones that are not active
"""
try:
async with async_timeout.timeout(60):
async with asyncio.timeout(60):
if self.hop_intervals is None:
hop_intervals: HopIntervals = await self._ek_api.get_hop_intervals()
hop_intervals.intervals = OrderedDict(

View file

@ -8,7 +8,6 @@ import re
from types import MappingProxyType
from typing import Any, cast
import async_timeout
from elkm1_lib.elements import Element
from elkm1_lib.elk import Elk
from elkm1_lib.util import parse_url
@ -382,7 +381,7 @@ async def async_wait_for_elk_to_sync(
):
_LOGGER.debug("Waiting for %s event for %s seconds", name, timeout)
try:
async with async_timeout.timeout(timeout):
async with asyncio.timeout(timeout):
await event.wait()
except asyncio.TimeoutError:
_LOGGER.debug("Timed out waiting for %s event", name)

View file

@ -1,11 +1,11 @@
"""Elmax integration common classes and utilities."""
from __future__ import annotations
import asyncio
from datetime import timedelta
import logging
from logging import Logger
import async_timeout
from elmax_api.exceptions import (
ElmaxApiError,
ElmaxBadLoginError,
@ -94,7 +94,7 @@ class ElmaxCoordinator(DataUpdateCoordinator[PanelStatus]):
async def _async_update_data(self):
try:
async with async_timeout.timeout(DEFAULT_TIMEOUT):
async with asyncio.timeout(DEFAULT_TIMEOUT):
# Retrieve the panel online status first
panels = await self._client.list_control_panels()
panel = next(

View file

@ -11,7 +11,6 @@ import time
from typing import Any
from aiohttp import web
import async_timeout
from homeassistant import core
from homeassistant.components import (
@ -898,7 +897,7 @@ async def wait_for_state_change_or_timeout(
unsub = async_track_state_change_event(hass, [entity_id], _async_event_changed)
try:
async with async_timeout.timeout(STATE_CHANGE_WAIT_TIMEOUT):
async with asyncio.timeout(STATE_CHANGE_WAIT_TIMEOUT):
await ev.wait()
except asyncio.TimeoutError:
pass

View file

@ -3,8 +3,6 @@ import asyncio
from contextlib import suppress
import logging
from async_timeout import timeout
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_entry_flow
from homeassistant.helpers.dispatcher import async_dispatcher_connect
@ -34,7 +32,7 @@ async def _async_has_devices(hass: HomeAssistant) -> bool:
discovery_service = await async_start_discovery_service(hass)
with suppress(asyncio.TimeoutError):
async with timeout(TIMEOUT_DISCOVERY):
async with asyncio.timeout(TIMEOUT_DISCOVERY):
await controller_ready.wait()
remove_handler()

View file

@ -22,7 +22,6 @@ from aioesphomeapi import (
from aioesphomeapi.connection import APIConnectionError, TimeoutAPIError
from aioesphomeapi.core import BluetoothGATTAPIError
from async_interrupt import interrupt
import async_timeout
from bleak.backends.characteristic import BleakGATTCharacteristic
from bleak.backends.client import BaseBleakClient, NotifyCallback
from bleak.backends.device import BLEDevice
@ -402,7 +401,7 @@ class ESPHomeClient(BaseBleakClient):
self._ble_device.name,
self._ble_device.address,
)
async with async_timeout.timeout(timeout):
async with asyncio.timeout(timeout):
await bluetooth_device.wait_for_ble_connections_free()
@property

View file

@ -9,7 +9,6 @@ import socket
from typing import cast
from aioesphomeapi import VoiceAssistantEventType
import async_timeout
from homeassistant.components import stt, tts
from homeassistant.components.assist_pipeline import (
@ -210,7 +209,7 @@ class VoiceAssistantUDPServer(asyncio.DatagramProtocol):
Returns False if the connection was stopped gracefully (b"" put onto the queue).
"""
# Timeout if no audio comes in for a while.
async with async_timeout.timeout(self.audio_timeout):
async with asyncio.timeout(self.audio_timeout):
chunk = await self.queue.get()
while chunk:
@ -220,7 +219,7 @@ class VoiceAssistantUDPServer(asyncio.DatagramProtocol):
if segmenter.in_command:
return True
async with async_timeout.timeout(self.audio_timeout):
async with asyncio.timeout(self.audio_timeout):
chunk = await self.queue.get()
# If chunk is falsey, `stop()` was called
@ -240,7 +239,7 @@ class VoiceAssistantUDPServer(asyncio.DatagramProtocol):
yield buffered_chunk
# Timeout if no audio comes in for a while.
async with async_timeout.timeout(self.audio_timeout):
async with asyncio.timeout(self.audio_timeout):
chunk = await self.queue.get()
while chunk:
@ -250,7 +249,7 @@ class VoiceAssistantUDPServer(asyncio.DatagramProtocol):
yield chunk
async with async_timeout.timeout(self.audio_timeout):
async with asyncio.timeout(self.audio_timeout):
chunk = await self.queue.get()
async def _iterate_packets_with_vad(
@ -259,7 +258,7 @@ class VoiceAssistantUDPServer(asyncio.DatagramProtocol):
segmenter = VoiceCommandSegmenter(silence_seconds=silence_seconds)
chunk_buffer: deque[bytes] = deque(maxlen=100)
try:
async with async_timeout.timeout(pipeline_timeout):
async with asyncio.timeout(pipeline_timeout):
speech_detected = await self._wait_for_speech(segmenter, chunk_buffer)
if not speech_detected:
_LOGGER.debug(
@ -326,7 +325,7 @@ class VoiceAssistantUDPServer(asyncio.DatagramProtocol):
_LOGGER.debug("Starting pipeline")
try:
async with async_timeout.timeout(pipeline_timeout):
async with asyncio.timeout(pipeline_timeout):
await async_pipeline_from_audio_stream(
self.hass,
context=self.context,

View file

@ -1,12 +1,12 @@
"""The Evil Genius Labs integration."""
from __future__ import annotations
import asyncio
from datetime import timedelta
import logging
from typing import cast
from aiohttp import ContentTypeError
from async_timeout import timeout
import pyevilgenius
from homeassistant.config_entries import ConfigEntry
@ -85,18 +85,18 @@ class EvilGeniusUpdateCoordinator(DataUpdateCoordinator[dict]):
async def _async_update_data(self) -> dict:
"""Update Evil Genius data."""
if not hasattr(self, "info"):
async with timeout(5):
async with asyncio.timeout(5):
self.info = await self.client.get_info()
if not hasattr(self, "product"):
async with timeout(5):
async with asyncio.timeout(5):
try:
self.product = await self.client.get_product()
except ContentTypeError:
# Older versions of the API don't support this
self.product = None
async with timeout(5):
async with asyncio.timeout(5):
return cast(dict, await self.client.get_all())

View file

@ -6,7 +6,6 @@ import logging
from typing import Any
import aiohttp
import async_timeout
import pyevilgenius
import voluptuous as vol
@ -31,7 +30,7 @@ async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str,
)
try:
async with async_timeout.timeout(10):
async with asyncio.timeout(10):
data = await hub.get_all()
info = await hub.get_info()
except aiohttp.ClientError as err:

View file

@ -1,10 +1,9 @@
"""Light platform for Evil Genius Light."""
from __future__ import annotations
import asyncio
from typing import Any, cast
from async_timeout import timeout
from homeassistant.components import light
from homeassistant.components.light import ColorMode, LightEntity, LightEntityFeature
from homeassistant.config_entries import ConfigEntry
@ -89,27 +88,27 @@ class EvilGeniusLight(EvilGeniusEntity, LightEntity):
) -> None:
"""Turn light on."""
if (brightness := kwargs.get(light.ATTR_BRIGHTNESS)) is not None:
async with timeout(5):
async with asyncio.timeout(5):
await self.coordinator.client.set_path_value("brightness", brightness)
# Setting a color will change the effect to "Solid Color" so skip setting effect
if (rgb_color := kwargs.get(light.ATTR_RGB_COLOR)) is not None:
async with timeout(5):
async with asyncio.timeout(5):
await self.coordinator.client.set_rgb_color(*rgb_color)
elif (effect := kwargs.get(light.ATTR_EFFECT)) is not None:
if effect == HA_NO_EFFECT:
effect = FIB_NO_EFFECT
async with timeout(5):
async with asyncio.timeout(5):
await self.coordinator.client.set_path_value(
"pattern", self.coordinator.data["pattern"]["options"].index(effect)
)
async with timeout(5):
async with asyncio.timeout(5):
await self.coordinator.client.set_path_value("power", 1)
@update_when_done
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn light off."""
async with timeout(5):
async with asyncio.timeout(5):
await self.coordinator.client.set_path_value("power", 0)

View file

@ -1,8 +1,8 @@
"""Provides the ezviz DataUpdateCoordinator."""
import asyncio
from datetime import timedelta
import logging
from async_timeout import timeout
from pyezviz.client import EzvizClient
from pyezviz.exceptions import (
EzvizAuthTokenExpired,
@ -37,7 +37,7 @@ class EzvizDataUpdateCoordinator(DataUpdateCoordinator):
async def _async_update_data(self) -> dict:
"""Fetch data from EZVIZ."""
try:
async with timeout(self._api_timeout):
async with asyncio.timeout(self._api_timeout):
return await self.hass.async_add_executor_job(
self.ezviz_client.load_cameras
)

View file

@ -1,6 +1,7 @@
"""esphome session fixtures."""
from __future__ import annotations
import asyncio
from asyncio import Event
from collections.abc import Awaitable, Callable
from typing import Any
@ -15,7 +16,6 @@ from aioesphomeapi import (
ReconnectLogic,
UserService,
)
import async_timeout
import pytest
from zeroconf import Zeroconf
@ -252,7 +252,7 @@ async def _mock_generic_device_entry(
"homeassistant.components.esphome.manager.ReconnectLogic", MockReconnectLogic
):
assert await hass.config_entries.async_setup(entry.entry_id)
async with async_timeout.timeout(2):
async with asyncio.timeout(2):
await try_connect_done.wait()
await hass.async_block_till_done()

View file

@ -5,7 +5,6 @@ import socket
from unittest.mock import Mock, patch
from aioesphomeapi import VoiceAssistantEventType
import async_timeout
import pytest
from homeassistant.components.assist_pipeline import PipelineEvent, PipelineEventType
@ -148,7 +147,7 @@ async def test_udp_server(
sock.sendto(b"test", ("127.0.0.1", port))
# Give the socket some time to send/receive the data
async with async_timeout.timeout(1):
async with asyncio.timeout(1):
while voice_assistant_udp_server_v1.queue.qsize() == 0:
await asyncio.sleep(0.1)