8000 Fix P100 errors on multi-requests by sdb9696 · Pull Request #930 · python-kasa/python-kasa · GitHub
[go: up one dir, main page]

Skip to content

Fix P100 errors on multi-requests #930

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Jun 4, 2024
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions kasa/httpclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import asyncio
import logging
import time
from typing import Any, Dict

import aiohttp
Expand All @@ -28,12 +29,18 @@ def get_cookie_jar() -> aiohttp.CookieJar:
class HttpClient:
"""HttpClient Class."""

# Time to wait between requests if getting client os errors
WAIT_TIME = 0.5

def __init__(self, config: DeviceConfig) -> None:
self._config = config
self._client_session: aiohttp.ClientSession = None
self._jar = aiohttp.CookieJar(unsafe=True, quote_cookie=False)
self._last_url = URL(f"http://{self._config.host}/")

self._wait_between_requests = 0.0
self._last_request_time = 0.0

@property
def client(self) -> aiohttp.ClientSession:
"""Return the underlying http client."""
Expand All @@ -60,6 +67,12 @@ async def post(

If the request is provided via the json parameter json will be returned.
"""
if self._wait_between_requests:
now = time.time()
gap = now - self._last_request_time
if gap < self._wait_between_requests:
await asyncio.sleep(self._wait_between_requests - gap)

_LOGGER.debug("Posting to %s", url)
response_data = None
self._last_url = url
Expand Down Expand Up @@ -89,6 +102,8 @@ async def post(
response_data = json_loads(response_data.decode())

except (aiohttp.ServerDisconnectedError, aiohttp.ClientOSError) as ex:
if isinstance(ex, aiohttp.ClientOSError):
self._wait_between_requests = self.WAIT_TIME
raise _ConnectionError(
f"Device connection error: {self._config.host}: {ex}", ex
) from ex
Expand All @@ -103,6 +118,9 @@ async def post(
f"Unable to query the device: {self._config.host}: {ex}", ex
) from ex

if self._wait_between_requests:
self._last_request_time = time.time()

return resp.status, response_data

def get_cookie(self, cookie_name: str) -> str | None:
Expand Down
0