8000 Enable multiple requests in smartprotocol by sdb9696 · Pull Request #584 · python-kasa/python-kasa · GitHub
[go: up one dir, main page]

Skip to content

Enable multiple requests in smartprotocol #584

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 3 commits into from
Dec 20, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
75 changes: 50 additions & 25 deletions kasa/smartprotocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,26 +62,7 @@ def get_smart_request(self, method, params=None) -> str:
async def query(self, request: Union[str, Dict], retry_count: int = 3) -> Dict:
"""Query the device retrying for retry_count on failure."""
async with self._query_lock:
resp_dict = await self._query(request, retry_count)

if (
error_code := SmartErrorCode(resp_dict.get("error_code")) # type: ignore[arg-type]
) != SmartErrorCode.SUCCESS:
msg = (
f"Error querying device: {self._host}: "
+ f"{error_code.name}({error_code.value})"
)
if error_code in SMART_TIMEOUT_ERRORS:
raise TimeoutException(msg)
if error_code in SMART_RETRYABLE_ERRORS:
raise RetryableException(msg)
if error_code in SMART_AUTHENTICATION_ERRORS:
raise AuthenticationException(msg)
raise SmartDeviceException(msg)

if "result" in resp_dict:
return resp_dict["result"]
return {}
return await self._query(request, retry_count)

async def _query(self, request: Union[str, Dict], retry_count: int = 3) -> Dict:
for retry in range(retry_count + 1):
Expand Down Expand Up @@ -144,9 +125,18 @@ async def _query(self, request: Union[str, Dict], retry_count: int = 3) -> Dict:
raise SmartDeviceException("Query reached somehow to unreachable")

async def _execute_query(self, request: Union[str, Dict], retry_count: int) -> Dict:
is_multi = False
if isinstance(request, dict):
smart_method = next(iter(request))
smart_params = request[smart_method]
if len(request) == 1:
smart_method = next(iter(request))
smart_params = request[smart_method]
else:
is_multi = True
requests = []
for method, params in request.items():
requests.append({"method": method, "params": params})
smart_method = "multipleRequest"
smart_params = {"requests": requests}
else:
smart_method = request
smart_params = None
Expand All @@ -157,15 +147,50 @@ async def _execute_query(self, request: Union[str, Dict], retry_count: int) -> D
self._host,
_LOGGER.isEnabledFor(logging.DEBUG) and pf(smart_request),
)
response_data = await self._transport.send(smart_request)
resp_dict = await self._transport.send(smart_request)

_LOGGER.debug(
"%s << %s",
self._host,
_LOGGER.isEnabledFor(logging.DEBUG) and pf(response_data),
_LOGGER.isEnabledFor(logging.DEBUG) and pf(resp_dict),
)

return response_data
self._handle_response_error_code(resp_dict)

if result := resp_dict.get("result"):
if is_multi:
if (responses := result.get("responses")) is None:
raise SmartDeviceException(
"Unexpected response to multipleRequest "
+ f"method for {self._host}: {result}"
)
multi_result = {}
for response in responses:
self._handle_response_error_code(response)
result = response.get("result", {})
multi_result[response["method"]] = result
return multi_result

return {smart_method: result}
return {smart_method: None}

def _handle_response_error_code(self, resp_dict: dict):
if (
error_code := SmartErrorCode(resp_dict.get("error_code")) # type: ignore[arg-type]
) != SmartErrorCode.SUCCESS:
msg = (
f"Error querying device: {self._host}: "
+ f"{error_code.name}({error_code.value})"
)
if method := resp_dict.get("method"):
msg += f" for method: {method}"
if error_code in SMART_TIMEOUT_ERRORS:
raise TimeoutException(msg)
if error_code in SMART_RETRYABLE_ERRORS:
raise RetryableException(msg)
if error_code in SMART_AUTHENTICATION_ERRORS:
raise AuthenticationException(msg)
raise SmartDeviceException(msg)

async def close(self) -> None:
"""Close the protocol."""
Expand Down
15 changes: 11 additions & 4 deletions kasa/tapo/tapodevice.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,18 @@ async def update(self, update_children: bool = True):
raise AuthenticationException("Tapo plug requires authentication.")

if self._components is None:
self._components = await self.protocol.query("component_nego")
resp = await self.protocol.query("component_nego")
self._components = resp["component_nego"]

self._info = await self.protocol.query("get_device_info")
self._usage = await self.protocol.query("get_device_usage")
self._time = await self.protocol.query("get_device_time")
req = {
"get_device_info": None,
"get_device_usage": None,
"get_device_time": None,
}
resp = await self.protocol.query(req)
self._info = resp["get_device_info"]
self._usage = resp["get_device_usage"]
self._time = resp["get_device_time"]

self._last_update = self._data = {
"components": self._components,
Expand Down
43 changes: 25 additions & 18 deletions kasa/tests/newfakes.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import copy
import logging
import re
import warnings
from json import loads as json_loads

from voluptuous import (
Expand Down Expand Up @@ -294,9 +295,7 @@ def __init__(self, info):
async def query(self, request, retry_count: int = 3):
"""Implement query here so can still patch SmartProtocol.query."""
resp_dict = await self._query(request, retry_count)
if "result" in resp_dict:
return resp_dict["result"]
return {}
return resp_dict


class FakeSmartTransport(BaseTransport):
Expand All @@ -306,26 +305,34 @@ def __init__(self, info):
)
self.info = info

@property
def needs_handshake(self) -> bool:
return False

@property
def needs_login(self) -> bool:
return False

async def login(self, request: str) -> None:
pass

async def handshake(self) -> None:
pass

async def send(self, request: str):
request_dict = json_loads(request)
method = request_dict["method"]
params = request_dict["params"]
if method == "multipleRequest":
responses = []
for request in params["requests"]:
response = self._send_request(request) # type: ignore[arg-type]
response["method"] = request["method"] # type: ignore[index]
responses.append(response)
return {"result": {"responses": responses}, "error_code": 0}
else:
return self._send_request(request_dict)

def _send_request(self, request_dict: dict):
method = request_dict["method"]
params = request_dict["params"]
if method == "component_nego" or method[:4] == "get_":
return {"result": self.info[method], "error_code": 0}
if method in self.info:
return {"result": self.info[method], "error_code": 0}
else:
warnings.warn(
UserWarning(
f"Fixture missing expected method {method}, try to regenerate"
),
stacklevel=1,
)
return {"result": {}, "error_code": 0}
elif method[:4] == "set_":
target_method = f"get_{method[4:]}"
self.info[target_method].update(params)
Expand Down
2 changes: 1 addition & 1 deletion kasa/tests/test_klapprotocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ def _fail_one_less_than_retry_count(*_, **__):
response = await protocol_class(host, transport=transport_class(host)).query(
DUMMY_QUERY, retry_count=retry_count
)
assert "result" in response or "great" in response
assert "result" in response or "foobar" in response
assert send_mock.call_count == retry_count


Expand Down
0