diff --git a/roborock/devices/device.py b/roborock/devices/device.py index 44c275f6c..d57b451b0 100644 --- a/roborock/devices/device.py +++ b/roborock/devices/device.py @@ -255,6 +255,10 @@ def diagnostic_data(self) -> dict[str, Any]: extra: dict[str, Any] = {} if self.v1_properties: extra["traits"] = self.v1_properties.as_dict() + elif self.dyad: + extra["traits"] = self.dyad.as_dict() + elif self.zeo: + extra["traits"] = self.zeo.as_dict() elif self.b01_q10_properties: extra["traits"] = self.b01_q10_properties.as_dict() return redact_device_data( diff --git a/roborock/devices/traits/a01/__init__.py b/roborock/devices/traits/a01/__init__.py index 7682bc7f8..9d2cb47b2 100644 --- a/roborock/devices/traits/a01/__init__.py +++ b/roborock/devices/traits/a01/__init__.py @@ -31,7 +31,14 @@ from datetime import UTC, datetime, time from typing import Any, Generic, TypeVar -from roborock.data import DyadProductInfo, DyadScheduleTask, DyadSndState, HomeDataProduct, RoborockCategory +from roborock.data import ( + DyadProductInfo, + DyadScheduleTask, + DyadSndState, + HomeDataProduct, + RoborockBase, + RoborockCategory, +) from roborock.data.dyad.dyad_code_mappings import ( DyadBrushSpeed, DyadCleanAssistPower, @@ -72,7 +79,7 @@ from roborock.devices.traits.common import TraitUpdateListener from roborock.devices.transport.mqtt_channel import MqttChannel from roborock.exceptions import RoborockException -from roborock.protocols.a01_protocol import decode_rpc_response +from roborock.protocols.a01_protocol import decode_datapoint_value, decode_rpc_response from roborock.roborock_message import ( RoborockDyadDataProtocol, RoborockMessage, @@ -89,11 +96,13 @@ ] -def _decode_dyad_schedule(value: str) -> list[DyadScheduleTask]: - """Decode the schedule data point, which is a JSON list or an empty string.""" +def _decode_dyad_schedule(value: Any) -> list[DyadScheduleTask]: + """Decode the schedule data point, a list of tasks or an empty string when there are none.""" if not value: return [] - return [DyadScheduleTask.from_dict(task) for task in json.loads(value)] + if not isinstance(value, list): + raise ValueError(f"Unexpected schedule value: {value!r}") + return [DyadScheduleTask.from_dict(task) for task in value] DYAD_PROTOCOL_ENTRIES: dict[RoborockDyadDataProtocol, Callable] = { @@ -191,6 +200,17 @@ def convert_zeo_value(protocol_value: RoborockZeoProtocol, value: Any) -> Any: return None +def _diagnostic_value(value: Any) -> Any: + """Convert a decoded value to plain data for diagnostics.""" + if isinstance(value, RoborockBase): + return value.as_dict() + if isinstance(value, list): + return [_diagnostic_value(item) for item in value] + if isinstance(value, time): + return value.isoformat() + return value + + _DYAD_PROTOCOL_VALUES = frozenset(protocol.value for protocol in RoborockDyadDataProtocol) _ZEO_PROTOCOL_VALUES = frozenset(protocol.value for protocol in RoborockZeoProtocol) @@ -225,6 +245,10 @@ def values(self) -> dict[_P, Any]: """ return dict(self._values) + def as_dict(self) -> dict[str, Any]: + """Return the latest known state as plain data for diagnostics.""" + return {protocol.name: _diagnostic_value(value) for protocol, value in self._values.items()} + @property def last_message_time(self) -> datetime | None: """Time the last message was received from the device. @@ -459,11 +483,11 @@ async def set_value(self, protocol: RoborockZeoProtocol, value: Any) -> dict[Rob def _parse_device_status(device_status: dict | None) -> dict[int, Any] | None: - """Normalize the cloud home data status snapshot to integer datapoint codes.""" + """Normalize the cloud home data status snapshot to integer datapoint codes and decoded values.""" if not device_status: return None try: - return {int(code): value for code, value in device_status.items()} + return {int(code): decode_datapoint_value(value) for code, value in device_status.items()} except (TypeError, ValueError): _LOGGER.debug("Ignoring malformed device status snapshot: %s", device_status) return None diff --git a/roborock/diagnostics.py b/roborock/diagnostics.py index 26d1e89c7..e94cbb7f7 100644 --- a/roborock/diagnostics.py +++ b/roborock/diagnostics.py @@ -9,11 +9,12 @@ DeviceManager. """ +import json import time from collections import Counter from collections.abc import Generator, Mapping from contextlib import contextmanager -from typing import Any, Self, TypeVar, cast +from typing import Any, Self, TypeVar, overload class Diagnostics: @@ -106,7 +107,9 @@ def reset(self) -> None: "ipAddress", "ipAdress", "wifiName", + "ssid", "rawName", + "iotName", "lat", "long", } @@ -123,13 +126,46 @@ def reset(self) -> None: REDACTED = "**REDACTED**" -def redact_device_data(data: T, path: str = "") -> T | dict[str, Any]: - """Redact sensitive data in a dict.""" +def _decode_json_string(value: str) -> Any: + """Decode a JSON object or array stored as a string. + + Some devices report structured data this way, such as the A01 product info + data point. Any other string is returned unchanged. + + `roborock.protocols.a01_protocol.decode_datapoint_value` does the same for A01 + data points. This module cannot import it: `roborock.util` imports this module, + so the import would be circular. + """ + if not value.lstrip().startswith(("{", "[")): + return value + try: + return json.loads(value) + except json.JSONDecodeError: + return value + + +@overload +def redact_device_data(data: Mapping[str, Any], path: str = "") -> dict[str, Any]: ... + + +@overload +def redact_device_data(data: T, path: str = "") -> T | dict[str, Any] | list[Any]: ... + + +def redact_device_data(data: Any, path: str = "") -> Any: + """Redact sensitive data in a dict or list. + + Strings holding a JSON object or array are decoded and redacted, so a string + input can return a dict or a list. Other values are returned unchanged. + """ + if isinstance(data, str): + data = _decode_json_string(data) + if not isinstance(data, (Mapping, list)): return data if isinstance(data, list): - return cast(T, [redact_device_data(item, path) for item in data]) + return [redact_device_data(item, path) for item in data] redacted = {**data} @@ -141,7 +177,7 @@ def redact_device_data(data: T, path: str = "") -> T | dict[str, Any]: redacted[key] = REDACTED elif key == DEVICE_UID and isinstance(value, str): redacted[key] = redact_device_uid(value) - elif isinstance(value, dict): + elif isinstance(value, (dict, str)): redacted[key] = redact_device_data(value, curr_path) elif isinstance(value, list): redacted[key] = [redact_device_data(item, curr_path) for item in value] diff --git a/roborock/protocols/a01_protocol.py b/roborock/protocols/a01_protocol.py index 27889752d..caeb88f73 100644 --- a/roborock/protocols/a01_protocol.py +++ b/roborock/protocols/a01_protocol.py @@ -55,6 +55,20 @@ def encode_mqtt_payload( ) +def decode_datapoint_value(value: Any) -> Any: + """Decode a data point value that holds a JSON object or array stored as a string. + + Some data points are sent this way, such as the Dyad schedule and product info. + Other values, including strings that are not valid JSON, are returned unchanged. + """ + if not isinstance(value, str) or not value.lstrip().startswith(("{", "[")): + return value + try: + return json.loads(value) + except json.JSONDecodeError: + return value + + def decode_rpc_response(message: RoborockMessage) -> dict[int, Any]: """Decode a V1 RPC_RESPONSE message.""" if not message.payload: @@ -73,7 +87,7 @@ def decode_rpc_response(message: RoborockMessage) -> dict[int, Any]: if not isinstance(datapoints, dict): raise RoborockException(f"Invalid A01 message format: 'dps' should be a dictionary for {message.payload!r}") try: - return {int(key): value for key, value in datapoints.items()} + return {int(key): decode_datapoint_value(value) for key, value in datapoints.items()} except ValueError as err: raise RoborockException( f"Invalid A01 message format: 'dps' key should be an integer for {message.payload!r}" diff --git a/roborock/testing/a01_simulator.py b/roborock/testing/a01_simulator.py index 472d440cd..a246a4d03 100644 --- a/roborock/testing/a01_simulator.py +++ b/roborock/testing/a01_simulator.py @@ -161,17 +161,8 @@ async def _handle_publish(self, message: RoborockMessage, channel: Any) -> None: id_query_key = int(RoborockDyadDataProtocol.ID_QUERY) if query_raw := decoded_dps.get(id_query_key): - query_list: list[Any] = [] - if isinstance(query_raw, str): - try: - parsed = json.loads(query_raw) - if isinstance(parsed, list): - query_list = parsed - except (json.JSONDecodeError, TypeError): - pass - elif isinstance(query_raw, list): - query_list = query_raw - + # decode_rpc_response already decodes the JSON list of requested data points. + query_list: list[Any] = query_raw if isinstance(query_raw, list) else [] for key_val in query_list: key_int = int(_extract_int_value(key_val)) if key_int in self.status: @@ -184,7 +175,8 @@ async def _handle_publish(self, message: RoborockMessage, channel: Any) -> None: # Direct setters: update internal state for received DPS for code, val in decoded_dps.items(): if code != id_query_key: - self.status[code] = val + # Keep JSON values in the string form the device sends. + self.status[code] = json.dumps(val) if isinstance(val, (dict, list)) else val updated_dps[code] = val if updated_dps: diff --git a/tests/devices/__snapshots__/test_device_manager.ambr b/tests/devices/__snapshots__/test_device_manager.ambr index dadae5983..a0dc2e419 100644 --- a/tests/devices/__snapshots__/test_device_manager.ambr +++ b/tests/devices/__snapshots__/test_device_manager.ambr @@ -18,7 +18,9 @@ '133': 1, }), 'duid': '******bc123', - 'extra': '{"RRPhotoPrivacyVersion": "1"}', + 'extra': dict({ + 'RRPhotoPrivacyVersion': '1', + }), 'featureSet': '2234201184108543', 'fv': '02.56.02', 'iconUrl': 'no_url', @@ -62,7 +64,10 @@ 'id': '120', 'mode': 'ro', 'name': '错误代码', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -70,7 +75,10 @@ 'id': '121', 'mode': 'ro', 'name': '设备状态', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -78,7 +86,10 @@ 'id': '122', 'mode': 'ro', 'name': '设备电量', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -86,7 +97,10 @@ 'id': '123', 'mode': 'rw', 'name': '清扫模式', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -94,7 +108,10 @@ 'id': '124', 'mode': 'rw', 'name': '拖地模式', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -102,7 +119,13 @@ 'id': '125', 'mode': 'rw', 'name': '主刷寿命', - 'property': '{"max": 100, "min": 0, "step": 1, "unit": null, "scale": 1}', + 'property': dict({ + 'max': 100, + 'min': 0, + 'scale': 1, + 'step': 1, + 'unit': None, + }), 'type': 'VALUE', }), dict({ @@ -110,7 +133,13 @@ 'id': '126', 'mode': 'rw', 'name': '边刷寿命', - 'property': '{"max": 100, "min": 0, "step": 1, "unit": null, "scale": 1}', + 'property': dict({ + 'max': 100, + 'min': 0, + 'scale': 1, + 'step': 1, + 'unit': None, + }), 'type': 'VALUE', }), dict({ @@ -118,7 +147,13 @@ 'id': '127', 'mode': 'rw', 'name': '滤网寿命', - 'property': '{"max": 100, "min": 0, "step": 1, "unit": null, "scale": 1}', + 'property': dict({ + 'max': 100, + 'min': 0, + 'scale': 1, + 'step': 1, + 'unit': None, + }), 'type': 'VALUE', }), dict({ @@ -443,7 +478,9 @@ '133': 1, }), 'duid': '******bc123', - 'extra': '{"RRPhotoPrivacyVersion": "1"}', + 'extra': dict({ + 'RRPhotoPrivacyVersion': '1', + }), 'featureSet': '2234201184108543', 'fv': '02.56.02', 'iconUrl': 'no_url', @@ -491,7 +528,10 @@ 'id': '**REDACTED**', 'mode': 'ro', 'name': '**REDACTED**', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -499,7 +539,10 @@ 'id': '**REDACTED**', 'mode': 'ro', 'name': '**REDACTED**', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -507,7 +550,10 @@ 'id': '**REDACTED**', 'mode': 'ro', 'name': '**REDACTED**', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -515,7 +561,10 @@ 'id': '**REDACTED**', 'mode': 'rw', 'name': '**REDACTED**', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -523,7 +572,10 @@ 'id': '**REDACTED**', 'mode': 'rw', 'name': '**REDACTED**', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -531,7 +583,13 @@ 'id': '**REDACTED**', 'mode': 'rw', 'name': '**REDACTED**', - 'property': '{"max": 100, "min": 0, "step": 1, "unit": null, "scale": 1}', + 'property': dict({ + 'max': 100, + 'min': 0, + 'scale': 1, + 'step': 1, + 'unit': None, + }), 'type': 'VALUE', }), dict({ @@ -539,7 +597,13 @@ 'id': '**REDACTED**', 'mode': 'rw', 'name': '**REDACTED**', - 'property': '{"max": 100, "min": 0, "step": 1, "unit": null, "scale": 1}', + 'property': dict({ + 'max': 100, + 'min': 0, + 'scale': 1, + 'step': 1, + 'unit': None, + }), 'type': 'VALUE', }), dict({ @@ -547,7 +611,13 @@ 'id': '**REDACTED**', 'mode': 'rw', 'name': '**REDACTED**', - 'property': '{"max": 100, "min": 0, "step": 1, "unit": null, "scale": 1}', + 'property': dict({ + 'max': 100, + 'min': 0, + 'scale': 1, + 'step': 1, + 'unit': None, + }), 'type': 'VALUE', }), dict({ diff --git a/tests/devices/__snapshots__/test_v1_device.ambr b/tests/devices/__snapshots__/test_v1_device.ambr index bc0d8fdb3..7653cf3f7 100644 --- a/tests/devices/__snapshots__/test_v1_device.ambr +++ b/tests/devices/__snapshots__/test_v1_device.ambr @@ -19,7 +19,9 @@ '133': 1, }), 'duid': '******bc123', - 'extra': '{"RRPhotoPrivacyVersion": "1"}', + 'extra': dict({ + 'RRPhotoPrivacyVersion': '1', + }), 'featureSet': '2234201184108543', 'fv': '02.56.02', 'iconUrl': 'no_url', @@ -63,7 +65,10 @@ 'id': '120', 'mode': 'ro', 'name': '错误代码', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -71,7 +76,10 @@ 'id': '121', 'mode': 'ro', 'name': '设备状态', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -79,7 +87,10 @@ 'id': '122', 'mode': 'ro', 'name': '设备电量', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -87,7 +98,10 @@ 'id': '123', 'mode': 'rw', 'name': '清扫模式', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -95,7 +109,10 @@ 'id': '124', 'mode': 'rw', 'name': '拖地模式', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -103,7 +120,13 @@ 'id': '125', 'mode': 'rw', 'name': '主刷寿命', - 'property': '{"max": 100, "min": 0, "step": 1, "unit": null, "scale": 1}', + 'property': dict({ + 'max': 100, + 'min': 0, + 'scale': 1, + 'step': 1, + 'unit': None, + }), 'type': 'VALUE', }), dict({ @@ -111,7 +134,13 @@ 'id': '126', 'mode': 'rw', 'name': '边刷寿命', - 'property': '{"max": 100, "min": 0, "step": 1, "unit": null, "scale": 1}', + 'property': dict({ + 'max': 100, + 'min': 0, + 'scale': 1, + 'step': 1, + 'unit': None, + }), 'type': 'VALUE', }), dict({ @@ -119,7 +148,13 @@ 'id': '127', 'mode': 'rw', 'name': '滤网寿命', - 'property': '{"max": 100, "min": 0, "step": 1, "unit": null, "scale": 1}', + 'property': dict({ + 'max': 100, + 'min': 0, + 'scale': 1, + 'step': 1, + 'unit': None, + }), 'type': 'VALUE', }), dict({ @@ -467,7 +502,9 @@ '133': 1, }), 'duid': '******bc123', - 'extra': '{"RRPhotoPrivacyVersion": "1"}', + 'extra': dict({ + 'RRPhotoPrivacyVersion': '1', + }), 'featureSet': '2234201184108543', 'fv': '02.56.02', 'iconUrl': 'no_url', @@ -511,7 +548,10 @@ 'id': '120', 'mode': 'ro', 'name': '错误代码', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -519,7 +559,10 @@ 'id': '121', 'mode': 'ro', 'name': '设备状态', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -527,7 +570,10 @@ 'id': '122', 'mode': 'ro', 'name': '设备电量', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -535,7 +581,10 @@ 'id': '123', 'mode': 'rw', 'name': '清扫模式', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -543,7 +592,10 @@ 'id': '124', 'mode': 'rw', 'name': '拖地模式', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -551,7 +603,13 @@ 'id': '125', 'mode': 'rw', 'name': '主刷寿命', - 'property': '{"max": 100, "min": 0, "step": 1, "unit": null, "scale": 1}', + 'property': dict({ + 'max': 100, + 'min': 0, + 'scale': 1, + 'step': 1, + 'unit': None, + }), 'type': 'VALUE', }), dict({ @@ -559,7 +617,13 @@ 'id': '126', 'mode': 'rw', 'name': '边刷寿命', - 'property': '{"max": 100, "min": 0, "step": 1, "unit": null, "scale": 1}', + 'property': dict({ + 'max': 100, + 'min': 0, + 'scale': 1, + 'step': 1, + 'unit': None, + }), 'type': 'VALUE', }), dict({ @@ -567,7 +631,13 @@ 'id': '127', 'mode': 'rw', 'name': '滤网寿命', - 'property': '{"max": 100, "min": 0, "step": 1, "unit": null, "scale": 1}', + 'property': dict({ + 'max': 100, + 'min': 0, + 'scale': 1, + 'step': 1, + 'unit': None, + }), 'type': 'VALUE', }), dict({ @@ -895,7 +965,9 @@ '133': 1, }), 'duid': '******bc123', - 'extra': '{"RRPhotoPrivacyVersion": "1"}', + 'extra': dict({ + 'RRPhotoPrivacyVersion': '1', + }), 'featureSet': '2234201184108543', 'fv': '02.56.02', 'iconUrl': 'no_url', @@ -939,7 +1011,10 @@ 'id': '120', 'mode': 'ro', 'name': '错误代码', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -947,7 +1022,10 @@ 'id': '121', 'mode': 'ro', 'name': '设备状态', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -955,7 +1033,10 @@ 'id': '122', 'mode': 'ro', 'name': '设备电量', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -963,7 +1044,10 @@ 'id': '123', 'mode': 'rw', 'name': '清扫模式', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -971,7 +1055,10 @@ 'id': '124', 'mode': 'rw', 'name': '拖地模式', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -979,7 +1066,13 @@ 'id': '125', 'mode': 'rw', 'name': '主刷寿命', - 'property': '{"max": 100, "min": 0, "step": 1, "unit": null, "scale": 1}', + 'property': dict({ + 'max': 100, + 'min': 0, + 'scale': 1, + 'step': 1, + 'unit': None, + }), 'type': 'VALUE', }), dict({ @@ -987,7 +1080,13 @@ 'id': '126', 'mode': 'rw', 'name': '边刷寿命', - 'property': '{"max": 100, "min": 0, "step": 1, "unit": null, "scale": 1}', + 'property': dict({ + 'max': 100, + 'min': 0, + 'scale': 1, + 'step': 1, + 'unit': None, + }), 'type': 'VALUE', }), dict({ @@ -995,7 +1094,13 @@ 'id': '127', 'mode': 'rw', 'name': '滤网寿命', - 'property': '{"max": 100, "min": 0, "step": 1, "unit": null, "scale": 1}', + 'property': dict({ + 'max': 100, + 'min': 0, + 'scale': 1, + 'step': 1, + 'unit': None, + }), 'type': 'VALUE', }), dict({ @@ -1293,7 +1398,9 @@ '133': 1, }), 'duid': '******bc123', - 'extra': '{"RRPhotoPrivacyVersion": "1"}', + 'extra': dict({ + 'RRPhotoPrivacyVersion': '1', + }), 'featureSet': '2234201184108543', 'fv': '02.56.02', 'iconUrl': 'no_url', @@ -1337,7 +1444,10 @@ 'id': '120', 'mode': 'ro', 'name': '错误代码', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -1345,7 +1455,10 @@ 'id': '121', 'mode': 'ro', 'name': '设备状态', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -1353,7 +1466,10 @@ 'id': '122', 'mode': 'ro', 'name': '设备电量', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -1361,7 +1477,10 @@ 'id': '123', 'mode': 'rw', 'name': '清扫模式', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -1369,7 +1488,10 @@ 'id': '124', 'mode': 'rw', 'name': '拖地模式', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -1377,7 +1499,13 @@ 'id': '125', 'mode': 'rw', 'name': '主刷寿命', - 'property': '{"max": 100, "min": 0, "step": 1, "unit": null, "scale": 1}', + 'property': dict({ + 'max': 100, + 'min': 0, + 'scale': 1, + 'step': 1, + 'unit': None, + }), 'type': 'VALUE', }), dict({ @@ -1385,7 +1513,13 @@ 'id': '126', 'mode': 'rw', 'name': '边刷寿命', - 'property': '{"max": 100, "min": 0, "step": 1, "unit": null, "scale": 1}', + 'property': dict({ + 'max': 100, + 'min': 0, + 'scale': 1, + 'step': 1, + 'unit': None, + }), 'type': 'VALUE', }), dict({ @@ -1393,7 +1527,13 @@ 'id': '127', 'mode': 'rw', 'name': '滤网寿命', - 'property': '{"max": 100, "min": 0, "step": 1, "unit": null, "scale": 1}', + 'property': dict({ + 'max': 100, + 'min': 0, + 'scale': 1, + 'step': 1, + 'unit': None, + }), 'type': 'VALUE', }), dict({ diff --git a/tests/devices/test_a01_traits.py b/tests/devices/test_a01_traits.py index 83a5b5cb3..2250911d5 100644 --- a/tests/devices/test_a01_traits.py +++ b/tests/devices/test_a01_traits.py @@ -1,9 +1,18 @@ +import json +from dataclasses import replace from unittest.mock import AsyncMock, Mock, patch import pytest -from roborock.devices.traits.a01 import DyadApi, ZeoApi +from roborock.devices.device import RoborockDevice +from roborock.devices.traits.a01 import DyadApi, ZeoApi, create from roborock.roborock_message import RoborockDyadDataProtocol, RoborockZeoProtocol +from roborock.testing.a01_simulator import ( + DEFAULT_DYAD_DEVICE_INFO, + DEFAULT_DYAD_PRODUCT, + DEFAULT_ZEO_DEVICE_INFO, + DEFAULT_ZEO_PRODUCT, +) @pytest.fixture @@ -51,3 +60,58 @@ async def test_zeo_query_values(mock_channel): assert RoborockZeoProtocol.STATE in result assert result[RoborockZeoProtocol.STATE] == "spinning" assert result[RoborockZeoProtocol.COUNTDOWN] == 120 + + +DYAD_PRODUCT_INFO_JSON = json.dumps( + { + "sn": "TESTSERIAL", + "ssid": "test-network", + "timezone": "Europe/Warsaw", + "posix_timezone": "CET-1CEST,M3.5.0/2,M10.5.0/3", + "ip": "192.0.2.1", + "mac": "00:00:5e:00:53:01", + "oba": {"bom": "A.01"}, + } +) + + +@pytest.mark.parametrize( + ("product", "device_info", "device_status", "expected_traits"), + [ + ( + DEFAULT_DYAD_PRODUCT, + DEFAULT_DYAD_DEVICE_INFO, + {"201": 3, "10005": DYAD_PRODUCT_INFO_JSON}, + {"status": "charging", "product_info": {"timezone": "Europe/Warsaw"}}, + ), + ( + DEFAULT_ZEO_PRODUCT, + DEFAULT_ZEO_DEVICE_INFO, + {"203": 1, "217": 5}, + {"state": "standby", "countdown": 5}, + ), + ], + ids=["dyad", "zeo"], +) +def test_a01_diagnostic_data_includes_redacted_traits( + mock_channel, product, device_info, device_status, expected_traits +): + """A01 diagnostics report the decoded state without identifiers.""" + device = RoborockDevice( + device_info=replace(device_info, device_status=device_status), + product=product, + channel=AsyncMock(), + trait=create(product, mock_channel, device_status=device_status), + ) + + diagnostics = device.diagnostic_data() + + dumped = json.dumps(diagnostics) + for private_value in ("TESTSERIAL", "test-network", "192.0.2.1", "00:00:5e:00:53:01"): + assert private_value not in dumped + traits = diagnostics["traits"] + for name, expected in expected_traits.items(): + if isinstance(expected, dict): + assert expected.items() <= traits[name].items() + else: + assert traits[name] == expected diff --git a/tests/devices/traits/a01/test_init.py b/tests/devices/traits/a01/test_init.py index aea824e6f..f8db9e91f 100644 --- a/tests/devices/traits/a01/test_init.py +++ b/tests/devices/traits/a01/test_init.py @@ -324,6 +324,95 @@ async def test_create_seeds_values_from_device_status(fake_channel: FakeChannel) } +PRODUCT_INFO_JSON = json.dumps( + { + "sn": "TESTSERIAL", + "ssid": "test-network", + "timezone": "Europe/Warsaw", + "posix_timezone": "CET-1CEST,M3.5.0/2,M10.5.0/3", + "ip": "192.0.2.1", + "mac": "00:00:5e:00:53:01", + "rssi": -53, + "oba": {"bom": "A.01"}, + } +) + + +SND_STATE_JSON = '{"sid_in_use":21,"sid_version":3,"location":"de","bom":"A.01","language":"en"}' + + +def assert_json_string_data_points_decoded(values: dict[RoborockDyadDataProtocol, Any]) -> None: + assert values[RoborockDyadDataProtocol.SND_STATE].sid_in_use == 21 + product_info = values[RoborockDyadDataProtocol.PRODUCT_INFO] + assert product_info.sn == "TESTSERIAL" + assert product_info.posix_timezone == "CET-1CEST,M3.5.0/2,M10.5.0/3" + assert product_info.oba == {"bom": "A.01"} + + +async def test_dyad_decodes_json_string_data_points_from_status_snapshot(fake_channel: FakeChannel): + """The cloud status snapshot holds product info and voice pack state as JSON strings.""" + api = create( + DEFAULT_DYAD_PRODUCT, + fake_channel, # type: ignore[arg-type] + device_status={"10004": SND_STATE_JSON, "10005": PRODUCT_INFO_JSON}, + ) + + assert_json_string_data_points_decoded(api.values) # type: ignore[arg-type] + + +async def test_dyad_decodes_json_string_data_points_from_push(dyad_api: DyadApi, fake_channel: FakeChannel): + """The device pushes product info and voice pack state as JSON strings over MQTT.""" + await dyad_api.start() + fake_channel.notify_subscribers(build_a01_message({10004: SND_STATE_JSON, 10005: PRODUCT_INFO_JSON})) + + assert_json_string_data_points_decoded(dyad_api.values) + + +async def test_dyad_decodes_json_string_data_points_from_query(dyad_api: DyadApi, fake_channel: FakeChannel): + """Query responses over MQTT hold product info and voice pack state as JSON strings.""" + fake_channel.response_queue.append(build_a01_message({10004: SND_STATE_JSON, 10005: PRODUCT_INFO_JSON})) + + result = await dyad_api.query_values([RoborockDyadDataProtocol.SND_STATE, RoborockDyadDataProtocol.PRODUCT_INFO]) + + assert_json_string_data_points_decoded(result) + + +@pytest.mark.parametrize("value", ["", "not json", None]) +async def test_dyad_invalid_json_string_data_point(fake_channel: FakeChannel, value: str | None): + """A malformed JSON data point leaves the value unset.""" + api = create(DEFAULT_DYAD_PRODUCT, fake_channel, device_status={"10005": value}) # type: ignore[arg-type] + + assert api.values == {} + + +async def test_dyad_as_dict_is_plain_data(fake_channel: FakeChannel): + """Decoded values are converted to JSON serializable data for diagnostics.""" + api = create( + DEFAULT_DYAD_PRODUCT, + fake_channel, # type: ignore[arg-type] + device_status={ + "201": 3, + "227": 1320, + "10002": '[{"id":1,"on":false,"cron":"15 14 31 10 *","dpAction":{"200":1}}]', + "10005": PRODUCT_INFO_JSON, + }, + ) + + data = api.as_dict() + + assert data["status"] == "charging" + assert data["silent_mode_start_time"] == "22:00:00" + assert data["schedule_task"][0]["cron"] == "15 14 31 10 *" + assert data["product_info"]["timezone"] == "Europe/Warsaw" + + +async def test_zeo_as_dict(fake_channel: FakeChannel): + """Zeo state is keyed by data point name for diagnostics.""" + api = ZeoApi(fake_channel, initial_status={RoborockZeoProtocol.COUNTDOWN.value: 5}) # type: ignore[arg-type] + + assert api.as_dict() == {RoborockZeoProtocol.COUNTDOWN.name: 5} + + async def test_dyad_close_stops_tracking(dyad_api: DyadApi, fake_channel: FakeChannel): """After close(), pushes no longer update `values`.""" await dyad_api.start() diff --git a/tests/devices/traits/b01/q10/__snapshots__/test_status.ambr b/tests/devices/traits/b01/q10/__snapshots__/test_status.ambr index 2604e87be..ae15096ee 100644 --- a/tests/devices/traits/b01/q10/__snapshots__/test_status.ambr +++ b/tests/devices/traits/b01/q10/__snapshots__/test_status.ambr @@ -206,7 +206,10 @@ 'id': 120, 'mode': 'ro', 'name': '错误代码', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -222,7 +225,10 @@ 'id': 122, 'mode': 'ro', 'name': '设备电量', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -230,7 +236,10 @@ 'id': 123, 'mode': 'rw', 'name': '吸力档位', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -246,7 +255,10 @@ 'id': 125, 'mode': 'ro', 'name': '主刷寿命', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -254,7 +266,10 @@ 'id': 126, 'mode': 'ro', 'name': '边刷寿命', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -262,7 +277,10 @@ 'id': 127, 'mode': 'ro', 'name': '滤网寿命', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -270,7 +288,10 @@ 'id': 135, 'mode': 'ro', 'name': '离线原因', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -278,7 +299,10 @@ 'id': 136, 'mode': 'rw', 'name': '清洁次数', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -286,7 +310,10 @@ 'id': 137, 'mode': 'rw', 'name': '扫拖模式', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -294,7 +321,10 @@ 'id': 138, 'mode': 'ro', 'name': '清洁任务类型', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -302,7 +332,10 @@ 'id': 139, 'mode': 'ro', 'name': '返回基站类型', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -310,7 +343,10 @@ 'id': 140, 'mode': 'ro', 'name': '基站任务类型', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -318,7 +354,10 @@ 'id': 141, 'mode': 'ro', 'name': '清洁进度', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -334,7 +373,10 @@ 'id': 201, 'mode': 'wo', 'name': '启动清洁任务', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -342,7 +384,10 @@ 'id': 202, 'mode': 'wo', 'name': '返回基站任务', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -350,7 +395,10 @@ 'id': 203, 'mode': 'wo', 'name': '启动基站任务', - 'property': '{"range": []}', + 'property': dict({ + 'range': list([ + ]), + }), 'type': 'ENUM', }), dict({ @@ -382,7 +430,11 @@ 'id': 207, 'mode': 'rw', 'name': '用户改善计划', - 'property': '{"range": ["0,1"]}', + 'property': dict({ + 'range': list([ + '0,1', + ]), + }), 'type': 'ENUM', }), ]), diff --git a/tests/protocols/test_a01_protocol.py b/tests/protocols/test_a01_protocol.py index f60cfdff3..e50f90d80 100644 --- a/tests/protocols/test_a01_protocol.py +++ b/tests/protocols/test_a01_protocol.py @@ -5,7 +5,7 @@ import pytest from Crypto.Cipher import AES -from Crypto.Util.Padding import unpad +from Crypto.Util.Padding import pad, unpad from roborock.exceptions import RoborockException from roborock.protocols.a01_protocol import decode_rpc_response, encode_mqtt_payload @@ -143,6 +143,31 @@ def test_decode_rpc_response_string_keys(): assert result[999] == {"nested": "data"} +def test_decode_rpc_response_decodes_json_string_values(): + """Values that hold a JSON object or array as a string are decoded, other values are kept.""" + payload_data = { + "dps": { + "10005": '{"sn": "TESTSERIAL", "rssi": -53}', + "10002": '[{"id": 1, "on": false}]', + "229": "", + "1": "plain", + "2": "{not json", + "209": 100, + } + } + padded_payload = pad(json.dumps(payload_data).encode("utf-8"), AES.block_size) + message = RoborockMessage(protocol=RoborockMessageProtocol.RPC_RESPONSE, payload=padded_payload) + + assert decode_rpc_response(message) == { + 10005: {"sn": "TESTSERIAL", "rssi": -53}, + 10002: [{"id": 1, "on": False}], + 229: "", + 1: "plain", + 2: "{not json", + 209: 100, + } + + def test_decode_rpc_response_missing_payload(): """Test decoding fails when payload is missing.""" message = RoborockMessage(protocol=RoborockMessageProtocol.RPC_RESPONSE, payload=None) diff --git a/tests/test_diagnostics.py b/tests/test_diagnostics.py index 5de9a6950..81cfc8cf2 100644 --- a/tests/test_diagnostics.py +++ b/tests/test_diagnostics.py @@ -1,5 +1,8 @@ """Tests for diagnostics module.""" +import json +from typing import Any + import pytest from roborock.diagnostics import REDACTED, Diagnostics, redact_device_data, redact_device_uid, redact_topic_name @@ -106,3 +109,67 @@ def test_redact_q10_raw_room_name() -> None: assert redact_device_data( {"map": {"rooms": [{"rawName": "Owner’s bedroom"}], "currentRoom": {"rawName": "Salle d’eau"}}} ) == {"map": {"rooms": [{"rawName": REDACTED}], "currentRoom": {"rawName": REDACTED}}} + + +def test_redact_iot_room_name() -> None: + """Room names reported in the map list are as private as raw room names.""" + assert redact_device_data({"rooms": [{"iotName": "Owner’s bedroom", "tag": 1}]}) == { + "rooms": [{"iotName": REDACTED, "tag": 1}] + } + + +def test_redact_json_string_in_device_status() -> None: + """Identifiers inside a data point that holds a JSON string are redacted.""" + product_info = json.dumps( + { + "sn": "TESTSERIAL", + "ssid": "test-network", + "ip": "192.0.2.1", + "mac": "00:00:5e:00:53:01", + "rssi": -53, + "oba": {"bom": "A.01"}, + } + ) + + redacted = redact_device_data({"device": {"deviceStatus": {"10005": product_info, "209": 100}}}) + + assert redacted == { + "device": { + "deviceStatus": { + "10005": { + "sn": REDACTED, + "ssid": REDACTED, + "ip": REDACTED, + "mac": REDACTED, + "rssi": -53, + "oba": {"bom": "A.01"}, + }, + "209": 100, + } + } + } + + +def test_redact_json_string_in_list() -> None: + """JSON strings inside lists are redacted too.""" + redacted = redact_device_data({"items": ['{"ip": "192.0.2.1"}', "plain"]}) + + assert redacted == {"items": [{"ip": REDACTED}, "plain"]} + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ('{"RRPhotoPrivacyVersion": "1"}', {"RRPhotoPrivacyVersion": "1"}), + ("[1, 2, 3]", [1, 2, 3]), + ], +) +def test_redact_decodes_json_strings(value: str, expected: Any) -> None: + """JSON documents stored as strings are decoded even when there is nothing to redact.""" + assert redact_device_data({"value": value}) == {"value": expected} + + +@pytest.mark.parametrize("value", ["plain text", "", "{not json"]) +def test_redact_keeps_other_strings(value: str) -> None: + """Strings that are not JSON documents are returned unchanged.""" + assert redact_device_data({"value": value}) == {"value": value}