|
2 | 2 |
|
3 | 3 | __version__ = "0.2.0" |
4 | 4 |
|
| 5 | +import asyncio |
5 | 6 | import json |
6 | 7 | import logging |
7 | 8 | import re |
8 | 9 | from typing import Any |
9 | 10 | from urllib.parse import urlencode |
10 | 11 |
|
| 12 | +import aiodns |
11 | 13 | import aiohttp |
12 | 14 |
|
13 | 15 | LOGGER = logging.getLogger(__name__) |
@@ -109,12 +111,33 @@ async def stromer_update(self) -> None: |
109 | 111 | LOGGER.error("Stromer error: api call failed 10 times, cowardly failing") |
110 | 112 | raise ApiError |
111 | 113 |
|
| 114 | + async def stromer_api_debouncer(self, url: str, timeout: int = 10, retries: int = 10, delay: int = 10) -> aiohttp.ClientResponse: |
| 115 | + """Debounce API-request to leverage DNS issues.""" |
| 116 | + for attempt in range(retries): |
| 117 | + try: |
| 118 | + log = f"Attempt {attempt + 1}/{retries} to interface with Stromer on {url}" |
| 119 | + LOGGER.debug(log) |
| 120 | + res = await self._websession.get(url, timeout=timeout) |
| 121 | + res.raise_for_status() |
| 122 | + return res |
| 123 | + except (aiodns.error.DNSError, aiohttp.ClientError, TimeoutError) as e: |
| 124 | + log = f"Error getting Stromer API (attempt {attempt + 1}/{retries}): {e}" |
| 125 | + LOGGER.warning(log) |
| 126 | + if attempt < retries - 1: |
| 127 | + log = f"Retrying in {delay} seconds..." |
| 128 | + LOGGER.warning(log) |
| 129 | + await asyncio.sleep(delay) |
| 130 | + else: |
| 131 | + log = f"Failed to get to Stromer API after {retries} attempts." |
| 132 | + LOGGER.error(log) |
| 133 | + raise # Re-raise the last exception if all retries fail |
| 134 | + |
112 | 135 | async def stromer_get_code(self) -> None: |
113 | 136 | """Retrieve authorization code from API.""" |
114 | 137 | url = f"{self.base_url}/mobile/v4/login/" |
115 | 138 | if self._api_version == "v3": |
116 | 139 | url = f"{self.base_url}/users/login/" |
117 | | - res = await self._websession.get(url) |
| 140 | + res = await self.stromer_api_debouncer(url) |
118 | 141 | try: |
119 | 142 | cookie = res.headers.get("Set-Cookie") |
120 | 143 | pattern = "=(.*?);" |
|
0 commit comments