Use asyncio.timeout [o-s] (#98451)

This commit is contained in:
Marc Mueller 2023-08-15 17:21:49 +02:00 committed by GitHub
parent 496a975c58
commit 063ce9159d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
41 changed files with 70 additions and 92 deletions

View File

@ -7,7 +7,6 @@ from http import HTTPStatus
import logging import logging
import aiohttp import aiohttp
import async_timeout
import voluptuous as vol import voluptuous as vol
from homeassistant.components.image_processing import ( from homeassistant.components.image_processing import (
@ -199,7 +198,7 @@ class OpenAlprCloudEntity(ImageProcessingAlprEntity):
body = {"image_bytes": str(b64encode(image), "utf-8")} body = {"image_bytes": str(b64encode(image), "utf-8")}
try: try:
async with async_timeout.timeout(self.timeout): async with asyncio.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

@ -10,7 +10,6 @@ from aioopenexchangerates import (
OpenExchangeRatesAuthError, OpenExchangeRatesAuthError,
OpenExchangeRatesClientError, OpenExchangeRatesClientError,
) )
import async_timeout
import voluptuous as vol import voluptuous as vol
from homeassistant import config_entries from homeassistant import config_entries
@ -40,7 +39,7 @@ async def validate_input(hass: HomeAssistant, data: dict[str, str]) -> dict[str,
"""Validate the user input allows us to connect.""" """Validate the user input allows us to connect."""
client = Client(data[CONF_API_KEY], async_get_clientsession(hass)) client = Client(data[CONF_API_KEY], async_get_clientsession(hass))
async with async_timeout.timeout(CLIENT_TIMEOUT): async with asyncio.timeout(CLIENT_TIMEOUT):
await client.get_latest(base=data[CONF_BASE]) await client.get_latest(base=data[CONF_BASE])
return {"title": data[CONF_BASE]} return {"title": data[CONF_BASE]}
@ -119,7 +118,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
if not self.currencies: if not self.currencies:
client = Client("dummy-api-key", async_get_clientsession(self.hass)) client = Client("dummy-api-key", async_get_clientsession(self.hass))
try: try:
async with async_timeout.timeout(CLIENT_TIMEOUT): async with asyncio.timeout(CLIENT_TIMEOUT):
self.currencies = await client.get_currencies() self.currencies = await client.get_currencies()
except OpenExchangeRatesClientError as err: except OpenExchangeRatesClientError as err:
raise AbortFlow("cannot_connect") from err raise AbortFlow("cannot_connect") from err

View File

@ -1,6 +1,7 @@
"""Provide an OpenExchangeRates data coordinator.""" """Provide an OpenExchangeRates data coordinator."""
from __future__ import annotations from __future__ import annotations
import asyncio
from datetime import timedelta from datetime import timedelta
from aiohttp import ClientSession from aiohttp import ClientSession
@ -10,7 +11,6 @@ from aioopenexchangerates import (
OpenExchangeRatesAuthError, OpenExchangeRatesAuthError,
OpenExchangeRatesClientError, OpenExchangeRatesClientError,
) )
import async_timeout
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed from homeassistant.exceptions import ConfigEntryAuthFailed
@ -40,7 +40,7 @@ class OpenexchangeratesCoordinator(DataUpdateCoordinator[Latest]):
async def _async_update_data(self) -> Latest: async def _async_update_data(self) -> Latest:
"""Update data from Open Exchange Rates.""" """Update data from Open Exchange Rates."""
try: try:
async with async_timeout.timeout(CLIENT_TIMEOUT): async with asyncio.timeout(CLIENT_TIMEOUT):
latest = await self.client.get_latest(base=self.base) latest = await self.client.get_latest(base=self.base)
except OpenExchangeRatesAuthError as err: except OpenExchangeRatesAuthError as err:
raise ConfigEntryAuthFailed(err) from err raise ConfigEntryAuthFailed(err) from err

View File

@ -3,7 +3,6 @@ import asyncio
from datetime import date, datetime from datetime import date, datetime
import logging import logging
import async_timeout
import pyotgw import pyotgw
import pyotgw.vars as gw_vars import pyotgw.vars as gw_vars
from serial import SerialException from serial import SerialException
@ -113,7 +112,7 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
config_entry.add_update_listener(options_updated) config_entry.add_update_listener(options_updated)
try: try:
async with async_timeout.timeout(CONNECTION_TIMEOUT): async with asyncio.timeout(CONNECTION_TIMEOUT):
await gateway.connect_and_subscribe() await gateway.connect_and_subscribe()
except (asyncio.TimeoutError, ConnectionError, SerialException) as ex: except (asyncio.TimeoutError, ConnectionError, SerialException) as ex:
await gateway.cleanup() await gateway.cleanup()

View File

@ -3,7 +3,6 @@ from __future__ import annotations
import asyncio import asyncio
import async_timeout
import pyotgw import pyotgw
from pyotgw import vars as gw_vars from pyotgw import vars as gw_vars
from serial import SerialException from serial import SerialException
@ -69,7 +68,7 @@ class OpenThermGwConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
return status[gw_vars.OTGW].get(gw_vars.OTGW_ABOUT) return status[gw_vars.OTGW].get(gw_vars.OTGW_ABOUT)
try: try:
async with async_timeout.timeout(CONNECTION_TIMEOUT): async with asyncio.timeout(CONNECTION_TIMEOUT):
await test_connection() await test_connection()
except asyncio.TimeoutError: except asyncio.TimeoutError:
return self._show_form({"base": "timeout_connect"}) return self._show_form({"base": "timeout_connect"})

View File

@ -1,8 +1,8 @@
"""Weather data coordinator for the OpenWeatherMap (OWM) service.""" """Weather data coordinator for the OpenWeatherMap (OWM) service."""
import asyncio
from datetime import timedelta from datetime import timedelta
import logging import logging
import async_timeout
from pyowm.commons.exceptions import APIRequestError, UnauthorizedError from pyowm.commons.exceptions import APIRequestError, UnauthorizedError
from homeassistant.components.weather import ( from homeassistant.components.weather import (
@ -80,7 +80,7 @@ class WeatherUpdateCoordinator(DataUpdateCoordinator):
async def _async_update_data(self): async def _async_update_data(self):
"""Update the data.""" """Update the data."""
data = {} data = {}
async with async_timeout.timeout(20): async with asyncio.timeout(20):
try: try:
weather_response = await self._get_owm_weather() weather_response = await self._get_owm_weather()
data = self._convert_weather_response(weather_response) data = self._convert_weather_response(weather_response)

View File

@ -1,11 +1,11 @@
"""Support for OVO Energy.""" """Support for OVO Energy."""
from __future__ import annotations from __future__ import annotations
import asyncio
from datetime import datetime, timedelta from datetime import datetime, timedelta
import logging import logging
import aiohttp import aiohttp
import async_timeout
from ovoenergy import OVODailyUsage from ovoenergy import OVODailyUsage
from ovoenergy.ovoenergy import OVOEnergy from ovoenergy.ovoenergy import OVOEnergy
@ -47,7 +47,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
async def async_update_data() -> OVODailyUsage: async def async_update_data() -> OVODailyUsage:
"""Fetch data from OVO Energy.""" """Fetch data from OVO Energy."""
async with async_timeout.timeout(10): async with asyncio.timeout(10):
try: try:
authenticated = await client.authenticate( authenticated = await client.authenticate(
entry.data[CONF_USERNAME], entry.data[CONF_USERNAME],

View File

@ -1,10 +1,10 @@
"""Coordinator to fetch data from the Picnic API.""" """Coordinator to fetch data from the Picnic API."""
import asyncio
from contextlib import suppress from contextlib import suppress
import copy import copy
from datetime import timedelta from datetime import timedelta
import logging import logging
import async_timeout
from python_picnic_api import PicnicAPI from python_picnic_api import PicnicAPI
from python_picnic_api.session import PicnicAuthError from python_picnic_api.session import PicnicAuthError
@ -44,7 +44,7 @@ class PicnicUpdateCoordinator(DataUpdateCoordinator):
try: try:
# Note: asyncio.TimeoutError and aiohttp.ClientError are already # Note: asyncio.TimeoutError and aiohttp.ClientError are already
# handled by the data update coordinator. # handled by the data update coordinator.
async with async_timeout.timeout(10): async with asyncio.timeout(10):
data = await self.hass.async_add_executor_job(self.fetch_data) data = await self.hass.async_add_executor_job(self.fetch_data)
# Update the auth token in the config entry if applicable # Update the auth token in the config entry if applicable

View File

@ -8,7 +8,6 @@ import logging
import re import re
from typing import TYPE_CHECKING, Any from typing import TYPE_CHECKING, Any
import async_timeout
from icmplib import NameLookupError, async_ping from icmplib import NameLookupError, async_ping
import voluptuous as vol import voluptuous as vol
@ -218,7 +217,7 @@ class PingDataSubProcess(PingData):
close_fds=False, # required for posix_spawn close_fds=False, # required for posix_spawn
) )
try: try:
async with async_timeout.timeout(self._count + PING_TIMEOUT): async with asyncio.timeout(self._count + PING_TIMEOUT):
out_data, out_error = await pinger.communicate() out_data, out_error = await pinger.communicate()
if out_data: if out_data:

View File

@ -3,7 +3,6 @@ import asyncio
from collections import OrderedDict from collections import OrderedDict
import logging import logging
import async_timeout
from pypoint import PointSession from pypoint import PointSession
import voluptuous as vol import voluptuous as vol
@ -94,7 +93,7 @@ class PointFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
errors["base"] = "follow_link" errors["base"] = "follow_link"
try: try:
async with async_timeout.timeout(10): async with asyncio.timeout(10):
url = await self._get_authorization_url() url = await self._get_authorization_url()
except asyncio.TimeoutError: except asyncio.TimeoutError:
return self.async_abort(reason="authorize_url_timeout") return self.async_abort(reason="authorize_url_timeout")

View File

@ -1,8 +1,8 @@
"""The PoolSense integration.""" """The PoolSense integration."""
import asyncio
from datetime import timedelta from datetime import timedelta
import logging import logging
import async_timeout
from poolsense import PoolSense from poolsense import PoolSense
from poolsense.exceptions import PoolSenseError from poolsense.exceptions import PoolSenseError
@ -90,7 +90,7 @@ class PoolSenseDataUpdateCoordinator(DataUpdateCoordinator):
async def _async_update_data(self): async def _async_update_data(self):
"""Update data via library.""" """Update data via library."""
data = {} data = {}
async with async_timeout.timeout(10): async with asyncio.timeout(10):
try: try:
data = await self.poolsense.get_poolsense_data() data = await self.poolsense.get_poolsense_data()
except PoolSenseError as error: except PoolSenseError as error:

View File

@ -1,8 +1,8 @@
"""Control binary sensor instances.""" """Control binary sensor instances."""
import asyncio
from datetime import timedelta from datetime import timedelta
import logging import logging
import async_timeout
from ProgettiHWSW.input import Input from ProgettiHWSW.input import Input
from homeassistant.components.binary_sensor import BinarySensorEntity from homeassistant.components.binary_sensor import BinarySensorEntity
@ -32,7 +32,7 @@ async def async_setup_entry(
async def async_update_data(): async def async_update_data():
"""Fetch data from API endpoint of board.""" """Fetch data from API endpoint of board."""
async with async_timeout.timeout(5): async with asyncio.timeout(5):
return await board_api.get_inputs() return await board_api.get_inputs()
coordinator = DataUpdateCoordinator( coordinator = DataUpdateCoordinator(

View File

@ -1,9 +1,9 @@
"""Control switches.""" """Control switches."""
import asyncio
from datetime import timedelta from datetime import timedelta
import logging import logging
from typing import Any from typing import Any
import async_timeout
from ProgettiHWSW.relay import Relay from ProgettiHWSW.relay import Relay
from homeassistant.components.switch import SwitchEntity from homeassistant.components.switch import SwitchEntity
@ -33,7 +33,7 @@ async def async_setup_entry(
async def async_update_data(): async def async_update_data():
"""Fetch data from API endpoint of board.""" """Fetch data from API endpoint of board."""
async with async_timeout.timeout(5): async with asyncio.timeout(5):
return await board_api.get_switches() return await board_api.get_switches()
coordinator = DataUpdateCoordinator( coordinator = DataUpdateCoordinator(

View File

@ -5,7 +5,6 @@ import asyncio
from http import HTTPStatus from http import HTTPStatus
import logging import logging
import async_timeout
import voluptuous as vol import voluptuous as vol
from homeassistant.components.notify import ( from homeassistant.components.notify import (
@ -64,7 +63,7 @@ class ProwlNotificationService(BaseNotificationService):
session = async_get_clientsession(self._hass) session = async_get_clientsession(self._hass)
try: try:
async with async_timeout.timeout(10): async with asyncio.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

@ -2,12 +2,12 @@
from __future__ import annotations from __future__ import annotations
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
import asyncio
from datetime import timedelta from datetime import timedelta
import logging import logging
from time import monotonic from time import monotonic
from typing import Generic, TypeVar from typing import Generic, TypeVar
import async_timeout
from pyprusalink import InvalidAuth, JobInfo, PrinterInfo, PrusaLink, PrusaLinkError from pyprusalink import InvalidAuth, JobInfo, PrinterInfo, PrusaLink, PrusaLinkError
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
@ -77,7 +77,7 @@ class PrusaLinkUpdateCoordinator(DataUpdateCoordinator, Generic[T], ABC):
async def _async_update_data(self) -> T: async def _async_update_data(self) -> T:
"""Update the data.""" """Update the data."""
try: try:
async with async_timeout.timeout(5): async with asyncio.timeout(5):
data = await self._fetch_data() data = await self._fetch_data()
except InvalidAuth: except InvalidAuth:
raise UpdateFailed("Invalid authentication") from None raise UpdateFailed("Invalid authentication") from None

View File

@ -6,7 +6,6 @@ import logging
from typing import Any from typing import Any
from aiohttp import ClientError from aiohttp import ClientError
import async_timeout
from awesomeversion import AwesomeVersion, AwesomeVersionException from awesomeversion import AwesomeVersion, AwesomeVersionException
from pyprusalink import InvalidAuth, PrusaLink from pyprusalink import InvalidAuth, PrusaLink
import voluptuous as vol import voluptuous as vol
@ -39,7 +38,7 @@ async def validate_input(hass: HomeAssistant, data: dict[str, str]) -> dict[str,
api = PrusaLink(async_get_clientsession(hass), data[CONF_HOST], data[CONF_API_KEY]) api = PrusaLink(async_get_clientsession(hass), data[CONF_HOST], data[CONF_API_KEY])
try: try:
async with async_timeout.timeout(5): async with asyncio.timeout(5):
version = await api.get_version() version = await api.get_version()
except (asyncio.TimeoutError, ClientError) as err: except (asyncio.TimeoutError, ClientError) as err:

View File

@ -7,7 +7,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 import webhook from homeassistant.components import webhook
@ -74,7 +73,7 @@ async def async_setup_platform(
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:
async with async_timeout.timeout(5): async with asyncio.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

@ -1,13 +1,13 @@
"""The QNAP QSW coordinator.""" """The QNAP QSW coordinator."""
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 Any from typing import Any
from aioqsw.exceptions import QswError from aioqsw.exceptions import QswError
from aioqsw.localapi import QnapQswApi from aioqsw.localapi import QnapQswApi
import async_timeout
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
@ -36,7 +36,7 @@ class QswDataCoordinator(DataUpdateCoordinator[dict[str, Any]]):
async def _async_update_data(self) -> dict[str, Any]: async def _async_update_data(self) -> dict[str, Any]:
"""Update data via library.""" """Update data via library."""
async with async_timeout.timeout(QSW_TIMEOUT_SEC): async with asyncio.timeout(QSW_TIMEOUT_SEC):
try: try:
await self.qsw.update() await self.qsw.update()
except QswError as error: except QswError as error:
@ -60,7 +60,7 @@ class QswFirmwareCoordinator(DataUpdateCoordinator[dict[str, Any]]):
async def _async_update_data(self) -> dict[str, Any]: async def _async_update_data(self) -> dict[str, Any]:
"""Update firmware data via library.""" """Update firmware data via library."""
async with async_timeout.timeout(QSW_TIMEOUT_SEC): async with asyncio.timeout(QSW_TIMEOUT_SEC):
try: try:
await self.qsw.check_firmware() await self.qsw.check_firmware()
except QswError as error: except QswError as error:

View File

@ -6,7 +6,6 @@ import asyncio
import logging import logging
from typing import Any from typing import Any
import async_timeout
from pyrainbird.async_client import ( from pyrainbird.async_client import (
AsyncRainbirdClient, AsyncRainbirdClient,
AsyncRainbirdController, AsyncRainbirdController,
@ -106,7 +105,7 @@ class RainbirdConfigFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
) )
) )
try: try:
async with async_timeout.timeout(TIMEOUT_SECONDS): async with asyncio.timeout(TIMEOUT_SECONDS):
return await controller.get_serial_number() return await controller.get_serial_number()
except asyncio.TimeoutError as err: except asyncio.TimeoutError as err:
raise ConfigFlowError( raise ConfigFlowError(

View File

@ -2,12 +2,12 @@
from __future__ import annotations from __future__ import annotations
import asyncio
from dataclasses import dataclass from dataclasses import dataclass
import datetime import datetime
import logging import logging
from typing import TypeVar from typing import TypeVar
import async_timeout
from pyrainbird.async_client import ( from pyrainbird.async_client import (
AsyncRainbirdController, AsyncRainbirdController,
RainbirdApiException, RainbirdApiException,
@ -86,7 +86,7 @@ class RainbirdUpdateCoordinator(DataUpdateCoordinator[RainbirdDeviceState]):
async def _async_update_data(self) -> RainbirdDeviceState: async def _async_update_data(self) -> RainbirdDeviceState:
"""Fetch data from Rain Bird device.""" """Fetch data from Rain Bird device."""
try: try:
async with async_timeout.timeout(TIMEOUT_SECONDS): async with asyncio.timeout(TIMEOUT_SECONDS):
return await self._fetch_data() return await self._fetch_data()
except RainbirdDeviceBusyException as err: except RainbirdDeviceBusyException as err:
raise UpdateFailed("Rain Bird device is busy") from err raise UpdateFailed("Rain Bird device is busy") from err

View File

@ -1,12 +1,12 @@
"""Rainforest data.""" """Rainforest data."""
from __future__ import annotations from __future__ import annotations
import asyncio
from datetime import timedelta from datetime import timedelta
import logging import logging
import aioeagle import aioeagle
import aiohttp import aiohttp
import async_timeout
from eagle100 import Eagle as Eagle100Reader from eagle100 import Eagle as Eagle100Reader
from requests.exceptions import ConnectionError as ConnectError, HTTPError, Timeout from requests.exceptions import ConnectionError as ConnectError, HTTPError, Timeout
@ -50,7 +50,7 @@ async def async_get_type(hass, cloud_id, install_code, host):
) )
try: try:
async with async_timeout.timeout(30): async with asyncio.timeout(30):
meters = await hub.get_device_list() meters = await hub.get_device_list()
except aioeagle.BadAuth as err: except aioeagle.BadAuth as err:
raise InvalidAuth from err raise InvalidAuth from err
@ -150,7 +150,7 @@ class EagleDataCoordinator(DataUpdateCoordinator):
else: else:
is_connected = eagle200_meter.is_connected is_connected = eagle200_meter.is_connected
async with async_timeout.timeout(30): async with asyncio.timeout(30):
data = await eagle200_meter.get_device_query() data = await eagle200_meter.get_device_query()
if self.eagle200_meter is None: if self.eagle200_meter is None:

View File

@ -1,12 +1,12 @@
"""The Renson integration.""" """The Renson integration."""
from __future__ import annotations from __future__ import annotations
import asyncio
from dataclasses import dataclass from dataclasses import dataclass
from datetime import timedelta from datetime import timedelta
import logging import logging
from typing import Any from typing import Any
import async_timeout
from renson_endura_delta.renson import RensonVentilation from renson_endura_delta.renson import RensonVentilation
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
@ -84,5 +84,5 @@ class RensonCoordinator(DataUpdateCoordinator):
async def _async_update_data(self) -> dict[str, Any]: async def _async_update_data(self) -> dict[str, Any]:
"""Fetch data from API endpoint.""" """Fetch data from API endpoint."""
async with async_timeout.timeout(30): async with asyncio.timeout(30):
return await self.hass.async_add_executor_job(self.api.get_all_data) return await self.hass.async_add_executor_job(self.api.get_all_data)

View File

@ -8,7 +8,6 @@ from datetime import timedelta
import logging import logging
from typing import Literal from typing import Literal
import async_timeout
from reolink_aio.api import RETRY_ATTEMPTS from reolink_aio.api import RETRY_ATTEMPTS
from reolink_aio.exceptions import CredentialsInvalidError, ReolinkError from reolink_aio.exceptions import CredentialsInvalidError, ReolinkError
@ -78,13 +77,13 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
async def async_device_config_update() -> None: async def async_device_config_update() -> None:
"""Update the host state cache and renew the ONVIF-subscription.""" """Update the host state cache and renew the ONVIF-subscription."""
async with async_timeout.timeout(host.api.timeout * (RETRY_ATTEMPTS + 2)): async with asyncio.timeout(host.api.timeout * (RETRY_ATTEMPTS + 2)):
try: try:
await host.update_states() await host.update_states()
except ReolinkError as err: except ReolinkError as err:
raise UpdateFailed(str(err)) from err raise UpdateFailed(str(err)) from err
async with async_timeout.timeout(host.api.timeout * (RETRY_ATTEMPTS + 2)): async with asyncio.timeout(host.api.timeout * (RETRY_ATTEMPTS + 2)):
await host.renew() await host.renew()
async def async_check_firmware_update() -> str | Literal[False]: async def async_check_firmware_update() -> str | Literal[False]:
@ -92,7 +91,7 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
if not host.api.supported(None, "update"): if not host.api.supported(None, "update"):
return False return False
async with async_timeout.timeout(host.api.timeout * (RETRY_ATTEMPTS + 2)): async with asyncio.timeout(host.api.timeout * (RETRY_ATTEMPTS + 2)):
try: try:
return await host.api.check_new_firmware() return await host.api.check_new_firmware()
except (ReolinkError, asyncio.exceptions.CancelledError) as err: except (ReolinkError, asyncio.exceptions.CancelledError) as err:

View File

@ -6,7 +6,6 @@ from http import HTTPStatus
import logging import logging
from typing import Any from typing import Any
import async_timeout
import httpx import httpx
import voluptuous as vol import voluptuous as vol
@ -203,7 +202,7 @@ class RestSwitch(ManualTriggerEntity, SwitchEntity):
rendered_headers = template.render_complex(self._headers, parse_result=False) rendered_headers = template.render_complex(self._headers, parse_result=False)
rendered_params = template.render_complex(self._params) rendered_params = template.render_complex(self._params)
async with async_timeout.timeout(self._timeout): async with asyncio.timeout(self._timeout):
req: httpx.Response = await getattr(websession, self._method)( req: httpx.Response = await getattr(websession, self._method)(
self._resource, self._resource,
auth=self._auth, auth=self._auth,
@ -234,7 +233,7 @@ class RestSwitch(ManualTriggerEntity, SwitchEntity):
rendered_headers = template.render_complex(self._headers, parse_result=False) rendered_headers = template.render_complex(self._headers, parse_result=False)
rendered_params = template.render_complex(self._params) rendered_params = template.render_complex(self._params)
async with async_timeout.timeout(self._timeout): async with asyncio.timeout(self._timeout):
req = await websession.get( req = await websession.get(
self._state_resource, self._state_resource,
auth=self._auth, auth=self._auth,

View File

@ -5,7 +5,6 @@ import asyncio
from collections import defaultdict from collections import defaultdict
import logging import logging
import async_timeout
from rflink.protocol import ProtocolBase, create_rflink_connection from rflink.protocol import ProtocolBase, create_rflink_connection
from serial import SerialException from serial import SerialException
import voluptuous as vol import voluptuous as vol
@ -280,7 +279,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
) )
try: try:
async with async_timeout.timeout(CONNECTION_TIMEOUT): async with asyncio.timeout(CONNECTION_TIMEOUT):
transport, protocol = await connection transport, protocol = await connection
except ( except (

View File

@ -8,7 +8,6 @@ import copy
import logging import logging
from typing import Any, NamedTuple, cast from typing import Any, NamedTuple, cast
import async_timeout
import RFXtrx as rfxtrxmod import RFXtrx as rfxtrxmod
import voluptuous as vol import voluptuous as vol
@ -165,7 +164,7 @@ async def async_setup_internal(hass: HomeAssistant, entry: ConfigEntry) -> None:
config = entry.data config = entry.data
# Initialize library # Initialize library
async with async_timeout.timeout(30): async with asyncio.timeout(30):
rfx_object = await hass.async_add_executor_job(_create_rfx, config) rfx_object = await hass.async_add_executor_job(_create_rfx, config)
# Setup some per device config # Setup some per device config

View File

@ -8,7 +8,6 @@ import itertools
import os import os
from typing import Any, TypedDict, cast from typing import Any, TypedDict, cast
from async_timeout import timeout
import RFXtrx as rfxtrxmod import RFXtrx as rfxtrxmod
import serial import serial
import serial.tools.list_ports import serial.tools.list_ports
@ -374,7 +373,7 @@ class OptionsFlow(config_entries.OptionsFlow):
# Wait for entities to finish cleanup # Wait for entities to finish cleanup
with suppress(asyncio.TimeoutError): with suppress(asyncio.TimeoutError):
async with timeout(10): async with asyncio.timeout(10):
await wait_for_entities.wait() await wait_for_entities.wait()
remove_track_state_changes() remove_track_state_changes()
@ -409,7 +408,7 @@ class OptionsFlow(config_entries.OptionsFlow):
# Wait for entities to finish renaming # Wait for entities to finish renaming
with suppress(asyncio.TimeoutError): with suppress(asyncio.TimeoutError):
async with timeout(10): async with asyncio.timeout(10):
await wait_for_entities.wait() await wait_for_entities.wait()
remove_track_state_changes() remove_track_state_changes()

View File

@ -3,7 +3,6 @@ import asyncio
from functools import partial from functools import partial
import logging import logging
import async_timeout
from roombapy import RoombaConnectionError, RoombaFactory from roombapy import RoombaConnectionError, RoombaFactory
from homeassistant import exceptions from homeassistant import exceptions
@ -86,7 +85,7 @@ async def async_connect_or_timeout(hass, roomba):
"""Connect to vacuum.""" """Connect to vacuum."""
try: try:
name = None name = None
async with async_timeout.timeout(10): async with asyncio.timeout(10):
_LOGGER.debug("Initialize connection to vacuum") _LOGGER.debug("Initialize connection to vacuum")
await hass.async_add_executor_job(roomba.connect) await hass.async_add_executor_job(roomba.connect)
while not roomba.roomba_connected or name is None: while not roomba.roomba_connected or name is None:
@ -110,7 +109,7 @@ async def async_connect_or_timeout(hass, roomba):
async def async_disconnect_or_timeout(hass, roomba): async def async_disconnect_or_timeout(hass, roomba):
"""Disconnect to vacuum.""" """Disconnect to vacuum."""
_LOGGER.debug("Disconnect vacuum") _LOGGER.debug("Disconnect vacuum")
async with async_timeout.timeout(3): async with asyncio.timeout(3):
await hass.async_add_executor_job(roomba.disconnect) await hass.async_add_executor_job(roomba.disconnect)
return True return True

View File

@ -18,10 +18,10 @@ Other integrations may use this integration with these steps:
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 rtsp_to_webrtc.client import get_adaptive_client from rtsp_to_webrtc.client import get_adaptive_client
from rtsp_to_webrtc.exceptions import ClientError, ResponseError from rtsp_to_webrtc.exceptions import ClientError, ResponseError
from rtsp_to_webrtc.interface import WebRTCClientInterface from rtsp_to_webrtc.interface import WebRTCClientInterface
@ -48,7 +48,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
client: WebRTCClientInterface client: WebRTCClientInterface
try: try:
async with async_timeout.timeout(TIMEOUT): async with asyncio.timeout(TIMEOUT):
client = await get_adaptive_client( client = await get_adaptive_client(
async_get_clientsession(hass), entry.data[DATA_SERVER_URL] async_get_clientsession(hass), entry.data[DATA_SERVER_URL]
) )
@ -71,7 +71,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
the stream itself happens directly between the client and proxy. the stream itself happens directly between the client and proxy.
""" """
try: try:
async with async_timeout.timeout(TIMEOUT): async with asyncio.timeout(TIMEOUT):
return await client.offer_stream_id(stream_id, offer_sdp, stream_source) return await client.offer_stream_id(stream_id, offer_sdp, stream_source)
except TimeoutError as err: except TimeoutError as err:
raise HomeAssistantError("Timeout talking to RTSPtoWebRTC server") from err raise HomeAssistantError("Timeout talking to RTSPtoWebRTC server") from err

View File

@ -5,7 +5,6 @@ import asyncio
from collections.abc import Coroutine, Sequence from collections.abc import Coroutine, Sequence
from typing import Any from typing import Any
import async_timeout
from async_upnp_client.aiohttp import AiohttpNotifyServer, AiohttpSessionRequester from async_upnp_client.aiohttp import AiohttpNotifyServer, AiohttpSessionRequester
from async_upnp_client.client import UpnpDevice, UpnpService, UpnpStateVariable from async_upnp_client.client import UpnpDevice, UpnpService, UpnpStateVariable
from async_upnp_client.client_factory import UpnpFactory from async_upnp_client.client_factory import UpnpFactory
@ -217,7 +216,7 @@ class SamsungTVDevice(SamsungTVEntity, MediaPlayerEntity):
# enter it unless we have to (Python 3.11 will have zero cost try) # enter it unless we have to (Python 3.11 will have zero cost try)
return return
try: try:
async with async_timeout.timeout(APP_LIST_DELAY): async with asyncio.timeout(APP_LIST_DELAY):
await self._app_list_event.wait() await self._app_list_event.wait()
except asyncio.TimeoutError as err: except asyncio.TimeoutError as err:
# No need to try again # No need to try again

View File

@ -1,10 +1,10 @@
"""Base entity for Sensibo integration.""" """Base entity for Sensibo integration."""
from __future__ import annotations from __future__ import annotations
import asyncio
from collections.abc import Callable, Coroutine from collections.abc import Callable, Coroutine
from typing import TYPE_CHECKING, Any, Concatenate, ParamSpec, TypeVar from typing import TYPE_CHECKING, Any, Concatenate, ParamSpec, TypeVar
import async_timeout
from pysensibo.model import MotionSensor, SensiboDevice from pysensibo.model import MotionSensor, SensiboDevice
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
@ -27,7 +27,7 @@ def async_handle_api_call(
"""Wrap services for api calls.""" """Wrap services for api calls."""
res: bool = False res: bool = False
try: try:
async with async_timeout.timeout(TIMEOUT): async with asyncio.timeout(TIMEOUT):
res = await function(*args, **kwargs) res = await function(*args, **kwargs)
except SENSIBO_ERRORS as err: except SENSIBO_ERRORS as err:
raise HomeAssistantError from err raise HomeAssistantError from err

View File

@ -1,7 +1,8 @@
"""Utils for Sensibo integration.""" """Utils for Sensibo integration."""
from __future__ import annotations from __future__ import annotations
import async_timeout import asyncio
from pysensibo import SensiboClient from pysensibo import SensiboClient
from pysensibo.exceptions import AuthenticationError from pysensibo.exceptions import AuthenticationError
@ -20,7 +21,7 @@ async def async_validate_api(hass: HomeAssistant, api_key: str) -> str:
) )
try: try:
async with async_timeout.timeout(TIMEOUT): async with asyncio.timeout(TIMEOUT):
device_query = await client.async_get_devices() device_query = await client.async_get_devices()
user_query = await client.async_get_me() user_query = await client.async_get_me()
except AuthenticationError as err: except AuthenticationError as err:

View File

@ -2,7 +2,6 @@
import asyncio import asyncio
from contextlib import suppress from contextlib import suppress
import async_timeout
from sharkiq import ( from sharkiq import (
AylaApi, AylaApi,
SharkIqAuthError, SharkIqAuthError,
@ -35,7 +34,7 @@ class CannotConnect(exceptions.HomeAssistantError):
async def async_connect_or_timeout(ayla_api: AylaApi) -> bool: async def async_connect_or_timeout(ayla_api: AylaApi) -> bool:
"""Connect to vacuum.""" """Connect to vacuum."""
try: try:
async with async_timeout.timeout(API_TIMEOUT): async with asyncio.timeout(API_TIMEOUT):
LOGGER.debug("Initialize connection to Ayla networks API") LOGGER.debug("Initialize connection to Ayla networks API")
await ayla_api.async_sign_in() await ayla_api.async_sign_in()
except SharkIqAuthError: except SharkIqAuthError:
@ -87,7 +86,7 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
async def async_disconnect_or_timeout(coordinator: SharkIqUpdateCoordinator): async def async_disconnect_or_timeout(coordinator: SharkIqUpdateCoordinator):
"""Disconnect to vacuum.""" """Disconnect to vacuum."""
LOGGER.debug("Disconnecting from Ayla Api") LOGGER.debug("Disconnecting from Ayla Api")
async with async_timeout.timeout(5): async with asyncio.timeout(5):
with suppress( with suppress(
SharkIqAuthError, SharkIqAuthExpiringError, SharkIqNotAuthedError SharkIqAuthError, SharkIqAuthExpiringError, SharkIqNotAuthedError
): ):

View File

@ -6,7 +6,6 @@ from collections.abc import Mapping
from typing import Any from typing import Any
import aiohttp import aiohttp
import async_timeout
from sharkiq import SharkIqAuthError, get_ayla_api from sharkiq import SharkIqAuthError, get_ayla_api
import voluptuous as vol import voluptuous as vol
@ -51,7 +50,7 @@ async def _validate_input(
) )
try: try:
async with async_timeout.timeout(10): async with asyncio.timeout(10):
LOGGER.debug("Initialize connection to Ayla networks API") LOGGER.debug("Initialize connection to Ayla networks API")
await ayla_api.async_sign_in() await ayla_api.async_sign_in()
except (asyncio.TimeoutError, aiohttp.ClientError, TypeError) as error: except (asyncio.TimeoutError, aiohttp.ClientError, TypeError) as error:

View File

@ -4,7 +4,6 @@ from __future__ import annotations
import asyncio import asyncio
from datetime import datetime, timedelta from datetime import datetime, timedelta
from async_timeout import timeout
from sharkiq import ( from sharkiq import (
AylaApi, AylaApi,
SharkIqAuthError, SharkIqAuthError,
@ -55,7 +54,7 @@ class SharkIqUpdateCoordinator(DataUpdateCoordinator[bool]):
"""Asynchronously update the data for a single vacuum.""" """Asynchronously update the data for a single vacuum."""
dsn = sharkiq.serial_number dsn = sharkiq.serial_number
LOGGER.debug("Updating sharkiq data for device DSN %s", dsn) LOGGER.debug("Updating sharkiq data for device DSN %s", dsn)
async with timeout(API_TIMEOUT): async with asyncio.timeout(API_TIMEOUT):
await sharkiq.async_update() await sharkiq.async_update()
async def _async_update_data(self) -> bool: async def _async_update_data(self) -> bool:

View File

@ -6,7 +6,6 @@ from contextlib import suppress
import logging import logging
import shlex import shlex
import async_timeout
import voluptuous as vol import voluptuous as vol
from homeassistant.core import ( from homeassistant.core import (
@ -89,7 +88,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
process = await create_process process = await create_process
try: try:
async with async_timeout.timeout(COMMAND_TIMEOUT): async with asyncio.timeout(COMMAND_TIMEOUT):
stdout_data, stderr_data = await process.communicate() stdout_data, stderr_data = await process.communicate()
except asyncio.TimeoutError: except asyncio.TimeoutError:
_LOGGER.error( _LOGGER.error(

View File

@ -5,7 +5,6 @@ from datetime import timedelta
import logging import logging
from aiohttp import client_exceptions from aiohttp import client_exceptions
import async_timeout
from smarttub import APIError, LoginFailed, SmartTub from smarttub import APIError, LoginFailed, SmartTub
from smarttub.api import Account from smarttub.api import Account
@ -85,7 +84,7 @@ class SmartTubController:
data = {} data = {}
try: try:
async with async_timeout.timeout(POLLING_TIMEOUT): async with asyncio.timeout(POLLING_TIMEOUT):
for spa in self.spas: for spa in self.spas:
data[spa.id] = await self._get_spa_data(spa) data[spa.id] = await self._get_spa_data(spa)
except APIError as err: except APIError as err:

View File

@ -1,7 +1,7 @@
"""Platform for switch integration.""" """Platform for switch integration."""
import asyncio
from typing import Any from typing import Any
import async_timeout
from smarttub import SpaPump from smarttub import SpaPump
from homeassistant.components.switch import SwitchEntity from homeassistant.components.switch import SwitchEntity
@ -80,6 +80,6 @@ class SmartTubPump(SmartTubEntity, SwitchEntity):
async def async_toggle(self, **kwargs: Any) -> None: async def async_toggle(self, **kwargs: Any) -> None:
"""Toggle the pump on or off.""" """Toggle the pump on or off."""
async with async_timeout.timeout(API_TIMEOUT): async with asyncio.timeout(API_TIMEOUT):
await self.pump.toggle() await self.pump.toggle()
await self.coordinator.async_request_refresh() await self.coordinator.async_request_refresh()

View File

@ -8,7 +8,6 @@ import logging
from typing import Any, Final from typing import Any, Final
import aiohttp import aiohttp
import async_timeout
from smhi import Smhi from smhi import Smhi
from smhi.smhi_lib import SmhiForecast, SmhiForecastException from smhi.smhi_lib import SmhiForecast, SmhiForecastException
@ -164,7 +163,7 @@ class SmhiWeather(WeatherEntity):
async def async_update(self) -> None: async def async_update(self) -> None:
"""Refresh the forecast data from SMHI weather API.""" """Refresh the forecast data from SMHI weather API."""
try: try:
async with async_timeout.timeout(TIMEOUT): async with asyncio.timeout(TIMEOUT):
self._forecast_daily = await self._smhi_api.async_get_forecast() self._forecast_daily = await self._smhi_api.async_get_forecast()
self._forecast_hourly = await self._smhi_api.async_get_forecast_hour() self._forecast_hourly = await self._smhi_api.async_get_forecast_hour()
self._fail_count = 0 self._fail_count = 0

View File

@ -1,8 +1,8 @@
"""The sms component.""" """The sms component."""
import asyncio
from datetime import timedelta from datetime import timedelta
import logging import logging
import async_timeout
import gammu # pylint: disable=import-error import gammu # pylint: disable=import-error
import voluptuous as vol import voluptuous as vol
@ -125,7 +125,7 @@ class SignalCoordinator(DataUpdateCoordinator):
async def _async_update_data(self): async def _async_update_data(self):
"""Fetch device signal quality.""" """Fetch device signal quality."""
try: try:
async with async_timeout.timeout(10): async with asyncio.timeout(10):
return await self._gateway.get_signal_quality_async() return await self._gateway.get_signal_quality_async()
except gammu.GSMError as exc: except gammu.GSMError as exc:
raise UpdateFailed(f"Error communicating with device: {exc}") from exc raise UpdateFailed(f"Error communicating with device: {exc}") from exc
@ -147,7 +147,7 @@ class NetworkCoordinator(DataUpdateCoordinator):
async def _async_update_data(self): async def _async_update_data(self):
"""Fetch device network info.""" """Fetch device network info."""
try: try:
async with async_timeout.timeout(10): async with asyncio.timeout(10):
return await self._gateway.get_network_info_async() return await self._gateway.get_network_info_async()
except gammu.GSMError as exc: except gammu.GSMError as exc:
raise UpdateFailed(f"Error communicating with device: {exc}") from exc raise UpdateFailed(f"Error communicating with device: {exc}") from exc

View File

@ -108,7 +108,7 @@ async def test_controller_timeout(
"""Test an error talking to the controller.""" """Test an error talking to the controller."""
with patch( with patch(
"homeassistant.components.rainbird.config_flow.async_timeout.timeout", "homeassistant.components.rainbird.config_flow.asyncio.timeout",
side_effect=asyncio.TimeoutError, side_effect=asyncio.TimeoutError,
): ):
result = await complete_flow(hass) result = await complete_flow(hass)