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

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

View File

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

View File

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

View File

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

View File

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

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 PLATFORM_SCHEMA, BaseNotificationService from homeassistant.components.notify import PLATFORM_SCHEMA, BaseNotificationService
@ -49,7 +48,7 @@ class FlockNotificationService(BaseNotificationService):
_LOGGER.debug("Attempting to call Flock at %s", self._url) _LOGGER.debug("Attempting to call Flock at %s", self._url)
try: try:
async with async_timeout.timeout(10): async with asyncio.timeout(10):
response = await self._session.post(self._url, json=payload) response = await self._session.post(self._url, json=payload)
result = await response.json() result = await response.json()

View File

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

View File

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

View File

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

View File

@ -2,7 +2,6 @@
import asyncio import asyncio
from typing import Any, cast from typing import Any, cast
from async_timeout import timeout
from fullykiosk import FullyKiosk from fullykiosk import FullyKiosk
from fullykiosk.exceptions import FullyKioskError from fullykiosk.exceptions import FullyKioskError
@ -36,7 +35,7 @@ class FullyKioskDataUpdateCoordinator(DataUpdateCoordinator):
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."""
try: try:
async with timeout(15): async with asyncio.timeout(15):
# Get device info and settings in parallel # Get device info and settings in parallel
result = await asyncio.gather( result = await asyncio.gather(
self.fully.getDeviceInfo(), self.fully.getSettings() self.fully.getDeviceInfo(), self.fully.getSettings()

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -4,7 +4,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.const import CONF_DOMAIN, CONF_PASSWORD, CONF_TIMEOUT, CONF_USERNAME from homeassistant.const import CONF_DOMAIN, CONF_PASSWORD, CONF_TIMEOUT, CONF_USERNAME
@ -69,7 +68,7 @@ async def _update_google_domains(hass, session, domain, user, password, timeout)
params = {"hostname": domain} params = {"hostname": domain}
try: try:
async with async_timeout.timeout(timeout): async with asyncio.timeout(timeout):
resp = await session.get(url, params=params) resp = await session.get(url, params=params)
body = await resp.text() body = await resp.text()

View File

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

View File

@ -1,8 +1,8 @@
"""The Legrand Home+ Control integration.""" """The Legrand Home+ Control integration."""
import asyncio
from datetime import timedelta from datetime import timedelta
import logging import logging
import async_timeout
from homepluscontrol.homeplusapi import HomePlusControlApiError from homepluscontrol.homeplusapi import HomePlusControlApiError
import voluptuous as vol import voluptuous as vol
@ -100,7 +100,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
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):
return await api.async_get_modules() return await api.async_get_modules()
except HomePlusControlApiError as err: except HomePlusControlApiError as err:
raise UpdateFailed( raise UpdateFailed(

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,9 +1,9 @@
"""The Huisbaasje integration.""" """The Huisbaasje integration."""
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 energyflip import EnergyFlip, EnergyFlipException from energyflip import EnergyFlip, EnergyFlipException
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
@ -86,7 +86,7 @@ async def async_update_huisbaasje(energyflip: EnergyFlip) -> dict[str, dict[str,
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(FETCH_TIMEOUT): async with asyncio.timeout(FETCH_TIMEOUT):
if not energyflip.is_authenticated(): if not energyflip.is_authenticated():
_LOGGER.warning("Huisbaasje is unauthenticated. Reauthenticating") _LOGGER.warning("Huisbaasje is unauthenticated. Reauthenticating")
await energyflip.authenticate() await energyflip.authenticate()

View File

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

View File

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

View File

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

View File

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

View File

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