| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import logging |
| 4 |
from typing import TYPE_CHECKING, Any, Callable, TypeVar, cast |
| 5 |
|
| 6 |
from .const import DEFAULT_RETRIES |
| 7 |
|
| 8 |
_LOGGER = logging.getLogger(__name__) |
| 9 |
|
| 10 |
|
| 11 |
WrapFuncType = TypeVar("WrapFuncType", bound=Callable[..., Any]) |
| 12 |
|
| 13 |
|
| 14 |
if TYPE_CHECKING: |
| 15 |
from .device import WifiLedBulb |
| 16 |
|
| 17 |
|
| 18 |
def _socket_retry(attempts: int = DEFAULT_RETRIES) -> WrapFuncType: |
| 19 |
"""Define a wrapper to retry on socket failures.""" |
| 20 |
|
| 21 |
def decorator_retry(func: WrapFuncType) -> WrapFuncType: |
| 22 |
def _retry_wrap( |
| 23 |
self: WifiLedBulb, |
| 24 |
*args: Any, |
| 25 |
retry: int = attempts, |
| 26 |
**kwargs: Any, |
| 27 |
) -> Any: |
| 28 |
attempts_remaining = retry + 1 |
| 29 |
while attempts_remaining: |
| 30 |
attempts_remaining -= 1 |
| 31 |
try: |
| 32 |
ret = func(self, *args, **kwargs) |
| 33 |
self.set_available(f"{func.__name__} was successful") |
| 34 |
return ret |
| 35 |
except OSError as ex: |
| 36 |
_LOGGER.debug( |
| 37 |
"%s: socket error while calling %s: %s", self.ipaddr, func, ex |
| 38 |
) |
| 39 |
if attempts_remaining: |
| 40 |
continue |
| 41 |
self.set_unavailable(f"{func.__name__} failed: {ex}") |
| 42 |
self.close() |
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
raise |
| 47 |
|
| 48 |
|
| 49 |
return cast("WrapFuncType", _retry_wrap) |
| 50 |
|
| 51 |
return cast("WrapFuncType", decorator_retry) |