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
15 changes: 13 additions & 2 deletions roborock/devices/rpc/a01_channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,11 @@ async def send_decoded_command(
) -> dict[RoborockDyadDataProtocol, Any] | dict[RoborockZeoProtocol, Any]:
"""Send a command on the MQTT channel and get a decoded response.

A query returns once every requested data point has arrived. Devices may
never report data points they do not support, so if only some arrive
before the timeout, that subset is returned. A query that receives none
of the requested data points raises `RoborockException`.

Args:
mqtt_channel: The MQTT channel to send the command on.
params: The parameters to send.
Expand Down Expand Up @@ -98,8 +103,14 @@ def find_response(response_message: RoborockMessage) -> None:
try:
await asyncio.wait_for(finished.wait(), timeout=_TIMEOUT)
except TimeoutError as ex:
await mqtt_channel.health_manager.on_timeout()
raise RoborockException(f"Command timed out after {_TIMEOUT}s") from ex
if not result:
await mqtt_channel.health_manager.on_timeout()
raise RoborockException(f"Command timed out after {_TIMEOUT}s") from ex
_LOGGER.debug(
"Partial query response after %ss, missing data points: %s",
_TIMEOUT,
[dp for dp in query_values if dp not in result],
)
finally:
unsub()

Expand Down
25 changes: 20 additions & 5 deletions roborock/devices/traits/a01/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -333,13 +333,20 @@ def _decode_datapoints(self, datapoints: dict[int, Any]) -> dict[RoborockDyadDat
return values

async def query_values(self, protocols: list[RoborockDyadDataProtocol]) -> dict[RoborockDyadDataProtocol, Any]:
"""Query the device for the values of the given Dyad protocols."""
"""Query the device for the values of the given Dyad protocols.

Every requested protocol is a key of the result; a protocol the device
did not report is `None`.
"""
response = await send_decoded_command(
self._channel,
{RoborockDyadDataProtocol.ID_QUERY: protocols},
value_encoder=json.dumps,
)
values = {protocol: convert_dyad_value(protocol, response.get(protocol)) for protocol in protocols}
values = {
protocol: convert_dyad_value(protocol, response[protocol]) if protocol in response else None
for protocol in protocols
}
self._merge_query_response(values)
return values

Expand Down Expand Up @@ -436,7 +443,8 @@ async def _force_load(self) -> None:
"""
dp_list = build_force_load_dp_list(self._model)
result = await self.query_values(dp_list)
self._feature_bits = result.get(RoborockZeoProtocol.FEATURE_BITS, 0)
if (feature_bits := result.get(RoborockZeoProtocol.FEATURE_BITS)) is not None:
self._feature_bits = feature_bits

async def _load_feature_dps(self) -> None:
"""Second-stage query for feature-gated DPs.
Expand Down Expand Up @@ -466,13 +474,20 @@ def supports(self, feature: ZeoFeatureBits) -> bool:
return bool(self._feature_bits & (1 << feature.value))

async def query_values(self, protocols: list[RoborockZeoProtocol]) -> dict[RoborockZeoProtocol, Any]:
"""Query the device for the values of the given protocols."""
"""Query the device for the values of the given protocols.

Every requested protocol is a key of the result; a protocol the device
did not report is `None`.
"""
response = await send_decoded_command(
self._channel,
{RoborockZeoProtocol.ID_QUERY: protocols},
value_encoder=json.dumps,
)
values = {protocol: convert_zeo_value(protocol, response.get(protocol)) for protocol in protocols}
values = {
protocol: convert_zeo_value(protocol, response[protocol]) if protocol in response else None
for protocol in protocols
}
self._merge_query_response(values)
return values

Expand Down
21 changes: 21 additions & 0 deletions tests/devices/rpc/test_a01_channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,3 +81,24 @@ async def test_query_timeout_reports_to_health_manager(mock_mqtt_channel: FakeCh
await send_decoded_command(mock_mqtt_channel, params) # type: ignore[call-overload]

mock_mqtt_channel.health_manager.on_timeout.assert_awaited_once()


async def test_query_returns_partial_response_after_timeout(mock_mqtt_channel: FakeChannel, monkeypatch):
"""A device that never reports a requested data point still yields the ones it sent."""
monkeypatch.setattr("roborock.devices.rpc.a01_channel._TIMEOUT", 0.01)
mock_mqtt_channel.health_manager.on_success = AsyncMock() # type: ignore[method-assign]
mock_mqtt_channel.health_manager.on_timeout = AsyncMock() # type: ignore[method-assign]

params: dict[RoborockDyadDataProtocol, Any] = {
RoborockDyadDataProtocol.ID_QUERY: [RoborockDyadDataProtocol.WARM_LEVEL, RoborockDyadDataProtocol.POWER]
}
encoded = encode_mqtt_payload({RoborockDyadDataProtocol.POWER: 75}, value_encoder=lambda x: x)
mock_mqtt_channel.response_queue.append(
RoborockMessage(protocol=RoborockMessageProtocol.RPC_RESPONSE, payload=encoded.payload, version=encoded.version)
)

result = await send_decoded_command(mock_mqtt_channel, params) # type: ignore[call-overload]

assert result == {RoborockDyadDataProtocol.POWER: 75}
mock_mqtt_channel.health_manager.on_success.assert_awaited_once()
mock_mqtt_channel.health_manager.on_timeout.assert_not_awaited()
74 changes: 74 additions & 0 deletions tests/devices/traits/a01/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from freezegun import freeze_time

from roborock.data import DyadScheduleTask
from roborock.data.zeo.zeo_code_mappings import ZeoFeatureBits
from roborock.devices.traits.a01 import DyadApi, ZeoApi, create
from roborock.devices.traits.a01.device_feature import build_force_load_dp_list
from roborock.roborock_message import RoborockDyadDataProtocol, RoborockMessageProtocol, RoborockZeoProtocol
Expand Down Expand Up @@ -559,6 +560,79 @@ async def test_zeo_invalid_response_value(
assert result == expected_result


async def test_dyad_partial_query_leaves_missing_values_none(
dyad_api: DyadApi, fake_channel: FakeChannel, monkeypatch: pytest.MonkeyPatch
):
"""A data point the device does not report is None rather than a converted default."""
monkeypatch.setattr("roborock.devices.rpc.a01_channel._TIMEOUT", 0.01)
fake_channel.response_queue.append(build_a01_message({201: 3}))

result = await dyad_api.query_values([RoborockDyadDataProtocol.STATUS, RoborockDyadDataProtocol.AUTO_DRY])

assert result == {RoborockDyadDataProtocol.STATUS: "charging", RoborockDyadDataProtocol.AUTO_DRY: None}
assert dyad_api.values == {RoborockDyadDataProtocol.STATUS: "charging"}


async def test_zeo_partial_query_keeps_known_values(fake_channel: FakeChannel, monkeypatch: pytest.MonkeyPatch):
"""Unreported data points are None and do not replace previously known values."""
monkeypatch.setattr("roborock.devices.rpc.a01_channel._TIMEOUT", 0.01)
zeo_api = ZeoApi(fake_channel, initial_status={227: 1, 214: 2}) # type: ignore[arg-type]
fake_channel.response_queue.append(build_a01_message({203: 1}))

result = await zeo_api.query_values(
[RoborockZeoProtocol.STATE, RoborockZeoProtocol.SOFTENER_TYPE, RoborockZeoProtocol.SOFTENER_EMPTY]
)

assert result == {
RoborockZeoProtocol.STATE: "standby",
RoborockZeoProtocol.SOFTENER_TYPE: None,
RoborockZeoProtocol.SOFTENER_EMPTY: None,
}
assert zeo_api.values == {
RoborockZeoProtocol.STATE: "standby",
RoborockZeoProtocol.SOFTENER_TYPE: "medium",
RoborockZeoProtocol.SOFTENER_EMPTY: True,
}


async def test_zeo_start_without_feature_bits(
zeo_api: ZeoApi, fake_channel: FakeChannel, monkeypatch: pytest.MonkeyPatch
):
"""Start succeeds when the device does not report FEATURE_BITS; no feature is supported."""
monkeypatch.setattr("roborock.devices.rpc.a01_channel._TIMEOUT", 0.01)
force_load_response = {
int(dp): 0 for dp in build_force_load_dp_list(None) if dp != RoborockZeoProtocol.FEATURE_BITS
}
fake_channel.response_queue.append(build_a01_message(force_load_response))

await zeo_api.start()

assert not any(zeo_api.supports(feature) for feature in ZeoFeatureBits)


async def test_zeo_restart_without_feature_bits_keeps_features(
zeo_api: ZeoApi, fake_channel: FakeChannel, monkeypatch: pytest.MonkeyPatch
):
"""A restart whose reply omits FEATURE_BITS keeps the previously reported features."""
monkeypatch.setattr("roborock.devices.rpc.a01_channel._TIMEOUT", 0.01)
force_load_response = {int(dp): 0 for dp in build_force_load_dp_list(None)}
force_load_response[RoborockZeoProtocol.FEATURE_BITS] = 1 << ZeoFeatureBits.dry_care.value
fake_channel.response_queue.append(build_a01_message(force_load_response))
fake_channel.response_queue.append(build_a01_message({244: 1}))
await zeo_api.start()

del force_load_response[RoborockZeoProtocol.FEATURE_BITS]
fake_channel.response_queue.append(build_a01_message(force_load_response))
fake_channel.response_queue.append(build_a01_message({244: 1}))
await zeo_api.start()

assert zeo_api.supports(ZeoFeatureBits.dry_care)
assert len(fake_channel.published_messages) == 4
assert fake_channel.published_messages[3].payload is not None
payload_data = json.loads(unpad(fake_channel.published_messages[3].payload, AES.block_size))
assert payload_data["dps"] == {"10000": "[244]"}


async def test_dyad_api_set_value(dyad_api: DyadApi, fake_channel: FakeChannel):
"""Test DyadApi set_value sends correct command."""
await dyad_api.set_value(RoborockDyadDataProtocol.POWER, 1)
Expand Down
Loading