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

View file

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

View file

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

View file

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

View file

@ -7,7 +7,6 @@ import json
import logging import logging
import aiohttp import aiohttp
import async_timeout
import voluptuous as vol import voluptuous as vol
from homeassistant.components.sensor import ( from homeassistant.components.sensor import (
@ -112,7 +111,7 @@ class ComedHourlyPricingSensor(SensorEntity):
else: else:
url_string += "?type=currenthouraverage" url_string += "?type=currenthouraverage"
async with async_timeout.timeout(60): async with asyncio.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

@ -4,7 +4,6 @@ from datetime import timedelta
import logging import logging
from aiohttp import ClientConnectionError from aiohttp import ClientConnectionError
from async_timeout import timeout
from pydaikin.daikin_base import Appliance from pydaikin.daikin_base import Appliance
from homeassistant.config_entries import ConfigEntry 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) session = async_get_clientsession(hass)
try: try:
async with timeout(TIMEOUT): async with asyncio.timeout(TIMEOUT):
device = await Appliance.factory( device = await Appliance.factory(
host, session, key=key, uuid=uuid, password=password host, session, key=key, uuid=uuid, password=password
) )

View file

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

View file

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

View file

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

View file

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

View file

@ -6,7 +6,6 @@ import datetime
import logging import logging
import aiohttp import aiohttp
import async_timeout
from homeassistant.components.camera import Camera, CameraEntityFeature from homeassistant.components.camera import Camera, CameraEntityFeature
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
@ -118,7 +117,7 @@ class DoorBirdCamera(DoorBirdEntity, Camera):
try: try:
websession = async_get_clientsession(self.hass) websession = async_get_clientsession(self.hass)
async with async_timeout.timeout(_TIMEOUT): async with asyncio.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

@ -6,7 +6,6 @@ from functools import partial
import os import os
from typing import Any from typing import Any
from async_timeout import timeout
from dsmr_parser import obis_references as obis_ref 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.protocol import create_dsmr_reader, create_tcp_dsmr_reader
from dsmr_parser.clients.rfxtrx_protocol import ( from dsmr_parser.clients.rfxtrx_protocol import (
@ -121,7 +120,7 @@ class DSMRConnection:
if transport: if transport:
try: try:
async with timeout(30): async with asyncio.timeout(30):
await protocol.wait_closed() await protocol.wait_closed()
except asyncio.TimeoutError: except asyncio.TimeoutError:
# Timeout (no data received), close transport and return True (if telegram is empty, will result in CannotCommunicate error) # 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.""" """Support for gauges from flood monitoring API."""
import asyncio
from datetime import timedelta from datetime import timedelta
import logging import logging
from aioeafm import get_station from aioeafm import get_station
import async_timeout
from homeassistant.components.sensor import SensorEntity, SensorStateClass from homeassistant.components.sensor import SensorEntity, SensorStateClass
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
@ -48,7 +48,7 @@ async def async_setup_entry(
async def async_update_data(): async def async_update_data():
# DataUpdateCoordinator will handle aiohttp ClientErrors and timeouts # 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) data = await get_station(session, station_key)
measures = get_measures(data) measures = get_measures(data)

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -5,7 +5,6 @@ import socket
from unittest.mock import Mock, patch from unittest.mock import Mock, patch
from aioesphomeapi import VoiceAssistantEventType from aioesphomeapi import VoiceAssistantEventType
import async_timeout
import pytest import pytest
from homeassistant.components.assist_pipeline import PipelineEvent, PipelineEventType 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)) sock.sendto(b"test", ("127.0.0.1", port))
# Give the socket some time to send/receive the data # 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: while voice_assistant_udp_server_v1.queue.qsize() == 0:
await asyncio.sleep(0.1) await asyncio.sleep(0.1)