Use builtin TimeoutError [socket.timeout] (#109704)

This commit is contained in:
Marc Mueller 2024-02-05 18:46:11 +01:00 committed by GitHub
parent 46f8fb3ac1
commit ed7307cdaf
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
16 changed files with 19 additions and 43 deletions

View File

@ -2,7 +2,6 @@
from __future__ import annotations from __future__ import annotations
import logging import logging
import socket
from pyblackbird import get_blackbird from pyblackbird import get_blackbird
from serial import SerialException from serial import SerialException
@ -93,7 +92,7 @@ def setup_platform(
try: try:
blackbird = get_blackbird(host, False) blackbird = get_blackbird(host, False)
connection = host connection = host
except socket.timeout: except TimeoutError:
_LOGGER.error("Error connecting to the Blackbird controller") _LOGGER.error("Error connecting to the Blackbird controller")
return return

View File

@ -2,7 +2,6 @@
from __future__ import annotations from __future__ import annotations
import logging import logging
import socket
from ssl import SSLError from ssl import SSLError
from deluge_client.client import DelugeRPCClient from deluge_client.client import DelugeRPCClient
@ -40,11 +39,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
api.web_port = entry.data[CONF_WEB_PORT] api.web_port = entry.data[CONF_WEB_PORT]
try: try:
await hass.async_add_executor_job(api.connect) await hass.async_add_executor_job(api.connect)
except ( except (ConnectionRefusedError, TimeoutError, SSLError) as ex:
ConnectionRefusedError,
socket.timeout,
SSLError,
) as ex:
raise ConfigEntryNotReady("Connection to Deluge Daemon failed") from ex raise ConfigEntryNotReady("Connection to Deluge Daemon failed") from ex
except Exception as ex: # pylint:disable=broad-except except Exception as ex: # pylint:disable=broad-except
if type(ex).__name__ == "BadLoginError": if type(ex).__name__ == "BadLoginError":

View File

@ -2,7 +2,6 @@
from __future__ import annotations from __future__ import annotations
from collections.abc import Mapping from collections.abc import Mapping
import socket
from ssl import SSLError from ssl import SSLError
from typing import Any from typing import Any
@ -91,11 +90,7 @@ class DelugeFlowHandler(ConfigFlow, domain=DOMAIN):
) )
try: try:
await self.hass.async_add_executor_job(api.connect) await self.hass.async_add_executor_job(api.connect)
except ( except (ConnectionRefusedError, TimeoutError, SSLError):
ConnectionRefusedError,
socket.timeout,
SSLError,
):
return "cannot_connect" return "cannot_connect"
except Exception as ex: # pylint:disable=broad-except except Exception as ex: # pylint:disable=broad-except
if type(ex).__name__ == "BadLoginError": if type(ex).__name__ == "BadLoginError":

View File

@ -2,7 +2,6 @@
from __future__ import annotations from __future__ import annotations
from datetime import timedelta from datetime import timedelta
import socket
from ssl import SSLError from ssl import SSLError
from typing import Any from typing import Any
@ -52,7 +51,7 @@ class DelugeDataUpdateCoordinator(
) )
except ( except (
ConnectionRefusedError, ConnectionRefusedError,
socket.timeout, TimeoutError,
SSLError, SSLError,
FailedToReconnectException, FailedToReconnectException,
) as ex: ) as ex:

View File

@ -1,6 +1,5 @@
"""Support for Ebusd daemon for communication with eBUS heating systems.""" """Support for Ebusd daemon for communication with eBUS heating systems."""
import logging import logging
import socket
import ebusdpy import ebusdpy
import voluptuous as vol import voluptuous as vol
@ -80,7 +79,7 @@ def setup(hass: HomeAssistant, config: ConfigType) -> bool:
_LOGGER.debug("Ebusd integration setup completed") _LOGGER.debug("Ebusd integration setup completed")
return True return True
except (socket.timeout, OSError): except (TimeoutError, OSError):
return False return False

View File

@ -1,7 +1,6 @@
"""Config flow to configure the LG Soundbar integration.""" """Config flow to configure the LG Soundbar integration."""
import logging import logging
from queue import Empty, Full, Queue from queue import Empty, Full, Queue
import socket
import temescal import temescal
import voluptuous as vol import voluptuous as vol
@ -60,7 +59,7 @@ def test_connect(host, port):
details["uuid"] = uuid_q.get(timeout=QUEUE_TIMEOUT) details["uuid"] = uuid_q.get(timeout=QUEUE_TIMEOUT)
except Empty: except Empty:
pass pass
except socket.timeout as err: except TimeoutError as err:
raise ConnectionError(f"Connection timeout with server: {host}:{port}") from err raise ConnectionError(f"Connection timeout with server: {host}:{port}") from err
except OSError as err: except OSError as err:
raise ConnectionError(f"Cannot resolve hostname: {host}") from err raise ConnectionError(f"Cannot resolve hostname: {host}") from err

View File

@ -1,6 +1,5 @@
"""Support for the MAX! Cube LAN Gateway.""" """Support for the MAX! Cube LAN Gateway."""
import logging import logging
from socket import timeout
from threading import Lock from threading import Lock
import time import time
@ -65,7 +64,7 @@ def setup(hass: HomeAssistant, config: ConfigType) -> bool:
try: try:
cube = MaxCube(host, port, now=now) cube = MaxCube(host, port, now=now)
hass.data[DATA_KEY][host] = MaxCubeHandle(cube, scan_interval) hass.data[DATA_KEY][host] = MaxCubeHandle(cube, scan_interval)
except timeout as ex: except TimeoutError as ex:
_LOGGER.error("Unable to connect to Max!Cube gateway: %s", str(ex)) _LOGGER.error("Unable to connect to Max!Cube gateway: %s", str(ex))
persistent_notification.create( persistent_notification.create(
hass, hass,
@ -108,7 +107,7 @@ class MaxCubeHandle:
try: try:
self.cube.update() self.cube.update()
except timeout: except TimeoutError:
_LOGGER.error("Max!Cube connection failed") _LOGGER.error("Max!Cube connection failed")
return False return False

View File

@ -2,7 +2,6 @@
from __future__ import annotations from __future__ import annotations
import logging import logging
import socket
from typing import Any from typing import Any
from maxcube.device import ( from maxcube.device import (
@ -152,7 +151,7 @@ class MaxCubeClimate(ClimateEntity):
with self._cubehandle.mutex: with self._cubehandle.mutex:
try: try:
self._cubehandle.cube.set_temperature_mode(self._device, temp, mode) self._cubehandle.cube.set_temperature_mode(self._device, temp, mode)
except (socket.timeout, OSError): except (TimeoutError, OSError):
_LOGGER.error("Setting HVAC mode failed") _LOGGER.error("Setting HVAC mode failed")
@property @property

View File

@ -3,7 +3,6 @@ from __future__ import annotations
from datetime import timedelta from datetime import timedelta
import logging import logging
import socket
import ssl import ssl
from typing import Any from typing import Any
@ -227,7 +226,7 @@ class MikrotikData:
except ( except (
librouteros.exceptions.ConnectionClosed, librouteros.exceptions.ConnectionClosed,
OSError, OSError,
socket.timeout, TimeoutError,
) as api_error: ) as api_error:
_LOGGER.error("Mikrotik %s connection error %s", self._host, api_error) _LOGGER.error("Mikrotik %s connection error %s", self._host, api_error)
# try to reconnect # try to reconnect
@ -330,7 +329,7 @@ def get_api(entry: dict[str, Any]) -> librouteros.Api:
except ( except (
librouteros.exceptions.LibRouterosError, librouteros.exceptions.LibRouterosError,
OSError, OSError,
socket.timeout, TimeoutError,
) as api_error: ) as api_error:
_LOGGER.error("Mikrotik %s error: %s", entry[CONF_HOST], api_error) _LOGGER.error("Mikrotik %s error: %s", entry[CONF_HOST], api_error)
if "invalid user name or password" in str(api_error): if "invalid user name or password" in str(api_error):

View File

@ -2,7 +2,6 @@
import asyncio import asyncio
from datetime import timedelta from datetime import timedelta
import logging import logging
from socket import timeout
from typing import Any from typing import Any
from motionblinds import DEVICE_TYPES_WIFI, ParseException from motionblinds import DEVICE_TYPES_WIFI, ParseException
@ -50,7 +49,7 @@ class DataUpdateCoordinatorMotionBlinds(DataUpdateCoordinator):
"""Fetch data from gateway.""" """Fetch data from gateway."""
try: try:
self._gateway.Update() self._gateway.Update()
except (timeout, ParseException): except (TimeoutError, ParseException):
# let the error be logged and handled by the motionblinds library # let the error be logged and handled by the motionblinds library
return {ATTR_AVAILABLE: False} return {ATTR_AVAILABLE: False}
@ -65,7 +64,7 @@ class DataUpdateCoordinatorMotionBlinds(DataUpdateCoordinator):
blind.Update() blind.Update()
else: else:
blind.Update_trigger() blind.Update_trigger()
except (timeout, ParseException): except (TimeoutError, ParseException):
# let the error be logged and handled by the motionblinds library # let the error be logged and handled by the motionblinds library
return {ATTR_AVAILABLE: False} return {ATTR_AVAILABLE: False}

View File

@ -50,7 +50,7 @@ class ConnectMotionGateway:
try: try:
# update device info and get the connected sub devices # update device info and get the connected sub devices
await self._hass.async_add_executor_job(self.update_gateway) await self._hass.async_add_executor_job(self.update_gateway)
except socket.timeout: except TimeoutError:
_LOGGER.error( _LOGGER.error(
"Timeout trying to connect to Motion Gateway with host %s", host "Timeout trying to connect to Motion Gateway with host %s", host
) )

View File

@ -5,7 +5,6 @@ from collections.abc import Callable
from datetime import timedelta from datetime import timedelta
import functools import functools
import logging import logging
import socket
import threading import threading
from typing import Any, ParamSpec from typing import Any, ParamSpec
@ -75,7 +74,7 @@ def setup(hass: HomeAssistant, config: ConfigType) -> bool:
try: try:
pilight_client = pilight.Client(host=host, port=port) pilight_client = pilight.Client(host=host, port=port)
except (OSError, socket.timeout) as err: except (OSError, TimeoutError) as err:
_LOGGER.error("Unable to connect to %s on port %s: %s", host, port, err) _LOGGER.error("Unable to connect to %s on port %s: %s", host, port, err)
return False return False

View File

@ -1,8 +1,6 @@
"""Support for controlling projector via the PJLink protocol.""" """Support for controlling projector via the PJLink protocol."""
from __future__ import annotations from __future__ import annotations
import socket
from pypjlink import MUTE_AUDIO, Projector from pypjlink import MUTE_AUDIO, Projector
from pypjlink.projector import ProjectorError from pypjlink.projector import ProjectorError
import voluptuous as vol import voluptuous as vol
@ -116,7 +114,7 @@ class PjLinkDevice(MediaPlayerEntity):
try: try:
projector = Projector.from_address(self._host, self._port) projector = Projector.from_address(self._host, self._port)
projector.authenticate(self._password) projector.authenticate(self._password)
except (socket.timeout, OSError) as err: except (TimeoutError, OSError) as err:
self._attr_available = False self._attr_available = False
raise ProjectorError(ERR_PROJECTOR_UNAVAILABLE) from err raise ProjectorError(ERR_PROJECTOR_UNAVAILABLE) from err

View File

@ -2,7 +2,6 @@
from __future__ import annotations from __future__ import annotations
from collections.abc import Coroutine from collections.abc import Coroutine
from socket import timeout
from typing import Any, TypeVar from typing import Any, TypeVar
from urllib.error import URLError from urllib.error import URLError
@ -32,7 +31,7 @@ async def _async_call_or_raise_not_ready(
except RadiothermTstatError as ex: except RadiothermTstatError as ex:
msg = f"{host} was busy (invalid value returned): {ex}" msg = f"{host} was busy (invalid value returned): {ex}"
raise ConfigEntryNotReady(msg) from ex raise ConfigEntryNotReady(msg) from ex
except timeout as ex: except TimeoutError as ex:
msg = f"{host} timed out waiting for a response: {ex}" msg = f"{host} timed out waiting for a response: {ex}"
raise ConfigEntryNotReady(msg) from ex raise ConfigEntryNotReady(msg) from ex
except (OSError, URLError) as ex: except (OSError, URLError) as ex:

View File

@ -2,7 +2,6 @@
from __future__ import annotations from __future__ import annotations
import logging import logging
from socket import timeout
from typing import Any from typing import Any
from urllib.error import URLError from urllib.error import URLError
@ -30,7 +29,7 @@ async def validate_connection(hass: HomeAssistant, host: str) -> RadioThermInitD
"""Validate the connection.""" """Validate the connection."""
try: try:
return await async_get_init_data(hass, host) return await async_get_init_data(hass, host)
except (timeout, RadiothermTstatError, URLError, OSError) as ex: except (TimeoutError, RadiothermTstatError, URLError, OSError) as ex:
raise CannotConnect(f"Failed to connect to {host}: {ex}") from ex raise CannotConnect(f"Failed to connect to {host}: {ex}") from ex

View File

@ -3,7 +3,6 @@ from __future__ import annotations
from datetime import timedelta from datetime import timedelta
import logging import logging
from socket import timeout
from urllib.error import URLError from urllib.error import URLError
from radiotherm.validate import RadiothermTstatError from radiotherm.validate import RadiothermTstatError
@ -39,7 +38,7 @@ class RadioThermUpdateCoordinator(DataUpdateCoordinator[RadioThermUpdate]):
except RadiothermTstatError as ex: except RadiothermTstatError as ex:
msg = f"{self._description} was busy (invalid value returned): {ex}" msg = f"{self._description} was busy (invalid value returned): {ex}"
raise UpdateFailed(msg) from ex raise UpdateFailed(msg) from ex
except timeout as ex: except TimeoutError as ex:
msg = f"{self._description}) timed out waiting for a response: {ex}" msg = f"{self._description}) timed out waiting for a response: {ex}"
raise UpdateFailed(msg) from ex raise UpdateFailed(msg) from ex
except (OSError, URLError) as ex: except (OSError, URLError) as ex: