2024-01-18 09:57:33 +00:00
|
|
|
"""Module for HttpClientSession class."""
|
2024-04-16 18:21:20 +00:00
|
|
|
|
2024-04-17 13:39:24 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2024-01-19 20:06:50 +00:00
|
|
|
import asyncio
|
2024-02-03 14:28:20 +00:00
|
|
|
import logging
|
2024-06-04 17:49:01 +00:00
|
|
|
import time
|
2024-04-17 13:39:24 +00:00
|
|
|
from typing import Any, Dict
|
2024-01-18 09:57:33 +00:00
|
|
|
|
2024-01-18 17:32:26 +00:00
|
|
|
import aiohttp
|
2024-01-29 15:26:00 +00:00
|
|
|
from yarl import URL
|
2024-01-18 09:57:33 +00:00
|
|
|
|
|
|
|
from .deviceconfig import DeviceConfig
|
2024-01-23 22:15:18 +00:00
|
|
|
from .exceptions import (
|
2024-02-21 15:52:55 +00:00
|
|
|
KasaException,
|
|
|
|
TimeoutError,
|
|
|
|
_ConnectionError,
|
2024-01-23 22:15:18 +00:00
|
|
|
)
|
2024-01-18 17:32:26 +00:00
|
|
|
from .json import loads as json_loads
|
2024-01-18 09:57:33 +00:00
|
|
|
|
2024-02-03 14:28:20 +00:00
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
2024-01-18 09:57:33 +00:00
|
|
|
|
2024-01-18 17:32:26 +00:00
|
|
|
def get_cookie_jar() -> aiohttp.CookieJar:
|
|
|
|
"""Return a new cookie jar with the correct options for device communication."""
|
|
|
|
return aiohttp.CookieJar(unsafe=True, quote_cookie=False)
|
2024-01-18 09:57:33 +00:00
|
|
|
|
|
|
|
|
|
|
|
class HttpClient:
|
|
|
|
"""HttpClient Class."""
|
|
|
|
|
2024-06-04 17:49:01 +00:00
|
|
|
# Some devices (only P100 so far) close the http connection after each request
|
|
|
|
# and aiohttp doesn't seem to handle it. If a Client OS error is received the
|
|
|
|
# http client will start ensuring that sequential requests have a wait delay.
|
|
|
|
WAIT_BETWEEN_REQUESTS_ON_OSERROR = 0.25
|
|
|
|
|
2024-01-18 09:57:33 +00:00
|
|
|
def __init__(self, config: DeviceConfig) -> None:
|
|
|
|
self._config = config
|
2024-06-19 13:07:59 +00:00
|
|
|
self._client_session: aiohttp.ClientSession | None = None
|
2024-01-18 17:32:26 +00:00
|
|
|
self._jar = aiohttp.CookieJar(unsafe=True, quote_cookie=False)
|
2024-01-29 15:26:00 +00:00
|
|
|
self._last_url = URL(f"http://{self._config.host}/")
|
2024-01-18 09:57:33 +00:00
|
|
|
|
2024-06-04 17:49:01 +00:00
|
|
|
self._wait_between_requests = 0.0
|
|
|
|
self._last_request_time = 0.0
|
|
|
|
|
2024-01-18 09:57:33 +00:00
|
|
|
@property
|
2024-01-18 17:32:26 +00:00
|
|
|
def client(self) -> aiohttp.ClientSession:
|
2024-01-18 09:57:33 +00:00
|
|
|
"""Return the underlying http client."""
|
|
|
|
if self._config.http_client and issubclass(
|
2024-01-18 17:32:26 +00:00
|
|
|
self._config.http_client.__class__, aiohttp.ClientSession
|
2024-01-18 09:57:33 +00:00
|
|
|
):
|
|
|
|
return self._config.http_client
|
|
|
|
|
2024-01-19 20:30:01 +00:00
|
|
|
if not self._client_session:
|
|
|
|
self._client_session = aiohttp.ClientSession(cookie_jar=get_cookie_jar())
|
|
|
|
return self._client_session
|
2024-01-18 09:57:33 +00:00
|
|
|
|
|
|
|
async def post(
|
|
|
|
self,
|
2024-01-29 15:26:00 +00:00
|
|
|
url: URL,
|
2024-01-18 09:57:33 +00:00
|
|
|
*,
|
2024-04-17 13:39:24 +00:00
|
|
|
params: dict[str, Any] | None = None,
|
|
|
|
data: bytes | None = None,
|
|
|
|
json: dict | Any | None = None,
|
|
|
|
headers: dict[str, str] | None = None,
|
|
|
|
cookies_dict: dict[str, str] | None = None,
|
|
|
|
) -> tuple[int, dict | bytes | None]:
|
2024-01-23 15:29:27 +00:00
|
|
|
"""Send an http post request to the device.
|
|
|
|
|
|
|
|
If the request is provided via the json parameter json will be returned.
|
|
|
|
"""
|
2024-06-04 17:49:01 +00:00
|
|
|
# Once we know a device needs a wait between sequential queries always wait
|
|
|
|
# first rather than keep erroring then waiting.
|
|
|
|
if self._wait_between_requests:
|
2024-07-16 12:25:32 +00:00
|
|
|
now = time.monotonic()
|
2024-06-04 17:49:01 +00:00
|
|
|
gap = now - self._last_request_time
|
|
|
|
if gap < self._wait_between_requests:
|
2024-07-11 15:21:59 +00:00
|
|
|
sleep = self._wait_between_requests - gap
|
|
|
|
_LOGGER.debug(
|
|
|
|
"Device %s waiting %s seconds to send request",
|
|
|
|
self._config.host,
|
|
|
|
sleep,
|
|
|
|
)
|
|
|
|
await asyncio.sleep(sleep)
|
2024-06-04 17:49:01 +00:00
|
|
|
|
2024-02-03 14:28:20 +00:00
|
|
|
_LOGGER.debug("Posting to %s", url)
|
2024-01-18 09:57:33 +00:00
|
|
|
response_data = None
|
2024-01-18 17:32:26 +00:00
|
|
|
self._last_url = url
|
|
|
|
self.client.cookie_jar.clear()
|
2024-01-23 15:29:27 +00:00
|
|
|
return_json = bool(json)
|
2024-07-11 15:21:59 +00:00
|
|
|
client_timeout = aiohttp.ClientTimeout(total=self._config.timeout)
|
|
|
|
|
2024-01-23 15:29:27 +00:00
|
|
|
# If json is not a dict send as data.
|
|
|
|
# This allows the json parameter to be used to pass other
|
|
|
|
# types of data such as async_generator and still have json
|
|
|
|
# returned.
|
|
|
|
if json and not isinstance(json, Dict):
|
|
|
|
data = json
|
|
|
|
json = None
|
2024-01-18 09:57:33 +00:00
|
|
|
try:
|
|
|
|
resp = await self.client.post(
|
|
|
|
url,
|
|
|
|
params=params,
|
|
|
|
data=data,
|
|
|
|
json=json,
|
2024-07-11 15:21:59 +00:00
|
|
|
timeout=client_timeout,
|
2024-01-18 17:32:26 +00:00
|
|
|
cookies=cookies_dict,
|
2024-01-18 09:57:33 +00:00
|
|
|
headers=headers,
|
2024-07-11 15:21:59 +00:00
|
|
|
ssl=False,
|
2024-01-18 09:57:33 +00:00
|
|
|
)
|
2024-01-19 20:06:50 +00:00
|
|
|
async with resp:
|
|
|
|
if resp.status == 200:
|
|
|
|
response_data = await resp.read()
|
2024-01-23 15:29:27 +00:00
|
|
|
if return_json:
|
2024-01-19 20:06:50 +00:00
|
|
|
response_data = json_loads(response_data.decode())
|
|
|
|
|
2024-01-18 17:32:26 +00:00
|
|
|
except (aiohttp.ServerDisconnectedError, aiohttp.ClientOSError) as ex:
|
2024-07-11 15:21:59 +00:00
|
|
|
if not self._wait_between_requests:
|
|
|
|
_LOGGER.debug(
|
|
|
|
"Device %s received an os error, "
|
|
|
|
"enabling sequential request delay: %s",
|
|
|
|
self._config.host,
|
|
|
|
ex,
|
|
|
|
)
|
2024-06-04 17:49:01 +00:00
|
|
|
self._wait_between_requests = self.WAIT_BETWEEN_REQUESTS_ON_OSERROR
|
2024-07-16 12:25:32 +00:00
|
|
|
self._last_request_time = time.monotonic()
|
2024-02-21 15:52:55 +00:00
|
|
|
raise _ConnectionError(
|
2024-01-23 22:15:18 +00:00
|
|
|
f"Device connection error: {self._config.host}: {ex}", ex
|
2024-01-18 09:57:33 +00:00
|
|
|
) from ex
|
2024-01-19 20:06:50 +00:00
|
|
|
except (aiohttp.ServerTimeoutError, asyncio.TimeoutError) as ex:
|
2024-02-21 15:52:55 +00:00
|
|
|
raise TimeoutError(
|
2024-01-19 20:06:50 +00:00
|
|
|
"Unable to query the device, "
|
|
|
|
+ f"timed out: {self._config.host}: {ex}",
|
|
|
|
ex,
|
2024-01-18 09:57:33 +00:00
|
|
|
) from ex
|
|
|
|
except Exception as ex:
|
2024-02-21 15:52:55 +00:00
|
|
|
raise KasaException(
|
2024-01-19 20:06:50 +00:00
|
|
|
f"Unable to query the device: {self._config.host}: {ex}", ex
|
2024-01-18 09:57:33 +00:00
|
|
|
) from ex
|
|
|
|
|
2024-06-04 17:49:01 +00:00
|
|
|
# For performance only request system time if waiting is enabled
|
|
|
|
if self._wait_between_requests:
|
2024-07-16 12:25:32 +00:00
|
|
|
self._last_request_time = time.monotonic()
|
2024-06-04 17:49:01 +00:00
|
|
|
|
2024-01-18 17:32:26 +00:00
|
|
|
return resp.status, response_data
|
2024-01-18 09:57:33 +00:00
|
|
|
|
2024-04-17 13:39:24 +00:00
|
|
|
def get_cookie(self, cookie_name: str) -> str | None:
|
2024-01-18 09:57:33 +00:00
|
|
|
"""Return the cookie with cookie_name."""
|
2024-01-18 17:32:26 +00:00
|
|
|
if cookie := self.client.cookie_jar.filter_cookies(self._last_url).get(
|
|
|
|
cookie_name
|
|
|
|
):
|
|
|
|
return cookie.value
|
|
|
|
return None
|
2024-01-18 09:57:33 +00:00
|
|
|
|
|
|
|
async def close(self) -> None:
|
2024-01-19 20:30:01 +00:00
|
|
|
"""Close the ClientSession."""
|
|
|
|
client = self._client_session
|
|
|
|
self._client_session = None
|
2024-01-18 09:57:33 +00:00
|
|
|
if client:
|
2024-01-18 17:32:26 +00:00
|
|
|
await client.close()
|