2023-12-04 18:50:05 +00:00
|
|
|
"""Implementation of the TP-Link AES Protocol.
|
|
|
|
|
|
|
|
Based on the work of https://github.com/petretiandrea/plugp100
|
|
|
|
under compatible GNU GPL3 license.
|
|
|
|
"""
|
|
|
|
|
2024-04-17 13:39:24 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2023-12-04 18:50:05 +00:00
|
|
|
import asyncio
|
|
|
|
import base64
|
|
|
|
import logging
|
|
|
|
import time
|
|
|
|
import uuid
|
2024-11-18 18:46:36 +00:00
|
|
|
from collections.abc import Callable
|
2023-12-04 18:50:05 +00:00
|
|
|
from pprint import pformat as pf
|
2024-11-18 18:46:36 +00:00
|
|
|
from typing import TYPE_CHECKING, Any
|
2023-12-04 18:50:05 +00:00
|
|
|
|
2024-11-13 17:50:21 +00:00
|
|
|
from ..exceptions import (
|
2023-12-10 15:41:53 +00:00
|
|
|
SMART_AUTHENTICATION_ERRORS,
|
|
|
|
SMART_RETRYABLE_ERRORS,
|
2024-02-21 15:52:55 +00:00
|
|
|
AuthenticationError,
|
|
|
|
DeviceError,
|
|
|
|
KasaException,
|
2023-12-10 15:41:53 +00:00
|
|
|
SmartErrorCode,
|
2024-02-21 15:52:55 +00:00
|
|
|
TimeoutError,
|
|
|
|
_ConnectionError,
|
|
|
|
_RetryableError,
|
2023-12-10 15:41:53 +00:00
|
|
|
)
|
2024-11-13 17:50:21 +00:00
|
|
|
from ..json import dumps as json_dumps
|
2024-11-12 13:40:44 +00:00
|
|
|
from .protocol import BaseProtocol, mask_mac, md5, redact_data
|
|
|
|
|
|
|
|
if TYPE_CHECKING:
|
2024-11-13 17:50:21 +00:00
|
|
|
from ..transports import BaseTransport
|
2024-11-12 13:40:44 +00:00
|
|
|
|
2023-12-04 18:50:05 +00:00
|
|
|
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
2024-07-17 17:57:09 +00:00
|
|
|
REDACTORS: dict[str, Callable[[Any], Any] | None] = {
|
|
|
|
"latitude": lambda x: 0,
|
|
|
|
"longitude": lambda x: 0,
|
|
|
|
"la": lambda x: 0, # lat on ks240
|
|
|
|
"lo": lambda x: 0, # lon on ks240
|
|
|
|
"device_id": lambda x: "REDACTED_" + x[9::],
|
|
|
|
"parent_device_id": lambda x: "REDACTED_" + x[9::], # Hub attached children
|
|
|
|
"original_device_id": lambda x: "REDACTED_" + x[9::], # Strip children
|
|
|
|
"nickname": lambda x: "I01BU0tFRF9OQU1FIw==" if x else "",
|
|
|
|
"mac": mask_mac,
|
|
|
|
"ssid": lambda x: "I01BU0tFRF9TU0lEIw=" if x else "",
|
|
|
|
"bssid": lambda _: "000000000000",
|
|
|
|
"oem_id": lambda x: "REDACTED_" + x[9::],
|
|
|
|
"setup_code": None, # matter
|
|
|
|
"setup_payload": None, # matter
|
|
|
|
"mfi_setup_code": None, # mfi_ for homekit
|
|
|
|
"mfi_setup_id": None,
|
|
|
|
"mfi_token_token": None,
|
|
|
|
"mfi_token_uuid": None,
|
|
|
|
}
|
|
|
|
|
2023-12-04 18:50:05 +00:00
|
|
|
|
2024-01-22 15:28:30 +00:00
|
|
|
class SmartProtocol(BaseProtocol):
|
2023-12-04 18:50:05 +00:00
|
|
|
"""Class for the new TPLink SMART protocol."""
|
|
|
|
|
2024-01-18 09:57:33 +00:00
|
|
|
BACKOFF_SECONDS_AFTER_TIMEOUT = 1
|
2024-01-29 10:55:54 +00:00
|
|
|
DEFAULT_MULTI_REQUEST_BATCH_SIZE = 5
|
2023-12-04 18:50:05 +00:00
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
*,
|
2023-12-19 14:11:59 +00:00
|
|
|
transport: BaseTransport,
|
2023-12-04 18:50:05 +00:00
|
|
|
) -> None:
|
2023-12-19 14:11:59 +00:00
|
|
|
"""Create a protocol object."""
|
2023-12-29 19:17:15 +00:00
|
|
|
super().__init__(transport=transport)
|
2023-12-19 14:11:59 +00:00
|
|
|
self._terminal_uuid: str = base64.b64encode(md5(uuid.uuid4().bytes)).decode()
|
2023-12-04 18:50:05 +00:00
|
|
|
self._query_lock = asyncio.Lock()
|
2024-07-01 12:57:13 +00:00
|
|
|
self._multi_request_batch_size = (
|
|
|
|
self._transport._config.batch_size or self.DEFAULT_MULTI_REQUEST_BATCH_SIZE
|
|
|
|
)
|
2024-07-17 17:57:09 +00:00
|
|
|
self._redact_data = True
|
2023-12-04 18:50:05 +00:00
|
|
|
|
2024-11-10 18:55:13 +00:00
|
|
|
def get_smart_request(self, method: str, params: dict | None = None) -> str:
|
2023-12-04 18:50:05 +00:00
|
|
|
"""Get a request message as a string."""
|
|
|
|
request = {
|
|
|
|
"method": method,
|
|
|
|
"request_time_milis": round(time.time() * 1000),
|
|
|
|
"terminal_uuid": self._terminal_uuid,
|
|
|
|
}
|
2024-07-23 18:02:20 +00:00
|
|
|
if params:
|
|
|
|
request["params"] = params
|
2023-12-04 18:50:05 +00:00
|
|
|
return json_dumps(request)
|
|
|
|
|
2024-04-17 13:39:24 +00:00
|
|
|
async def query(self, request: str | dict, retry_count: int = 3) -> dict:
|
2023-12-04 18:50:05 +00:00
|
|
|
"""Query the device retrying for retry_count on failure."""
|
|
|
|
async with self._query_lock:
|
2023-12-20 17:08:04 +00:00
|
|
|
return await self._query(request, retry_count)
|
2023-12-04 18:50:05 +00:00
|
|
|
|
2024-04-17 13:39:24 +00:00
|
|
|
async def _query(self, request: str | dict, retry_count: int = 3) -> dict:
|
2023-12-04 18:50:05 +00:00
|
|
|
for retry in range(retry_count + 1):
|
|
|
|
try:
|
2024-04-24 18:32:30 +00:00
|
|
|
return await self._execute_query(
|
|
|
|
request, retry_count=retry, iterate_list_pages=True
|
|
|
|
)
|
2024-07-11 15:21:59 +00:00
|
|
|
except _ConnectionError as ex:
|
|
|
|
if retry == 0:
|
|
|
|
_LOGGER.debug(
|
|
|
|
"Device %s got a connection error, will retry %s times: %s",
|
|
|
|
self._host,
|
|
|
|
retry_count,
|
|
|
|
ex,
|
|
|
|
)
|
2023-12-04 18:50:05 +00:00
|
|
|
if retry >= retry_count:
|
2023-12-19 14:11:59 +00:00
|
|
|
_LOGGER.debug("Giving up on %s after %s retries", self._host, retry)
|
2024-07-11 15:21:59 +00:00
|
|
|
raise ex
|
2023-12-10 15:41:53 +00:00
|
|
|
continue
|
2024-07-11 15:21:59 +00:00
|
|
|
except AuthenticationError as ex:
|
2024-01-23 22:15:18 +00:00
|
|
|
await self._transport.reset()
|
2023-12-19 14:11:59 +00:00
|
|
|
_LOGGER.debug(
|
2024-07-11 15:21:59 +00:00
|
|
|
"Unable to authenticate with %s, not retrying: %s", self._host, ex
|
2023-12-19 14:11:59 +00:00
|
|
|
)
|
2024-07-11 15:21:59 +00:00
|
|
|
raise ex
|
2024-02-21 15:52:55 +00:00
|
|
|
except _RetryableError as ex:
|
2024-07-11 15:21:59 +00:00
|
|
|
if retry == 0:
|
|
|
|
_LOGGER.debug(
|
|
|
|
"Device %s got a retryable error, will retry %s times: %s",
|
|
|
|
self._host,
|
|
|
|
retry_count,
|
|
|
|
ex,
|
|
|
|
)
|
2024-01-23 22:15:18 +00:00
|
|
|
await self._transport.reset()
|
2023-12-10 15:41:53 +00:00
|
|
|
if retry >= retry_count:
|
2023-12-19 14:11:59 +00:00
|
|
|
_LOGGER.debug("Giving up on %s after %s retries", self._host, retry)
|
2023-12-10 15:41:53 +00:00
|
|
|
raise ex
|
2024-02-14 19:13:28 +00:00
|
|
|
await asyncio.sleep(self.BACKOFF_SECONDS_AFTER_TIMEOUT)
|
2023-12-10 15:41:53 +00:00
|
|
|
continue
|
2024-02-21 15:52:55 +00:00
|
|
|
except TimeoutError as ex:
|
2024-07-11 15:21:59 +00:00
|
|
|
if retry == 0:
|
|
|
|
_LOGGER.debug(
|
|
|
|
"Device %s got a timeout error, will retry %s times: %s",
|
|
|
|
self._host,
|
|
|
|
retry_count,
|
|
|
|
ex,
|
|
|
|
)
|
2024-01-23 22:15:18 +00:00
|
|
|
await self._transport.reset()
|
2023-12-10 15:41:53 +00:00
|
|
|
if retry >= retry_count:
|
2023-12-19 14:11:59 +00:00
|
|
|
_LOGGER.debug("Giving up on %s after %s retries", self._host, retry)
|
2023-12-10 15:41:53 +00:00
|
|
|
raise ex
|
2024-01-18 09:57:33 +00:00
|
|
|
await asyncio.sleep(self.BACKOFF_SECONDS_AFTER_TIMEOUT)
|
2023-12-10 15:41:53 +00:00
|
|
|
continue
|
2024-02-21 15:52:55 +00:00
|
|
|
except KasaException as ex:
|
2024-01-23 22:15:18 +00:00
|
|
|
await self._transport.reset()
|
2023-12-10 15:41:53 +00:00
|
|
|
_LOGGER.debug(
|
2024-01-18 09:57:33 +00:00
|
|
|
"Unable to query the device: %s, not retrying: %s",
|
|
|
|
self._host,
|
|
|
|
ex,
|
2023-12-10 15:41:53 +00:00
|
|
|
)
|
2024-01-18 09:57:33 +00:00
|
|
|
raise ex
|
2023-12-04 18:50:05 +00:00
|
|
|
|
|
|
|
# make mypy happy, this should never be reached..
|
2024-02-21 15:52:55 +00:00
|
|
|
raise KasaException("Query reached somehow to unreachable")
|
2023-12-04 18:50:05 +00:00
|
|
|
|
2024-04-20 15:24:49 +00:00
|
|
|
async def _execute_multiple_query(self, requests: dict, retry_count: int) -> dict:
|
2024-01-29 10:55:54 +00:00
|
|
|
debug_enabled = _LOGGER.isEnabledFor(logging.DEBUG)
|
2024-04-17 13:39:24 +00:00
|
|
|
multi_result: dict[str, Any] = {}
|
2024-01-29 10:55:54 +00:00
|
|
|
smart_method = "multipleRequest"
|
2024-07-23 18:02:20 +00:00
|
|
|
|
2024-04-20 15:24:49 +00:00
|
|
|
multi_requests = [
|
2024-07-23 18:02:20 +00:00
|
|
|
{"method": method, "params": params} if params else {"method": method}
|
|
|
|
for method, params in requests.items()
|
2024-01-29 10:55:54 +00:00
|
|
|
]
|
|
|
|
|
2024-04-20 15:24:49 +00:00
|
|
|
end = len(multi_requests)
|
2024-11-23 08:07:47 +00:00
|
|
|
# The SmartCamProtocol sends requests with a length 1 as a
|
2024-10-24 12:11:28 +00:00
|
|
|
# multipleRequest. The SmartProtocol doesn't so will never
|
|
|
|
# raise_on_error
|
|
|
|
raise_on_error = end == 1
|
2024-10-18 11:06:22 +00:00
|
|
|
|
2024-01-29 10:55:54 +00:00
|
|
|
# Break the requests down as there can be a size limit
|
2024-07-01 12:57:13 +00:00
|
|
|
step = self._multi_request_batch_size
|
|
|
|
if step == 1:
|
|
|
|
# If step is 1 do not send request batches
|
|
|
|
for request in multi_requests:
|
|
|
|
method = request["method"]
|
2024-07-23 18:02:20 +00:00
|
|
|
req = self.get_smart_request(method, request.get("params"))
|
2024-07-01 12:57:13 +00:00
|
|
|
resp = await self._transport.send(req)
|
2024-10-24 12:11:28 +00:00
|
|
|
self._handle_response_error_code(
|
|
|
|
resp, method, raise_on_error=raise_on_error
|
|
|
|
)
|
2024-07-01 12:57:13 +00:00
|
|
|
multi_result[method] = resp["result"]
|
|
|
|
return multi_result
|
2024-07-11 15:21:59 +00:00
|
|
|
|
|
|
|
for batch_num, i in enumerate(range(0, end, step)):
|
2024-04-20 15:24:49 +00:00
|
|
|
requests_step = multi_requests[i : i + step]
|
2024-01-29 10:55:54 +00:00
|
|
|
|
|
|
|
smart_params = {"requests": requests_step}
|
|
|
|
smart_request = self.get_smart_request(smart_method, smart_params)
|
2024-07-11 15:21:59 +00:00
|
|
|
batch_name = f"multi-request-batch-{batch_num+1}-of-{int(end/step)+1}"
|
2024-01-29 10:55:54 +00:00
|
|
|
if debug_enabled:
|
|
|
|
_LOGGER.debug(
|
2024-07-11 15:21:59 +00:00
|
|
|
"%s %s >> %s",
|
2024-01-29 10:55:54 +00:00
|
|
|
self._host,
|
2024-07-11 15:21:59 +00:00
|
|
|
batch_name,
|
2024-01-29 10:55:54 +00:00
|
|
|
pf(smart_request),
|
|
|
|
)
|
|
|
|
response_step = await self._transport.send(smart_request)
|
|
|
|
if debug_enabled:
|
2024-07-17 17:57:09 +00:00
|
|
|
if self._redact_data:
|
|
|
|
data = redact_data(response_step, REDACTORS)
|
|
|
|
else:
|
|
|
|
data = response_step
|
2024-01-29 10:55:54 +00:00
|
|
|
_LOGGER.debug(
|
2024-02-15 18:10:34 +00:00
|
|
|
"%s %s << %s",
|
2024-01-29 10:55:54 +00:00
|
|
|
self._host,
|
2024-02-15 18:10:34 +00:00
|
|
|
batch_name,
|
2024-07-17 17:57:09 +00:00
|
|
|
pf(data),
|
2024-01-29 10:55:54 +00:00
|
|
|
)
|
2024-07-01 12:57:13 +00:00
|
|
|
try:
|
|
|
|
self._handle_response_error_code(response_step, batch_name)
|
|
|
|
except DeviceError as ex:
|
2024-07-01 13:33:28 +00:00
|
|
|
# P100 sometimes raises JSON_DECODE_FAIL_ERROR or INTERNAL_UNKNOWN_ERROR
|
|
|
|
# on batched request so disable batching
|
2024-07-01 12:57:13 +00:00
|
|
|
if (
|
2024-07-01 13:33:28 +00:00
|
|
|
ex.error_code
|
|
|
|
in {
|
|
|
|
SmartErrorCode.JSON_DECODE_FAIL_ERROR,
|
|
|
|
SmartErrorCode.INTERNAL_UNKNOWN_ERROR,
|
|
|
|
}
|
2024-07-01 12:57:13 +00:00
|
|
|
and self._multi_request_batch_size != 1
|
|
|
|
):
|
|
|
|
self._multi_request_batch_size = 1
|
|
|
|
raise _RetryableError(
|
|
|
|
"JSON Decode failure, multi requests disabled"
|
|
|
|
) from ex
|
|
|
|
raise ex
|
|
|
|
|
2024-01-29 10:55:54 +00:00
|
|
|
responses = response_step["result"]["responses"]
|
|
|
|
for response in responses:
|
2024-02-15 18:10:34 +00:00
|
|
|
method = response["method"]
|
2024-10-18 11:06:22 +00:00
|
|
|
self._handle_response_error_code(
|
|
|
|
response, method, raise_on_error=raise_on_error
|
|
|
|
)
|
2024-01-29 10:55:54 +00:00
|
|
|
result = response.get("result", None)
|
2024-04-24 18:32:30 +00:00
|
|
|
await self._handle_response_lists(
|
|
|
|
result, method, retry_count=retry_count
|
|
|
|
)
|
2024-02-15 18:10:34 +00:00
|
|
|
multi_result[method] = result
|
2024-04-20 15:24:49 +00:00
|
|
|
# Multi requests don't continue after errors so requery any missing
|
|
|
|
for method, params in requests.items():
|
|
|
|
if method not in multi_result:
|
|
|
|
resp = await self._transport.send(
|
|
|
|
self.get_smart_request(method, params)
|
|
|
|
)
|
|
|
|
self._handle_response_error_code(resp, method, raise_on_error=False)
|
|
|
|
multi_result[method] = resp.get("result")
|
2024-01-29 10:55:54 +00:00
|
|
|
return multi_result
|
|
|
|
|
2024-04-24 18:32:30 +00:00
|
|
|
async def _execute_query(
|
|
|
|
self, request: str | dict, *, retry_count: int, iterate_list_pages: bool = True
|
|
|
|
) -> dict:
|
2024-01-29 10:55:54 +00:00
|
|
|
debug_enabled = _LOGGER.isEnabledFor(logging.DEBUG)
|
|
|
|
|
2023-12-04 18:50:05 +00:00
|
|
|
if isinstance(request, dict):
|
2023-12-20 17:08:04 +00:00
|
|
|
if len(request) == 1:
|
|
|
|
smart_method = next(iter(request))
|
|
|
|
smart_params = request[smart_method]
|
|
|
|
else:
|
2024-01-29 10:55:54 +00:00
|
|
|
return await self._execute_multiple_query(request, retry_count)
|
2023-12-04 18:50:05 +00:00
|
|
|
else:
|
|
|
|
smart_method = request
|
|
|
|
smart_params = None
|
|
|
|
|
|
|
|
smart_request = self.get_smart_request(smart_method, smart_params)
|
2024-01-29 10:55:54 +00:00
|
|
|
if debug_enabled:
|
|
|
|
_LOGGER.debug(
|
|
|
|
"%s >> %s",
|
|
|
|
self._host,
|
|
|
|
pf(smart_request),
|
|
|
|
)
|
2023-12-04 18:50:05 +00:00
|
|
|
response_data = await self._transport.send(smart_request)
|
|
|
|
|
2024-01-29 10:55:54 +00:00
|
|
|
if debug_enabled:
|
|
|
|
_LOGGER.debug(
|
|
|
|
"%s << %s",
|
|
|
|
self._host,
|
|
|
|
pf(response_data),
|
|
|
|
)
|
2023-12-04 18:50:05 +00:00
|
|
|
|
2024-02-15 18:10:34 +00:00
|
|
|
self._handle_response_error_code(response_data, smart_method)
|
2023-12-20 17:08:04 +00:00
|
|
|
|
2024-01-29 10:55:54 +00:00
|
|
|
# Single set_ requests do not return a result
|
|
|
|
result = response_data.get("result")
|
2024-04-24 18:32:30 +00:00
|
|
|
if iterate_list_pages and result:
|
|
|
|
await self._handle_response_lists(
|
|
|
|
result, smart_method, retry_count=retry_count
|
|
|
|
)
|
2024-01-29 10:55:54 +00:00
|
|
|
return {smart_method: result}
|
2023-12-20 17:08:04 +00:00
|
|
|
|
2024-04-24 18:32:30 +00:00
|
|
|
async def _handle_response_lists(
|
2024-11-10 18:55:13 +00:00
|
|
|
self, response_result: dict[str, Any], method: str, retry_count: int
|
|
|
|
) -> None:
|
2024-04-24 18:32:30 +00:00
|
|
|
if (
|
2024-04-29 13:24:30 +00:00
|
|
|
response_result is None
|
|
|
|
or isinstance(response_result, SmartErrorCode)
|
2024-04-24 18:32:30 +00:00
|
|
|
or "start_index" not in response_result
|
|
|
|
or (list_sum := response_result.get("sum")) is None
|
|
|
|
):
|
|
|
|
return
|
|
|
|
|
|
|
|
response_list_name = next(
|
|
|
|
iter(
|
|
|
|
[
|
|
|
|
key
|
|
|
|
for key in response_result
|
|
|
|
if isinstance(response_result[key], list)
|
|
|
|
]
|
|
|
|
)
|
|
|
|
)
|
|
|
|
while (list_length := len(response_result[response_list_name])) < list_sum:
|
|
|
|
response = await self._execute_query(
|
|
|
|
{method: {"start_index": list_length}},
|
|
|
|
retry_count=retry_count,
|
|
|
|
iterate_list_pages=False,
|
|
|
|
)
|
|
|
|
next_batch = response[method]
|
2024-05-19 09:34:52 +00:00
|
|
|
# In case the device returns empty lists avoid infinite looping
|
|
|
|
if not next_batch[response_list_name]:
|
|
|
|
_LOGGER.error(
|
2024-08-30 14:13:14 +00:00
|
|
|
"Device %s returned empty results list for method %s",
|
|
|
|
self._host,
|
|
|
|
method,
|
2024-05-19 09:34:52 +00:00
|
|
|
)
|
|
|
|
break
|
2024-04-24 18:32:30 +00:00
|
|
|
response_result[response_list_name].extend(next_batch[response_list_name])
|
|
|
|
|
2024-11-10 18:55:13 +00:00
|
|
|
def _handle_response_error_code(
|
|
|
|
self, resp_dict: dict, method: str, raise_on_error: bool = True
|
|
|
|
) -> None:
|
2024-06-27 14:58:45 +00:00
|
|
|
error_code_raw = resp_dict.get("error_code")
|
|
|
|
try:
|
2024-06-30 09:49:59 +00:00
|
|
|
error_code = SmartErrorCode.from_int(error_code_raw)
|
2024-06-27 14:58:45 +00:00
|
|
|
except ValueError:
|
2024-07-11 15:21:59 +00:00
|
|
|
_LOGGER.warning(
|
|
|
|
"Device %s received unknown error code: %s", self._host, error_code_raw
|
|
|
|
)
|
2024-06-27 14:58:45 +00:00
|
|
|
error_code = SmartErrorCode.INTERNAL_UNKNOWN_ERROR
|
|
|
|
|
2024-06-30 09:49:59 +00:00
|
|
|
if error_code is SmartErrorCode.SUCCESS:
|
2023-12-20 17:08:04 +00:00
|
|
|
return
|
2024-06-27 14:58:45 +00:00
|
|
|
|
2024-02-15 18:10:34 +00:00
|
|
|
if not raise_on_error:
|
|
|
|
resp_dict["result"] = error_code
|
|
|
|
return
|
2024-06-27 14:58:45 +00:00
|
|
|
|
2023-12-20 17:08:04 +00:00
|
|
|
msg = (
|
|
|
|
f"Error querying device: {self._host}: "
|
|
|
|
+ f"{error_code.name}({error_code.value})"
|
2024-02-15 18:10:34 +00:00
|
|
|
+ f" for method: {method}"
|
2023-12-20 17:08:04 +00:00
|
|
|
)
|
|
|
|
if error_code in SMART_RETRYABLE_ERRORS:
|
2024-02-21 15:52:55 +00:00
|
|
|
raise _RetryableError(msg, error_code=error_code)
|
2023-12-20 17:08:04 +00:00
|
|
|
if error_code in SMART_AUTHENTICATION_ERRORS:
|
2024-02-21 15:52:55 +00:00
|
|
|
raise AuthenticationError(msg, error_code=error_code)
|
|
|
|
raise DeviceError(msg, error_code=error_code)
|
2023-12-04 18:50:05 +00:00
|
|
|
|
|
|
|
async def close(self) -> None:
|
2024-01-23 22:15:18 +00:00
|
|
|
"""Close the underlying transport."""
|
2023-12-04 18:50:05 +00:00
|
|
|
await self._transport.close()
|
|
|
|
|
|
|
|
|
2024-01-29 16:11:29 +00:00
|
|
|
class _ChildProtocolWrapper(SmartProtocol):
|
|
|
|
"""Protocol wrapper for controlling child devices.
|
|
|
|
|
|
|
|
This is an internal class used to communicate with child devices,
|
|
|
|
and should not be used directly.
|
|
|
|
|
|
|
|
This class overrides query() method of the protocol to modify all
|
|
|
|
outgoing queries to use ``control_child`` command, and unwraps the
|
|
|
|
device responses before returning to the caller.
|
|
|
|
"""
|
|
|
|
|
2024-11-10 18:55:13 +00:00
|
|
|
def __init__(self, device_id: str, base_protocol: SmartProtocol) -> None:
|
2024-01-29 16:11:29 +00:00
|
|
|
self._device_id = device_id
|
|
|
|
self._protocol = base_protocol
|
|
|
|
self._transport = base_protocol._transport
|
|
|
|
|
2024-11-10 18:55:13 +00:00
|
|
|
def _get_method_and_params_for_request(self, request: dict[str, Any] | str) -> Any:
|
2024-01-29 16:11:29 +00:00
|
|
|
"""Return payload for wrapping.
|
|
|
|
|
|
|
|
TODO: this does not support batches and requires refactoring in the future.
|
|
|
|
"""
|
|
|
|
if isinstance(request, dict):
|
|
|
|
if len(request) == 1:
|
|
|
|
smart_method = next(iter(request))
|
|
|
|
smart_params = request[smart_method]
|
|
|
|
else:
|
|
|
|
smart_method = "multipleRequest"
|
|
|
|
requests = [
|
|
|
|
{"method": method, "params": params}
|
2024-07-23 18:02:20 +00:00
|
|
|
if params
|
|
|
|
else {"method": method}
|
2024-01-29 16:11:29 +00:00
|
|
|
for method, params in request.items()
|
|
|
|
]
|
|
|
|
smart_params = {"requests": requests}
|
|
|
|
else:
|
|
|
|
smart_method = request
|
|
|
|
smart_params = None
|
|
|
|
|
|
|
|
return smart_method, smart_params
|
|
|
|
|
2024-04-17 13:39:24 +00:00
|
|
|
async def query(self, request: str | dict, retry_count: int = 3) -> dict:
|
2024-07-04 07:02:50 +00:00
|
|
|
"""Wrap request inside control_child envelope."""
|
|
|
|
return await self._query(request, retry_count)
|
|
|
|
|
|
|
|
async def _query(self, request: str | dict, retry_count: int = 3) -> dict:
|
2024-01-29 16:11:29 +00:00
|
|
|
"""Wrap request inside control_child envelope."""
|
|
|
|
method, params = self._get_method_and_params_for_request(request)
|
|
|
|
request_data = {
|
|
|
|
"method": method,
|
|
|
|
"params": params,
|
|
|
|
}
|
|
|
|
wrapped_payload = {
|
|
|
|
"control_child": {
|
|
|
|
"device_id": self._device_id,
|
|
|
|
"requestData": request_data,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
response = await self._protocol.query(wrapped_payload, retry_count)
|
|
|
|
result = response.get("control_child")
|
|
|
|
# Unwrap responseData for control_child
|
|
|
|
if result and (response_data := result.get("responseData")):
|
|
|
|
result = response_data.get("result")
|
2024-02-26 16:13:46 +00:00
|
|
|
if result and (multi_responses := result.get("responses")):
|
|
|
|
ret_val = {}
|
|
|
|
for multi_response in multi_responses:
|
|
|
|
method = multi_response["method"]
|
2024-06-03 18:41:55 +00:00
|
|
|
self._handle_response_error_code(
|
|
|
|
multi_response, method, raise_on_error=False
|
|
|
|
)
|
2024-02-26 16:13:46 +00:00
|
|
|
ret_val[method] = multi_response.get("result")
|
|
|
|
return ret_val
|
2024-01-29 16:11:29 +00:00
|
|
|
|
2024-02-26 16:13:46 +00:00
|
|
|
self._handle_response_error_code(response_data, "control_child")
|
2024-01-29 16:11:29 +00:00
|
|
|
|
|
|
|
return {method: result}
|
|
|
|
|
|
|
|
async def close(self) -> None:
|
|
|
|
"""Do nothing as the parent owns the protocol."""
|