Skip to content

Commit

Permalink
Retry Nanoleaf requests (#7)
Browse files Browse the repository at this point in the history
Implement three retries for all requests.
  • Loading branch information
asymmetricia authored Dec 9, 2022
1 parent 7cb6f2f commit 4372e32
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 12 deletions.
35 changes: 24 additions & 11 deletions aionanoleaf/nanoleaf.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
ClientResponse,
ClientSession,
ClientTimeout,
ServerDisconnectedError,
ClientConnectionError,
)

Expand Down Expand Up @@ -67,12 +66,14 @@ def __init__(
host: str,
auth_token: str | None = None,
port: int = 16021,
retries: int = 3,
) -> None:
"""Initialize the Nanoleaf."""
self._session = session
self._host = host
self._auth_token = auth_token
self._port = port
self._retries = 3

@property
def host(self) -> str:
Expand Down Expand Up @@ -223,20 +224,32 @@ async def _request(
"""Make an authorized request to Nanoleaf with an auth_token."""
url = f"{self._api_url}/{self.auth_token}/{path}"
json_data = json.dumps(data)
try:
err = None
# try self._retries times and only then raise an exception if we failed
for attempt in range(self._retries):
try:
resp = await self._session.request(
method, url, data=json_data, timeout=self._REQUEST_TIMEOUT
)
except ServerDisconnectedError:
# Retry request once if the device disconnected
resp = await self._session.request(
method, url, data=json_data, timeout=self._REQUEST_TIMEOUT
)
except ClientConnectionError as err:
raise Unavailable from err
except asyncio.TimeoutError as err:
raise Unavailable from err
# it worked (or 401, but that's a hard fail), so clear any
# previous error
err = None
break
except Exception as e:
err = e

# did it work after retries?
if err is not None:
# no. we had an error; perform desired error handling (converting
# certain exceptions to Unavailable) and otherwise let it percolate
# upward.
try:
raise err
except ClientConnectionError as err:
raise Unavailable from err
except asyncio.TimeoutError as err:
raise Unavailable from err

if resp.status == 401:
raise InvalidToken
resp.raise_for_status()
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

setup(
name="aionanoleaf",
version="0.2.0",
version="0.2.1",
author="Milan Meulemans",
author_email="[email protected]",
description="Async Python package for the Nanoleaf API",
Expand Down

0 comments on commit 4372e32

Please sign in to comment.