Bump to aiohttp 3.8.0 (#58974)

This commit is contained in:
J. Nick Koston 2021-11-04 10:07:50 -05:00 committed by GitHub
parent 23cb396aad
commit 10d6247fee
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
106 changed files with 221 additions and 142 deletions

View file

@ -0,0 +1,67 @@
"""Provide backwards compat for async_timeout."""
from __future__ import annotations
import asyncio
import contextlib
import logging
from typing import Any
import async_timeout
from homeassistant.helpers.frame import (
MissingIntegrationFrame,
get_integration_frame,
report_integration,
)
_LOGGER = logging.getLogger(__name__)
def timeout(
delay: float | None, loop: asyncio.AbstractEventLoop | None = None
) -> async_timeout.Timeout:
"""Backwards compatible timeout context manager that warns with loop usage."""
if loop is None:
loop = asyncio.get_running_loop()
else:
_report(
"called async_timeout.timeout with loop keyword argument. The loop keyword argument is deprecated and calls will fail after Home Assistant 2022.2"
)
if delay is not None:
deadline: float | None = loop.time() + delay
else:
deadline = None
return async_timeout.Timeout(deadline, loop)
def current_task(loop: asyncio.AbstractEventLoop) -> asyncio.Task[Any] | None:
"""Backwards compatible current_task."""
_report(
"called async_timeout.current_task. The current_task call is deprecated and calls will fail after Home Assistant 2022.2; use asyncio.current_task instead"
)
return asyncio.current_task()
def enable() -> None:
"""Enable backwards compat transitions."""
async_timeout.timeout = timeout
async_timeout.current_task = current_task # type: ignore[attr-defined]
def _report(what: str) -> None:
"""Report incorrect usage.
Async friendly.
"""
integration_frame = None
with contextlib.suppress(MissingIntegrationFrame):
integration_frame = get_integration_frame()
if not integration_frame:
_LOGGER.warning(
"Detected code that %s; Please report this issue", what, stack_info=True
)
return
report_integration(what, integration_frame)

View file

@ -307,7 +307,7 @@ class AdsEntity(Entity):
self._ads_hub.add_device_notification, ads_var, plctype, update
)
try:
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
await self._event.wait()
except asyncio.TimeoutError:
_LOGGER.debug("Variable %s: Timeout during first update", ads_var)

View file

@ -140,7 +140,7 @@ class WeatherUpdateCoordinator(DataUpdateCoordinator):
async def _async_update_data(self):
data = {}
with async_timeout.timeout(120):
async with async_timeout.timeout(120):
weather_response = await self._get_aemet_weather()
data = self._convert_weather_response(weather_response)
return data

View file

@ -167,7 +167,7 @@ class AirlyDataUpdateCoordinator(DataUpdateCoordinator):
measurements = self.airly.create_measurements_session_point(
self.latitude, self.longitude
)
with async_timeout.timeout(20):
async with async_timeout.timeout(20):
try:
await measurements.update()
except (AirlyError, ClientConnectorError) as error:

View file

@ -103,7 +103,7 @@ async def test_location(
measurements = airly.create_measurements_session_point(
latitude=latitude, longitude=longitude
)
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
await measurements.update()
current = measurements.current

View file

@ -105,7 +105,7 @@ class Auth:
try:
session = aiohttp_client.async_get_clientsession(self.hass)
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
response = await session.post(
LWA_TOKEN_URI,
headers=LWA_HEADERS,

View file

@ -132,7 +132,7 @@ async def async_send_changereport_message(
session = hass.helpers.aiohttp_client.async_get_clientsession()
try:
with async_timeout.timeout(DEFAULT_TIMEOUT):
async with async_timeout.timeout(DEFAULT_TIMEOUT):
response = await session.post(
config.endpoint,
headers=headers,
@ -263,7 +263,7 @@ async def async_send_doorbell_event_message(hass, config, alexa_entity):
session = hass.helpers.aiohttp_client.async_get_clientsession()
try:
with async_timeout.timeout(DEFAULT_TIMEOUT):
async with async_timeout.timeout(DEFAULT_TIMEOUT):
response = await session.post(
config.endpoint,
headers=headers,

View file

@ -192,7 +192,7 @@ async def _configure_almond_for_ha(
# Store token in Almond
try:
with async_timeout.timeout(30):
async with async_timeout.timeout(30):
await api.async_create_device(
{
"kind": "io.home-assistant",

View file

@ -24,7 +24,7 @@ async def async_verify_local_connection(hass: core.HomeAssistant, host: str):
api = WebAlmondAPI(AlmondLocalAuth(host, websession))
try:
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
await api.async_list_apps()
return True

View file

@ -255,7 +255,7 @@ class Analytics:
)
try:
with async_timeout.timeout(30):
async with async_timeout.timeout(30):
response = await self.session.post(self.endpoint, json=payload)
if response.status == 200:
LOGGER.info(

View file

@ -131,7 +131,7 @@ class APIEventStream(HomeAssistantView):
while True:
try:
with async_timeout.timeout(STREAM_PING_INTERVAL):
async with async_timeout.timeout(STREAM_PING_INTERVAL):
payload = await to_write.get()
if payload is stop_obj:

View file

@ -85,7 +85,7 @@ async def _run_client(hass, client, interval):
while True:
try:
with async_timeout.timeout(interval):
async with async_timeout.timeout(interval):
await client.start()
_LOGGER.debug("Client connected %s", client.host)

View file

@ -29,7 +29,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
async def _async_update_data():
"""Update data via library."""
with async_timeout.timeout(20):
async with async_timeout.timeout(20):
try:
await atag.update()
except AtagException as err:

View file

@ -58,7 +58,7 @@ class AwairDataUpdateCoordinator(DataUpdateCoordinator):
async def _async_update_data(self) -> Any | None:
"""Update data via Awair client library."""
with timeout(API_TIMEOUT):
async with timeout(API_TIMEOUT):
try:
LOGGER.debug("Fetching users and devices")
user = await self._awair.user()

View file

@ -280,7 +280,7 @@ async def get_device(hass, host, port, username, password):
)
try:
with async_timeout.timeout(30):
async with async_timeout.timeout(30):
await device.vapix.initialize()
return device

View file

@ -358,7 +358,7 @@ class BluesoundPlayer(MediaPlayerEntity):
try:
websession = async_get_clientsession(self._hass)
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
response = await websession.get(url)
if response.status == HTTPStatus.OK:
@ -400,7 +400,7 @@ class BluesoundPlayer(MediaPlayerEntity):
try:
with async_timeout.timeout(125):
async with async_timeout.timeout(125):
response = await self._polling_session.get(
url, headers={CONNECTION: KEEP_ALIVE}
)

View file

@ -88,7 +88,7 @@ class BrData:
resp = None
try:
websession = async_get_clientsession(self.hass)
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
resp = await websession.get(url)
result[STATUS_CODE] = resp.status

View file

@ -135,7 +135,7 @@ async def async_citybikes_request(hass, uri, schema):
try:
session = async_get_clientsession(hass)
with async_timeout.timeout(REQUEST_TIMEOUT):
async with async_timeout.timeout(REQUEST_TIMEOUT):
req = await session.get(DEFAULT_ENDPOINT.format(uri=uri))
json_response = await req.json()

View file

@ -313,7 +313,7 @@ class AlexaConfig(alexa_config.AbstractConfig):
)
try:
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
await asyncio.wait(tasks, return_when=asyncio.ALL_COMPLETED)
return True

View file

@ -204,7 +204,7 @@ class CloudLogoutView(HomeAssistantView):
hass = request.app["hass"]
cloud = hass.data[DOMAIN]
with async_timeout.timeout(REQUEST_TIMEOUT):
async with async_timeout.timeout(REQUEST_TIMEOUT):
await cloud.logout()
return self.json_message("ok")
@ -230,7 +230,7 @@ class CloudRegisterView(HomeAssistantView):
hass = request.app["hass"]
cloud = hass.data[DOMAIN]
with async_timeout.timeout(REQUEST_TIMEOUT):
async with async_timeout.timeout(REQUEST_TIMEOUT):
await cloud.auth.async_register(data["email"], data["password"])
return self.json_message("ok")
@ -249,7 +249,7 @@ class CloudResendConfirmView(HomeAssistantView):
hass = request.app["hass"]
cloud = hass.data[DOMAIN]
with async_timeout.timeout(REQUEST_TIMEOUT):
async with async_timeout.timeout(REQUEST_TIMEOUT):
await cloud.auth.async_resend_email_confirm(data["email"])
return self.json_message("ok")
@ -268,7 +268,7 @@ class CloudForgotPasswordView(HomeAssistantView):
hass = request.app["hass"]
cloud = hass.data[DOMAIN]
with async_timeout.timeout(REQUEST_TIMEOUT):
async with async_timeout.timeout(REQUEST_TIMEOUT):
await cloud.auth.async_forgot_password(data["email"])
return self.json_message("ok")
@ -314,7 +314,7 @@ async def websocket_subscription(hass, connection, msg):
"""Handle request for account info."""
cloud = hass.data[DOMAIN]
try:
with async_timeout.timeout(REQUEST_TIMEOUT):
async with async_timeout.timeout(REQUEST_TIMEOUT):
data = await cloud_api.async_subscription_info(cloud)
except aiohttp.ClientError:
connection.send_error(
@ -353,7 +353,7 @@ async def websocket_update_prefs(hass, connection, msg):
if changes.get(PREF_ALEXA_REPORT_STATE):
alexa_config = await cloud.client.get_alexa_config()
try:
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
await alexa_config.async_get_access_token()
except asyncio.TimeoutError:
connection.send_error(
@ -574,7 +574,7 @@ async def alexa_sync(hass, connection, msg):
cloud = hass.data[DOMAIN]
alexa_config = await cloud.client.get_alexa_config()
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
try:
success = await alexa_config.async_sync_entities()
except alexa_errors.NoTokenAvailable:
@ -597,7 +597,7 @@ async def thingtalk_convert(hass, connection, msg):
"""Convert a query."""
cloud = hass.data[DOMAIN]
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
try:
connection.send_result(
msg["id"], await thingtalk.async_convert(cloud, msg["query"])

View file

@ -113,7 +113,7 @@ async def async_setup(hass, hass_config):
try:
session = aiohttp_client.async_get_clientsession(hass)
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
response = await session.get(url)
except (asyncio.TimeoutError, aiohttp.ClientError) as err:

View file

@ -104,7 +104,7 @@ class ComedHourlyPricingSensor(SensorEntity):
else:
url_string += "?type=currenthouraverage"
with async_timeout.timeout(60):
async with async_timeout.timeout(60):
response = await self.websession.get(url_string)
# The API responds with MIME type 'text/html'
text = await response.text()

View file

@ -66,7 +66,7 @@ async def get_coordinator(
return hass.data[DOMAIN]
async def async_get_cases():
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
return {
case.country: case
for case in await coronavirus.get_cases(

View file

@ -65,7 +65,7 @@ async def daikin_api_setup(hass, host, key, uuid, password):
session = hass.helpers.aiohttp_client.async_get_clientsession()
try:
with timeout(TIMEOUT):
async with timeout(TIMEOUT):
device = await Appliance.factory(
host, session, key=key, uuid=uuid, password=password
)

View file

@ -70,7 +70,7 @@ class FlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
password = None
try:
with timeout(TIMEOUT):
async with timeout(TIMEOUT):
device = await Appliance.factory(
host,
self.hass.helpers.aiohttp_client.async_get_clientsession(),

View file

@ -85,7 +85,7 @@ class DeconzFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
session = aiohttp_client.async_get_clientsession(self.hass)
try:
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
self.bridges = await deconz_discovery(session)
except (asyncio.TimeoutError, ResponseError):
@ -141,7 +141,7 @@ class DeconzFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
)
try:
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
api_key = await deconz_session.get_api_key()
except (ResponseError, RequestError, asyncio.TimeoutError):
@ -159,7 +159,7 @@ class DeconzFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
session = aiohttp_client.async_get_clientsession(self.hass)
try:
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
self.bridge_id = await deconz_get_bridge_id(
session, **self.deconz_config
)

View file

@ -276,7 +276,7 @@ async def get_gateway(
connection_status=async_connection_status_callback,
)
try:
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
await deconz.refresh_state()
return deconz

View file

@ -125,7 +125,7 @@ class DoorBirdCamera(DoorBirdEntity, Camera):
try:
websession = async_get_clientsession(self.hass)
with async_timeout.timeout(_TIMEOUT):
async with async_timeout.timeout(_TIMEOUT):
response = await websession.get(self._url)
self._last_image = await response.read()

View file

@ -319,7 +319,7 @@ async def async_wait_for_elk_to_sync(elk, timeout, conf_host):
elk.add_handler("login", login_status)
elk.add_handler("sync_complete", sync_complete)
try:
with async_timeout.timeout(timeout):
async with async_timeout.timeout(timeout):
await event.wait()
except asyncio.TimeoutError:
_LOGGER.error(

View file

@ -56,7 +56,7 @@ class FAADataUpdateCoordinator(DataUpdateCoordinator):
async def _async_update_data(self):
try:
with timeout(10):
async with timeout(10):
await self.data.update()
except ClientConnectionError as err:
raise UpdateFailed(err) from err

View file

@ -45,7 +45,7 @@ class FlickConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
)
try:
with async_timeout.timeout(60):
async with async_timeout.timeout(60):
token = await auth.async_get_access_token()
except asyncio.TimeoutError as err:
raise CannotConnect() from err

View file

@ -67,7 +67,7 @@ class FlickPricingSensor(SensorEntity):
if self._price and self._price.end_at >= utcnow():
return # Power price data is still valid
with async_timeout.timeout(60):
async with async_timeout.timeout(60):
self._price = await self._api.getPricing()
self._attributes[ATTR_START_AT] = self._price.start_at

View file

@ -41,7 +41,7 @@ class FlockNotificationService(BaseNotificationService):
_LOGGER.debug("Attempting to call Flock at %s", self._url)
try:
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
response = await self._session.post(self._url, json=payload)
result = await response.json()

View file

@ -72,7 +72,7 @@ async def _update_freedns(hass, session, url, auth_token):
params[auth_token] = ""
try:
with async_timeout.timeout(TIMEOUT):
async with async_timeout.timeout(TIMEOUT):
resp = await session.get(url, params=params)
body = await resp.text()

View file

@ -39,7 +39,7 @@ async def get_coordinator(
return hass.data[DOMAIN]
async def async_get_garages():
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
return {
garage.garage_name: garage
for garage in await garages_amsterdam.get_garages(

View file

@ -87,7 +87,7 @@ class GiosDataUpdateCoordinator(DataUpdateCoordinator):
async def _async_update_data(self) -> dict[str, Any]:
"""Update data via library."""
try:
with timeout(API_TIMEOUT):
async with timeout(API_TIMEOUT):
return cast(Dict[str, Any], await self.gios.async_update())
except (
ApiError,

View file

@ -37,7 +37,7 @@ class GiosFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
websession = async_get_clientsession(self.hass)
with timeout(API_TIMEOUT):
async with timeout(API_TIMEOUT):
gios = Gios(user_input[CONF_STATION_ID], websession)
await gios.async_update()

View file

@ -281,7 +281,7 @@ class GoogleCloudTTSProvider(Provider):
)
# pylint: enable=no-member
with async_timeout.timeout(10, loop=self.hass.loop):
async with async_timeout.timeout(10):
response = await self.hass.async_add_executor_job(
self._client.synthesize_speech, synthesis_input, voice, audio_config
)

View file

@ -65,7 +65,7 @@ async def _update_google_domains(hass, session, domain, user, password, timeout)
params = {"hostname": domain}
try:
with async_timeout.timeout(timeout):
async with async_timeout.timeout(timeout):
resp = await session.get(url, params=params)
body = await resp.text()

View file

@ -280,7 +280,7 @@ class HueBridge:
async def authenticate_bridge(hass: core.HomeAssistant, bridge: aiohue.Bridge):
"""Create a bridge object and verify authentication."""
try:
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
# Create username if we don't have one
if not bridge.username:
device_name = unicode_slug.slugify(

View file

@ -84,7 +84,7 @@ class HueFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
# Find / discover bridges
try:
with async_timeout.timeout(5):
async with async_timeout.timeout(5):
bridges = await discover_nupnp(
websession=aiohttp_client.async_get_clientsession(self.hass)
)

View file

@ -227,7 +227,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
async def async_safe_fetch(bridge, fetch_method):
"""Safely fetch data."""
try:
with async_timeout.timeout(4):
async with async_timeout.timeout(4):
return await bridge.async_request_call(fetch_method)
except aiohue.Unauthorized as err:
await bridge.handle_unauthorized_error()

View file

@ -61,7 +61,7 @@ class SensorManager:
async def async_update_data(self):
"""Update sensor data."""
try:
with async_timeout.timeout(4):
async with async_timeout.timeout(4):
return await self.bridge.async_request_call(
self.bridge.api.sensors.update
)

View file

@ -42,7 +42,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
config_port = config[CONF_PORT]
config_name = config[CONF_NAME]
try:
with async_timeout.timeout(PLATFORM_TIMEOUT):
async with async_timeout.timeout(PLATFORM_TIMEOUT):
api = await real_time_api(config_host, config_port)
except (IamMeterError, asyncio.TimeoutError) as err:
_LOGGER.error("Device is not ready")
@ -50,7 +50,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
async def async_update_data():
try:
with async_timeout.timeout(PLATFORM_TIMEOUT):
async with async_timeout.timeout(PLATFORM_TIMEOUT):
return await api.get_data()
except (IamMeterError, asyncio.TimeoutError) as err:
raise UpdateFailed from err

View file

@ -134,7 +134,7 @@ class ImapSensor(SensorEntity):
idle = await self._connection.idle_start()
await self._connection.wait_server_push()
self._connection.idle_done()
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
await idle
else:
self.async_write_ha_state()

View file

@ -142,7 +142,7 @@ async def async_get_api(hass):
async def async_get_location(hass, api, latitude, longitude):
"""Retrieve pyipma location, location name to be used as the entity name."""
with async_timeout.timeout(30):
async with async_timeout.timeout(30):
location = await Location.get(api, float(latitude), float(longitude))
_LOGGER.debug(
@ -172,7 +172,7 @@ class IPMAWeather(WeatherEntity):
@Throttle(MIN_TIME_BETWEEN_UPDATES)
async def async_update(self):
"""Update Condition and Forecast."""
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
new_observation = await self._location.observation(self._api)
new_forecast = await self._location.forecast(self._api)

View file

@ -89,7 +89,7 @@ async def validate_input(hass: core.HomeAssistant, data):
)
try:
with async_timeout.timeout(30):
async with async_timeout.timeout(30):
isy_conf_xml = await isy_conn.test_connection()
except ISYInvalidAuthError as error:
raise InvalidAuth from error

View file

@ -53,7 +53,7 @@ class KaiterraApiData:
"""Get the data from Kaiterra API."""
try:
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
data = await self._api.get_latest_sensor_readings(self._devices)
except (ClientResponseError, asyncio.TimeoutError):
_LOGGER.debug("Couldn't fetch data from Kaiterra API")

View file

@ -38,7 +38,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
try:
httpsession = async_get_clientsession(hass)
with async_timeout.timeout(timeout):
async with async_timeout.timeout(timeout):
scenes_resp = await httpsession.get(url, headers=headers)
except (asyncio.TimeoutError, aiohttp.ClientError):
@ -81,7 +81,7 @@ class LifxCloudScene(Scene):
try:
httpsession = async_get_clientsession(self.hass)
with async_timeout.timeout(self._timeout):
async with async_timeout.timeout(self._timeout):
await httpsession.put(url, headers=self._headers)
except (asyncio.TimeoutError, aiohttp.ClientError):

View file

@ -147,7 +147,7 @@ async def async_setup_entry(hass, entry):
return False
try:
with async_timeout.timeout(_TIMEOUT):
async with async_timeout.timeout(_TIMEOUT):
# Ensure the cameras property returns the same Camera objects for
# all devices. Performs implicit login and session validation.
await logi_circle.synchronize_cameras()

View file

@ -158,7 +158,7 @@ class LogiCircleFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
)
try:
with async_timeout.timeout(_TIMEOUT):
async with async_timeout.timeout(_TIMEOUT):
await logi_session.authorize(code)
except AuthorizationFailed:
(self.hass.data[DATA_FLOW_IMPL][DOMAIN][EXTERNAL_ERRORS]) = "invalid_auth"

View file

@ -250,7 +250,7 @@ class MailboxMediaView(MailboxView):
mailbox = self.get_mailbox(platform)
with suppress(asyncio.CancelledError, asyncio.TimeoutError):
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
try:
stream = await mailbox.async_get_media(msgid)
except StreamError as err:

View file

@ -145,7 +145,7 @@ async def mel_devices_setup(hass, token) -> list[MelCloudDevice]:
"""Query connected devices from MELCloud."""
session = hass.helpers.aiohttp_client.async_get_clientsession()
try:
with timeout(10):
async with timeout(10):
all_devices = await get_devices(
token,
session,

View file

@ -42,7 +42,7 @@ class FlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
)
try:
with timeout(10):
async with timeout(10):
if (acquired_token := token) is None:
acquired_token = await pymelcloud.login(
username,

View file

@ -299,7 +299,7 @@ class MicrosoftFace:
payload = None
try:
with async_timeout.timeout(self.timeout):
async with async_timeout.timeout(self.timeout):
response = await getattr(self.websession, method)(
url, data=payload, headers=headers, params=params
)

View file

@ -122,7 +122,7 @@ class MjpegCamera(Camera):
websession = async_get_clientsession(self.hass, verify_ssl=self._verify_ssl)
try:
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
response = await websession.get(self._still_image_url, auth=self._auth)
image = await response.read()

View file

@ -149,7 +149,7 @@ class MobileAppNotificationService(BaseNotificationService):
target_data["registration_info"] = reg_info
try:
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
response = await async_get_clientsession(self._hass).post(
push_url, json=target_data
)

View file

@ -18,7 +18,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: dict) -> bool:
"""Set up Mullvad VPN integration."""
async def async_get_mullvad_api_data():
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
api = await hass.async_add_executor_job(MullvadAPI)
return api.data

View file

@ -107,7 +107,7 @@ async def try_connect(
connect_task = None
try:
connect_task = asyncio.create_task(gateway.start())
with async_timeout.timeout(GATEWAY_READY_TIMEOUT):
async with async_timeout.timeout(GATEWAY_READY_TIMEOUT):
await gateway_ready.wait()
return True
except asyncio.TimeoutError:
@ -319,7 +319,7 @@ async def _gw_start(
# Gatways connected via mqtt doesn't send gateway ready message.
return
try:
with async_timeout.timeout(GATEWAY_READY_TIMEOUT):
async with async_timeout.timeout(GATEWAY_READY_TIMEOUT):
await gateway_ready.wait()
except asyncio.TimeoutError:
_LOGGER.warning(

View file

@ -100,7 +100,7 @@ class NAMDataUpdateCoordinator(DataUpdateCoordinator):
# Device firmware uses synchronous code and doesn't respond to http queries
# when reading data from sensors. The nettigo-air-quality library tries to
# get the data 4 times, so we use a longer than usual timeout here.
with async_timeout.timeout(30):
async with async_timeout.timeout(30):
data = await self.nam.async_update()
except (ApiError, ClientConnectorError, InvalidSensorData) as error:
raise UpdateFailed(error) from error

View file

@ -120,5 +120,5 @@ class NAMFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
# Device firmware uses synchronous code and doesn't respond to http queries
# when reading data from sensors. The nettigo-air-monitor library tries to get
# the data 4 times, so we use a longer than usual timeout here.
with async_timeout.timeout(30):
async with async_timeout.timeout(30):
return await nam.async_get_mac_address()

View file

@ -211,7 +211,7 @@ class NestFlowHandler(
if user_input is not None:
try:
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
tokens = await flow["convert_code"](user_input["code"])
return self._entry_from_tokens(
f"Nest (via {flow['name']})", flow, tokens
@ -228,7 +228,7 @@ class NestFlowHandler(
_LOGGER.exception("Unexpected error resolving code")
try:
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
url = await flow["gen_authorize_url"](self.flow_id)
except asyncio.TimeoutError:
return self.async_abort(reason="authorize_url_timeout")

View file

@ -96,7 +96,7 @@ async def _update_no_ip(
}
try:
with async_timeout.timeout(timeout):
async with async_timeout.timeout(timeout):
resp = await session.get(url, params=params, headers=headers)
body = await resp.text()

View file

@ -113,7 +113,7 @@ class OpenAlprCloudEntity(ImageProcessingAlprEntity):
body = {"image_bytes": str(b64encode(image), "utf-8")}
try:
with async_timeout.timeout(self.timeout):
async with async_timeout.timeout(self.timeout):
request = await websession.post(
OPENALPR_API_URL, params=params, data=body
)

View file

@ -73,7 +73,7 @@ class WeatherUpdateCoordinator(DataUpdateCoordinator):
async def _async_update_data(self):
data = {}
with async_timeout.timeout(20):
async with async_timeout.timeout(20):
try:
weather_response = await self._get_owm_weather()
data = self._convert_weather_response(weather_response)

View file

@ -93,7 +93,7 @@ class PointFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
errors["base"] = "follow_link"
try:
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
url = await self._get_authorization_url()
except asyncio.TimeoutError:
return self.async_abort(reason="authorize_url_timeout")

View file

@ -90,7 +90,7 @@ class PoolSenseDataUpdateCoordinator(DataUpdateCoordinator):
async def _async_update_data(self):
"""Update data via library."""
data = {}
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
try:
data = await self.poolsense.get_poolsense_data()
except (PoolSenseError) as error:

View file

@ -56,7 +56,7 @@ class ProwlNotificationService(BaseNotificationService):
session = async_get_clientsession(self._hass)
try:
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
response = await session.post(url, data=payload)
result = await response.text()

View file

@ -72,7 +72,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
async def handle_webhook(hass, webhook_id, request):
"""Handle incoming webhook POST with image files."""
try:
with async_timeout.timeout(5):
async with async_timeout.timeout(5):
data = dict(await request.post())
except (asyncio.TimeoutError, aiohttp.web.HTTPException) as error:
_LOGGER.error("Could not get information from POST <%s>", error)

View file

@ -50,7 +50,7 @@ async def async_get_type(hass, cloud_id, install_code, host):
)
try:
with async_timeout.timeout(30):
async with async_timeout.timeout(30):
meters = await hub.get_device_list()
except aioeagle.BadAuth as err:
raise InvalidAuth from err

View file

@ -210,7 +210,7 @@ class RestSwitch(SwitchEntity):
rendered_headers = render_templates(self._headers)
rendered_params = render_templates(self._params)
with async_timeout.timeout(self._timeout):
async with async_timeout.timeout(self._timeout):
req = await getattr(websession, self._method)(
self._resource,
auth=self._auth,
@ -236,7 +236,7 @@ class RestSwitch(SwitchEntity):
rendered_headers = render_templates(self._headers)
rendered_params = render_templates(self._params)
with async_timeout.timeout(self._timeout):
async with async_timeout.timeout(self._timeout):
req = await websession.get(
self._state_resource,
auth=self._auth,

View file

@ -270,7 +270,7 @@ async def async_setup(hass, config):
)
try:
with async_timeout.timeout(CONNECTION_TIMEOUT):
async with async_timeout.timeout(CONNECTION_TIMEOUT):
transport, protocol = await connection
except (

View file

@ -80,7 +80,7 @@ async def async_connect_or_timeout(hass, roomba):
"""Connect to vacuum."""
try:
name = None
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
_LOGGER.debug("Initialize connection to vacuum")
await hass.async_add_executor_job(roomba.connect)
while not roomba.roomba_connected or name is None:
@ -104,7 +104,7 @@ async def async_connect_or_timeout(hass, roomba):
async def async_disconnect_or_timeout(hass, roomba):
"""Disconnect to vacuum."""
_LOGGER.debug("Disconnect vacuum")
with async_timeout.timeout(3):
async with async_timeout.timeout(3):
await hass.async_add_executor_job(roomba.disconnect)
return True

View file

@ -91,7 +91,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
)
devices = []
try:
with async_timeout.timeout(TIMEOUT):
async with async_timeout.timeout(TIMEOUT):
for dev in await client.async_get_devices(_INITIAL_FETCH_FIELDS):
if config[CONF_ID] == ALL or dev["id"] in config[CONF_ID]:
devices.append(
@ -363,7 +363,7 @@ class SensiboClimate(ClimateEntity):
async def async_update(self):
"""Retrieve latest state."""
try:
with async_timeout.timeout(TIMEOUT):
async with async_timeout.timeout(TIMEOUT):
data = await self._client.async_get_device(self._id, _FETCH_FIELDS)
except (
aiohttp.client_exceptions.ClientError,
@ -389,7 +389,7 @@ class SensiboClimate(ClimateEntity):
async def _async_set_ac_state_property(self, name, value, assumed_state=False):
"""Set AC state."""
try:
with async_timeout.timeout(TIMEOUT):
async with async_timeout.timeout(TIMEOUT):
await self._client.async_set_ac_state_property(
self._id, name, value, self._ac_states, assumed_state
)

View file

@ -26,7 +26,7 @@ class CannotConnect(exceptions.HomeAssistantError):
async def async_connect_or_timeout(ayla_api: AylaApi) -> bool:
"""Connect to vacuum."""
try:
with async_timeout.timeout(API_TIMEOUT):
async with async_timeout.timeout(API_TIMEOUT):
_LOGGER.debug("Initialize connection to Ayla networks API")
await ayla_api.async_sign_in()
except SharkIqAuthError:
@ -71,10 +71,11 @@ async def async_setup_entry(hass, config_entry):
async def async_disconnect_or_timeout(coordinator: SharkIqUpdateCoordinator):
"""Disconnect to vacuum."""
_LOGGER.debug("Disconnecting from Ayla Api")
with async_timeout.timeout(5), suppress(
SharkIqAuthError, SharkIqAuthExpiringError, SharkIqNotAuthedError
):
await coordinator.ayla_api.async_sign_out()
async with async_timeout.timeout(5):
with suppress(
SharkIqAuthError, SharkIqAuthExpiringError, SharkIqNotAuthedError
):
await coordinator.ayla_api.async_sign_out()
async def async_update_options(hass, config_entry):

View file

@ -27,7 +27,7 @@ async def validate_input(hass: core.HomeAssistant, data):
)
try:
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
_LOGGER.debug("Initialize connection to Ayla networks API")
await ayla_api.async_sign_in()
except (asyncio.TimeoutError, aiohttp.ClientError) as errors:

View file

@ -54,7 +54,7 @@ class SharkIqUpdateCoordinator(DataUpdateCoordinator):
"""Asynchronously update the data for a single vacuum."""
dsn = sharkiq.serial_number
_LOGGER.debug("Updating sharkiq data for device DSN %s", dsn)
with timeout(API_TIMEOUT):
async with timeout(API_TIMEOUT):
await sharkiq.async_update()
async def _async_update_data(self) -> bool:

View file

@ -125,7 +125,7 @@ class SmhiWeather(WeatherEntity):
async def async_update(self) -> None:
"""Refresh the forecast data from SMHI weather API."""
try:
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
self._forecasts = await self.get_weather_forecast()
self._fail_count = 0

View file

@ -972,7 +972,7 @@ class SonosSpeaker:
return True
try:
with async_timeout.timeout(5):
async with async_timeout.timeout(5):
while not _test_groups(groups):
await hass.data[DATA_SONOS].topology_condition.wait()
except asyncio.TimeoutError:

View file

@ -44,7 +44,7 @@ async def async_setup_entry(hass, entry, async_add_entities):
# Fetch srp_energy data
start_date = datetime.now() + timedelta(days=-1)
end_date = datetime.now()
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
hourly_usage = await hass.async_add_executor_job(
api.usage,
start_date,

View file

@ -193,7 +193,7 @@ class StartcaData:
"""Get the Start.ca bandwidth data from the web service."""
_LOGGER.debug("Updating Start.ca usage data")
url = f"https://www.start.ca/support/usage/api?key={self.api_key}"
with async_timeout.timeout(REQUEST_TIMEOUT):
async with async_timeout.timeout(REQUEST_TIMEOUT):
req = await self.websession.get(url)
if req.status != HTTPStatus.OK:
_LOGGER.error("Request failed with status: %u", req.status)

View file

@ -64,7 +64,7 @@ async def get_integration_info(
):
"""Get integration system health."""
try:
with async_timeout.timeout(INFO_CALLBACK_TIMEOUT):
async with async_timeout.timeout(INFO_CALLBACK_TIMEOUT):
data = await registration.info_callback(hass)
except asyncio.TimeoutError:
data = {"error": {"type": "failed", "error": "timeout"}}

View file

@ -106,7 +106,7 @@ class TadoDeviceScanner(DeviceScanner):
last_results = []
try:
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
# Format the URL here, so we can log the template URL if
# anything goes wrong without exposing username and password.
url = self.tadoapiurl.format(

View file

@ -92,7 +92,7 @@ class FlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
errors["base"] = "invalid_auth"
try:
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
auth_url = await self.hass.async_add_executor_job(self._get_auth_url)
if not auth_url:
return self.async_abort(reason="unknown_authorize_url_generation")

View file

@ -124,7 +124,7 @@ class TtnDataStorage:
"""Get the current state from The Things Network Data Storage."""
try:
session = async_get_clientsession(self._hass)
with async_timeout.timeout(DEFAULT_TIMEOUT):
async with async_timeout.timeout(DEFAULT_TIMEOUT):
response = await session.get(self._url, headers=self._headers)
except (asyncio.TimeoutError, aiohttp.ClientError):

View file

@ -174,7 +174,7 @@ async def authenticate(
api_factory = await APIFactory.init(host, psk_id=identity)
try:
with async_timeout.timeout(5):
async with async_timeout.timeout(5):
key = await api_factory.generate_psk(security_code)
except RequestError as err:
raise AuthError("invalid_security_code") from err

View file

@ -419,7 +419,7 @@ class UniFiController:
async def async_reconnect(self) -> None:
"""Try to reconnect UniFi session."""
try:
with async_timeout.timeout(5):
async with async_timeout.timeout(5):
await self.api.login()
self.api.start_websocket()
@ -488,7 +488,7 @@ async def get_controller(
)
try:
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
await controller.check_unifi_os()
await controller.login()
return controller

View file

@ -125,7 +125,7 @@ async def get_newest_version(hass):
"""Get the newest Home Assistant version."""
session = async_get_clientsession(hass)
with async_timeout.timeout(30):
async with async_timeout.timeout(30):
req = await session.get(UPDATER_URL)
try:

View file

@ -70,7 +70,7 @@ async def async_http_request(hass, uri):
"""Perform actual request."""
try:
session = hass.helpers.aiohttp_client.async_get_clientsession(hass)
with async_timeout.timeout(REQUEST_TIMEOUT):
async with async_timeout.timeout(REQUEST_TIMEOUT):
req = await session.get(uri)
if req.status != HTTPStatus.OK:
return {"error": req.status}

View file

@ -196,7 +196,7 @@ class VoiceRSSProvider(Provider):
form_data["hl"] = language
try:
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
request = await websession.post(VOICERSS_API_URL, data=form_data)
if request.status != HTTPStatus.OK:

View file

@ -176,7 +176,7 @@ class WebSocketHandler:
# Auth Phase
try:
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
msg = await wsock.receive()
except asyncio.TimeoutError as err:
disconnect_warn = "Did not receive auth message within 10 seconds"

View file

@ -85,7 +85,7 @@ class WorxLandroidSensor(SensorEntity):
try:
session = async_get_clientsession(self.hass)
with async_timeout.timeout(self.timeout):
async with async_timeout.timeout(self.timeout):
auth = aiohttp.helpers.BasicAuth("admin", self.pin)
mower_response = await session.get(self.url, auth=auth)
except (asyncio.TimeoutError, aiohttp.ClientError):

View file

@ -121,7 +121,7 @@ class YandexSpeechKitProvider(Provider):
options = options or {}
try:
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
url_param = {
"text": message,
"lang": actual_language,

View file

@ -25,7 +25,7 @@ import attr
import voluptuous as vol
import yarl
from homeassistant import block_async_io, loader, util
from homeassistant import async_timeout_backcompat, block_async_io, loader, util
from homeassistant.const import (
ATTR_DOMAIN,
ATTR_FRIENDLY_NAME,
@ -82,7 +82,7 @@ STAGE_1_SHUTDOWN_TIMEOUT = 100
STAGE_2_SHUTDOWN_TIMEOUT = 60
STAGE_3_SHUTDOWN_TIMEOUT = 30
async_timeout_backcompat.enable()
block_async_io.enable()
T = TypeVar("T")

View file

@ -123,7 +123,7 @@ async def async_aiohttp_proxy_web(
) -> web.StreamResponse | None:
"""Stream websession request to aiohttp web response."""
try:
with async_timeout.timeout(timeout):
async with async_timeout.timeout(timeout):
req = await web_coro
except asyncio.CancelledError:
@ -164,7 +164,7 @@ async def async_aiohttp_proxy_stream(
# Suppressing something went wrong fetching data, closed connection
with suppress(asyncio.TimeoutError, aiohttp.ClientError):
while hass.is_running:
with async_timeout.timeout(timeout):
async with async_timeout.timeout(timeout):
data = await stream.read(buffer_size)
if not data:

View file

@ -270,7 +270,7 @@ class AbstractOAuth2FlowHandler(config_entries.ConfigFlow, metaclass=ABCMeta):
return self.async_external_step_done(next_step_id="creation")
try:
with async_timeout.timeout(10):
async with async_timeout.timeout(10):
url = await self.flow_impl.async_generate_authorize_url(self.flow_id)
except asyncio.TimeoutError:
return self.async_abort(reason="authorize_url_timeout")

View file

@ -476,7 +476,10 @@ class _ScriptRun:
def async_script_wait(entity_id, from_s, to_s):
"""Handle script after template condition is true."""
wait_var = self._variables["wait"]
wait_var["remaining"] = to_context.remaining if to_context else timeout
if to_context and to_context.deadline:
wait_var["remaining"] = to_context.deadline - self._hass.loop.time()
else:
wait_var["remaining"] = timeout
wait_var["completed"] = True
done.set()
@ -777,7 +780,10 @@ class _ScriptRun:
async def async_done(variables, context=None):
wait_var = self._variables["wait"]
wait_var["remaining"] = to_context.remaining if to_context else timeout
if to_context and to_context.deadline:
wait_var["remaining"] = to_context.deadline - self._hass.loop.time()
else:
wait_var["remaining"] = timeout
wait_var["trigger"] = variables["trigger"]
done.set()

View file

@ -1,11 +1,11 @@
PyJWT==2.1.0
PyNaCl==1.4.0
aiodiscover==1.4.5
aiohttp==3.7.4.post0
aiohttp==3.8.0
aiohttp_cors==0.7.0
astral==2.2
async-upnp-client==0.22.11
async_timeout==3.0.1
async_timeout==4.0.0
attrs==21.2.0
awesomeversion==21.10.1
backports.zoneinfo;python_version<"3.9"

View file

@ -1,9 +1,9 @@
-c homeassistant/package_constraints.txt
# Home Assistant Core
aiohttp==3.7.4.post0
aiohttp==3.8.0
astral==2.2
async_timeout==3.0.1
async_timeout==4.0.0
attrs==21.2.0
awesomeversion==21.10.1
backports.zoneinfo;python_version<"3.9"

View file

@ -32,9 +32,9 @@ PROJECT_URLS = {
PACKAGES = find_packages(exclude=["tests", "tests.*"])
REQUIRES = [
"aiohttp==3.7.4.post0",
"aiohttp==3.8.0",
"astral==2.2",
"async_timeout==3.0.1",
"async_timeout==4.0.0",
"attrs==21.2.0",
"awesomeversion==21.10.1",
'backports.zoneinfo;python_version<"3.9"',

Some files were not shown because too many files have changed in this diff Show more