diff --git a/kasa/httpclient.py b/kasa/httpclient.py index 26b8d6a7..a4bd84a3 100644 --- a/kasa/httpclient.py +++ b/kasa/httpclient.py @@ -19,7 +19,7 @@ class HttpClient: def __init__(self, config: DeviceConfig) -> None: self._config = config - self._client: aiohttp.ClientSession = None + self._client_session: aiohttp.ClientSession = None self._jar = aiohttp.CookieJar(unsafe=True, quote_cookie=False) self._last_url = f"http://{self._config.host}/" @@ -31,9 +31,9 @@ class HttpClient: ): return self._config.http_client - if not self._client: - self._client = aiohttp.ClientSession(cookie_jar=get_cookie_jar()) - return self._client + if not self._client_session: + self._client_session = aiohttp.ClientSession(cookie_jar=get_cookie_jar()) + return self._client_session async def post( self, @@ -91,8 +91,8 @@ class HttpClient: return None async def close(self) -> None: - """Close the client.""" - client = self._client - self._client = None + """Close the ClientSession.""" + client = self._client_session + self._client_session = None if client: await client.close() diff --git a/kasa/klaptransport.py b/kasa/klaptransport.py index 39dc1f28..8128a20b 100644 --- a/kasa/klaptransport.py +++ b/kasa/klaptransport.py @@ -320,7 +320,7 @@ class KlapTransport(BaseTransport): + f"Response status is {response_status}, Request was {request}" ) if response_status != 200: - _LOGGER.error("Query failed after succesful authentication " + msg) + _LOGGER.error("Query failed after successful authentication " + msg) # If we failed with a security error, force a new handshake next time. if response_status == 403: self._handshake_done = False @@ -351,9 +351,8 @@ class KlapTransport(BaseTransport): return json_payload async def close(self) -> None: - """Close the transport.""" + """Mark the handshake as not done since we likely lost the connection.""" self._handshake_done = False - await self._http_client.close() @staticmethod def generate_auth_hash(creds: Credentials): diff --git a/kasa/smartprotocol.py b/kasa/smartprotocol.py index 8d74a502..e7143d2e 100644 --- a/kasa/smartprotocol.py +++ b/kasa/smartprotocol.py @@ -84,8 +84,8 @@ class SmartProtocol(TPLinkProtocol): raise ex continue except TimeoutException as ex: + await self.close() if retry >= retry_count: - await self.close() _LOGGER.debug("Giving up on %s after %s retries", self._host, retry) raise ex await asyncio.sleep(self.BACKOFF_SECONDS_AFTER_TIMEOUT) @@ -167,7 +167,12 @@ class SmartProtocol(TPLinkProtocol): raise SmartDeviceException(msg, error_code=error_code) async def close(self) -> None: - """Close the protocol.""" + """Close the underlying transport. + + Some transports may close the connection, and some may + use this as a hint that they need to reconnect, or + reauthenticate. + """ await self._transport.close()