Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
4 changes: 4 additions & 0 deletions roborock/devices/device.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
38 changes: 31 additions & 7 deletions roborock/devices/traits/a01/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand All @@ -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] = {
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
46 changes: 41 additions & 5 deletions roborock/diagnostics.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -106,7 +107,9 @@ def reset(self) -> None:
"ipAddress",
"ipAdress",
"wifiName",
"ssid",
"rawName",
"iotName",
"lat",
"long",
}
Expand All @@ -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}

Expand All @@ -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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why drop list values?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The list case was not dropped: redact_device_data handles lists itself at the top, so the else gave the same result. That was not clear from the diff, so I restored the dict and list branches and added str to the dict branch.

elif isinstance(value, list):
redacted[key] = [redact_device_data(item, curr_path) for item in value]
Expand Down
16 changes: 15 additions & 1 deletion roborock/protocols/a01_protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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}"
Expand Down
16 changes: 4 additions & 12 deletions roborock/testing/a01_simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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:
Expand Down
Loading
Loading