Skip to content

Commit

Permalink
Enhanced HafeleClient with timeout and retry logic
Browse files Browse the repository at this point in the history
 - Added a timeout parameter to HafeleClient initialization.
 - Updated retry_with_backoff decorator with base_delay, max_delay, and jitter_range for improved retry logic.
 - Adjusted total_delay calculation to ensure it respects the base_delay.
 - Modified client initialization in config_flow to include a timeout.
  • Loading branch information
QNimbus committed Nov 4, 2024
1 parent cbe85e8 commit bda5311
Show file tree
Hide file tree
Showing 4 changed files with 4 additions and 4 deletions.
2 changes: 1 addition & 1 deletion custom_components/haefele_connect_mesh/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:

# Create API client
session = async_get_clientsession(hass)
client = HafeleClient(entry.data["api_token"], session)
client = HafeleClient(entry.data["api_token"], session, timeout=10)

# Store client for use by platforms
hass.data[DOMAIN][entry.entry_id] = {
Expand Down
2 changes: 1 addition & 1 deletion custom_components/haefele_connect_mesh/api/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def __init__(
}
logger.debug("Initialized HafeleClient with base URL: %s", self._base_url)

@retry_with_backoff(max_delay=8.0)
@retry_with_backoff(base_delay=0.5, max_delay=4.0, jitter_range=0.5)
async def _request(
self, method: str, endpoint: str, timeout: Optional[int] = None, **kwargs: Any
) -> aiohttp.ClientResponse:
Expand Down
2 changes: 1 addition & 1 deletion custom_components/haefele_connect_mesh/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ async def _validate_api_token(self, api_token: str) -> tuple[bool, str | None]:
Tuple of (success, error_message)
"""
session = async_get_clientsession(self.hass)
client = HafeleClient(api_token, session)
client = HafeleClient(api_token, session, timeout=6)

try:
networks = await client.get_networks()
Expand Down
2 changes: 1 addition & 1 deletion custom_components/haefele_connect_mesh/utils/retry.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ async def wrapper(*args: Any, **kwargs: Any) -> T:
delay = min(base_delay * (2 ** (attempt - 1)), max_delay)
# Add random jitter
jitter = random.uniform(-jitter_range, jitter_range)
total_delay = max(delay + jitter, 0.1)
total_delay = max(delay + jitter, base_delay)

logger.debug(
"Retrying request after %.2f seconds (attempt %d/%d)",
Expand Down

0 comments on commit bda5311

Please sign in to comment.