From 6bb4aa71a1e0bdadfdd2e1511bd5178686652b2f Mon Sep 17 00:00:00 2001 From: infy1995 Date: Mon, 30 Nov 2026 10:08:52 +0100 Subject: [PATCH 1/2] feat(a01): track whether the device is online The cloud sends a notice (message protocol 500, `{"online": bool}`) on an A01 device's topic when it loses or regains the device, for example when it goes to sleep and wakes up. The library dropped it, so a sleeping device could not be told apart from one that stopped answering. `device.dyad.is_online` (and `device.zeo.is_online`) now follows the notice. Update listeners fire when it changes, and any data message from the device also marks it online. The decoder lives in `protocols/online_notice.py`, so other protocol families can use it. `A01DeviceSimulator.set_online()` simulates it. --- docs/DEVICES.md | 3 +- roborock/devices/traits/a01/__init__.py | 42 +++++++++++++---- roborock/protocols/online_notice.py | 20 ++++++++ roborock/roborock_message.py | 1 + roborock/testing/a01_simulator.py | 16 ++++++- tests/devices/traits/a01/test_init.py | 63 ++++++++++++++++++++++++- tests/protocols/test_online_notice.py | 35 ++++++++++++++ tests/testing/test_a01_simulator.py | 35 ++++++++++++++ 8 files changed, 203 insertions(+), 12 deletions(-) create mode 100644 roborock/protocols/online_notice.py create mode 100644 tests/protocols/test_online_notice.py diff --git a/docs/DEVICES.md b/docs/DEVICES.md index 6218538aa..363ff74dc 100644 --- a/docs/DEVICES.md +++ b/docs/DEVICES.md @@ -16,7 +16,8 @@ Cloud and Network. * Use `device.v1_properties.command.send()` for raw commands (start/stop). * **Washers (A01)**: Use `device.dyad` or `device.zeo` for Dyad/Zeo devices. * Read `api.values` for the latest known state, merged from query responses and unsolicited pushes. - * Use `api.add_update_listener(callback)` to be notified when `values` changes. + * Use `api.add_update_listener(callback)` to be notified when `values` or `api.is_online` changes. + * `api.is_online` follows an online notice that the Roborock cloud (not the device) sends when it loses or regains the device, for example on sleep, wake or a network drop (seen on a Dyad F25 Ultra, not yet on Zeo). Any data message also sets it to `True`. After waking, Dyad devices do not send their state by themselves. * Use `await api.query_values([...])` to poll specific data points. * Use `await api.set_value(protocol, value)` to control. * **Vacuums (B01 Q10)**: Use `device.b01_q10_properties` for Q10 series devices. diff --git a/roborock/devices/traits/a01/__init__.py b/roborock/devices/traits/a01/__init__.py index 37f153aee..ea9b42038 100644 --- a/roborock/devices/traits/a01/__init__.py +++ b/roborock/devices/traits/a01/__init__.py @@ -17,7 +17,9 @@ 3. **values**: The latest known state, merged from query responses and unsolicited pushes in arrival order. 4. **add_update_listener(callback)**: Registers a callback invoked whenever `values` - changes; read `values` from the callback to get the updated state. + or `is_online` changes; read them from the callback to get the updated state. +5. **is_online**: Whether the device is online, from the cloud's online notices and the device's data + messages. It is `None` until one of them arrives; the cloud status does not set it. The device pushes only the data points that changed, so `values` is the merged view of everything seen so far. State tracking is active once the device is connected @@ -83,6 +85,7 @@ from roborock.devices.transport.mqtt_channel import MqttChannel from roborock.exceptions import RoborockException from roborock.protocols.a01_protocol import decode_datapoint_value, decode_rpc_response +from roborock.protocols.online_notice import decode_online_notice from roborock.roborock_message import ( RoborockDyadDataProtocol, RoborockMessage, @@ -232,7 +235,7 @@ class A01Api(Trait, TraitUpdateListener, Generic[_P]): Query responses and unsolicited pushes both arrive on the same MQTT topic, so a single subscription merges every decoded message into `values` in - arrival order. Update listeners are notified whenever a value changes. + arrival order. Update listeners are notified whenever a value or `is_online` changes. """ def __init__(self, channel: MqttChannel, initial_status: dict[int, Any] | None = None) -> None: @@ -242,6 +245,7 @@ def __init__(self, channel: MqttChannel, initial_status: dict[int, Any] | None = self._values: dict[_P, Any] = {} self._unsub: Callable[[], None] | None = None self._last_message_time: datetime | None = None + self._is_online: bool | None = None if initial_status: self._merge_values(self._decode_datapoints(initial_status)) @@ -263,13 +267,18 @@ def as_dict(self) -> dict[str, Any]: def last_message_time(self) -> datetime | None: """Time the last message was received from the device. - Updated on every decoded message, even when no value changed: idle + Updated on every decoded data message, even when no value changed: idle devices push an identical heartbeat, so this is the liveness signal even when `values` stays the same and update listeners stay silent. - The initial cloud status snapshot does not count as a message. + Online notices and the initial cloud status snapshot do not update it. """ return self._last_message_time + @property + def is_online(self) -> bool | None: + """Whether the device is online, or None until the cloud's online notice or a data message arrives.""" + return self._is_online + async def start(self) -> None: """Subscribe to the device state topic and start tracking `values`.""" await self._ensure_subscribed() @@ -291,7 +300,10 @@ def _decode_datapoints(self, datapoints: dict[int, Any]) -> dict[_P, Any]: """Convert raw datapoints to typed values, skipping unknown codes.""" def _on_message(self, message: RoborockMessage) -> None: - """Handle a message on the device topic (query response or push).""" + """Handle a message on the device topic (online notice, query response or push).""" + if message.protocol == RoborockMessageProtocol.DEVICE_ONLINE: + self._on_online_notice(message) + return if message.protocol != RoborockMessageProtocol.RPC_RESPONSE: return try: @@ -300,7 +312,16 @@ def _on_message(self, message: RoborockMessage) -> None: _LOGGER.debug("Dropped malformed push message", exc_info=True) return self._last_message_time = datetime.now(UTC) - self._merge_values(self._decode_datapoints(datapoints)) + self._merge_values(self._decode_datapoints(datapoints), online=True) + + def _on_online_notice(self, message: RoborockMessage) -> None: + """Record the online state from the cloud's notice. It is not from the device: keep `last_message_time`.""" + try: + online = decode_online_notice(message) + except RoborockException: + _LOGGER.debug("Dropped malformed online notice", exc_info=True) + return + self._merge_values({}, online=online) def _merge_query_response(self, values: dict[_P, Any]) -> None: """Record a successful query response when there is no subscription. @@ -312,10 +333,10 @@ def _merge_query_response(self, values: dict[_P, Any]) -> None: if self._unsub is not None: return self._last_message_time = datetime.now(UTC) - self._merge_values(values) + self._merge_values(values, online=True) - def _merge_values(self, values: dict[_P, Any]) -> None: - """Merge decoded values into the cache and notify on change.""" + def _merge_values(self, values: dict[_P, Any], online: bool | None = None) -> None: + """Merge decoded values and the online state into the cache, notifying once if either changed.""" changed = False for protocol, value in values.items(): if value is None: @@ -323,6 +344,9 @@ def _merge_values(self, values: dict[_P, Any]) -> None: if protocol not in self._values or self._values[protocol] != value: self._values[protocol] = value changed = True + if online is not None and online != self._is_online: + self._is_online = online + changed = True if changed: self._notify_update() diff --git a/roborock/protocols/online_notice.py b/roborock/protocols/online_notice.py new file mode 100644 index 000000000..f7fbeae58 --- /dev/null +++ b/roborock/protocols/online_notice.py @@ -0,0 +1,20 @@ +"""The online notice the Roborock cloud publishes on a device's MQTT topic, shared by the protocol families.""" + +import json + +from roborock.exceptions import RoborockException +from roborock.roborock_message import RoborockMessage + + +def decode_online_notice(message: RoborockMessage) -> bool: + """Decode the cloud's plain JSON notice that it lost (False) or regained (True) a device.""" + if not message.payload: + raise RoborockException("Invalid online notice: missing payload") + try: + payload = json.loads(message.payload.decode()) + except (json.JSONDecodeError, UnicodeDecodeError) as err: + raise RoborockException(f"Invalid online notice: {err} for {message.payload!r}") from err + + if not isinstance(payload, dict) or not isinstance(online := payload.get("online"), bool): + raise RoborockException(f"Invalid online notice: expected a boolean 'online' in {message.payload!r}") + return online diff --git a/roborock/roborock_message.py b/roborock/roborock_message.py index d0a688c54..41e4ae7f6 100644 --- a/roborock/roborock_message.py +++ b/roborock/roborock_message.py @@ -17,6 +17,7 @@ class RoborockMessageProtocol(RoborockEnum): RPC_RESPONSE = 102 MAP_RESPONSE_PART = 300 # Non-final part of a map response split into multiple messages MAP_RESPONSE = 301 + DEVICE_ONLINE = 500 # Sent by the cloud when it loses or regains a device (A01 and V1) class RoborockDataProtocol(RoborockEnum): diff --git a/roborock/testing/a01_simulator.py b/roborock/testing/a01_simulator.py index a246a4d03..847f2b0cb 100644 --- a/roborock/testing/a01_simulator.py +++ b/roborock/testing/a01_simulator.py @@ -132,6 +132,18 @@ def __init__( super().__init__(duid, device_info, product, has_local_channel=False) raw_status = status or {} self.status: dict[int, Any] = {int(_extract_int_value(k)): _extract_int_value(v) for k, v in raw_status.items()} + self._is_online = True + + def set_online(self, online: bool) -> None: + """Publish the cloud's online notice. While offline, commands are ignored and no data points are pushed.""" + self._is_online = online + self.mqtt_channel.notify_subscribers( + RoborockMessage( + protocol=RoborockMessageProtocol.DEVICE_ONLINE, + version=b"1.0", + payload=json.dumps({"online": online}).encode(), + ) + ) def set_protocol_value(self, protocol: enum.Enum | int, value: Any, push: bool = False) -> None: """Set a protocol value in the simulator status. @@ -148,7 +160,7 @@ def set_protocol_value(self, protocol: enum.Enum | int, value: Any, push: bool = async def _handle_publish(self, message: RoborockMessage, channel: Any) -> None: """Process incoming A01 encrypted payload and respond.""" - if not message.payload: + if not self._is_online or not message.payload: return try: @@ -184,6 +196,8 @@ async def _handle_publish(self, message: RoborockMessage, channel: Any) -> None: def push_dps(self, dps_updates: dict[int, Any]) -> None: """Push encrypted A01 status datapoint updates to subscribers.""" + if not self._is_online: + return msg = encode_mqtt_payload(dps_updates) # type: ignore[arg-type] msg.protocol = RoborockMessageProtocol.RPC_RESPONSE self.mqtt_channel.notify_subscribers(msg) diff --git a/tests/devices/traits/a01/test_init.py b/tests/devices/traits/a01/test_init.py index e09125d57..ebf154a0d 100644 --- a/tests/devices/traits/a01/test_init.py +++ b/tests/devices/traits/a01/test_init.py @@ -10,7 +10,12 @@ from roborock.data import DyadScheduleTask 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 +from roborock.roborock_message import ( + RoborockDyadDataProtocol, + RoborockMessage, + RoborockMessageProtocol, + RoborockZeoProtocol, +) from roborock.testing.a01_simulator import DEFAULT_DYAD_PRODUCT from tests.fixtures.channel_fixtures import FakeChannel from tests.protocols.common import build_a01_message @@ -31,6 +36,15 @@ def zeo_api_fixture(fake_channel: FakeChannel) -> ZeoApi: return ZeoApi(fake_channel) # type: ignore[arg-type] +def build_online_notice(online: bool) -> RoborockMessage: + """Build the cloud's plain JSON online notice for an A01 device.""" + return RoborockMessage( + protocol=RoborockMessageProtocol.DEVICE_ONLINE, + version=b"1.0", + payload=json.dumps({"online": online}).encode(), + ) + + async def test_dyad_api_query_values(dyad_api: DyadApi, fake_channel: FakeChannel): """Test that DyadApi currently returns raw values without conversion.""" fake_channel.response_queue.append( @@ -296,6 +310,7 @@ async def test_dyad_query_values_updates_values(dyad_api: DyadApi, fake_channel: RoborockDyadDataProtocol.POWER: 80, } assert dyad_api.last_message_time is not None + assert dyad_api.is_online is True async def test_dyad_query_response_does_not_overwrite_newer_push(dyad_api: DyadApi, fake_channel: FakeChannel): @@ -452,6 +467,52 @@ async def test_dyad_close_stops_tracking(dyad_api: DyadApi, fake_channel: FakeCh assert dyad_api.values == {RoborockDyadDataProtocol.POWER: 80} +async def test_dyad_online_notice(dyad_api: DyadApi, fake_channel: FakeChannel): + updates: list[bool | None] = [] + dyad_api.add_update_listener(lambda: updates.append(dyad_api.is_online)) + await dyad_api.start() + assert dyad_api.is_online is None + + for online in (False, False, True): + fake_channel.notify_subscribers(build_online_notice(online)) + + assert updates == [False, True] + assert dyad_api.last_message_time is None + assert dyad_api.values == {} + + +async def test_dyad_message_means_online(dyad_api: DyadApi, fake_channel: FakeChannel): + await dyad_api.start() + fake_channel.notify_subscribers(build_a01_message({209: 90})) + last_message_time = dyad_api.last_message_time + fake_channel.notify_subscribers(build_online_notice(False)) + assert dyad_api.last_message_time == last_message_time + updates: list[bool | None] = [] + dyad_api.add_update_listener(lambda: updates.append(dyad_api.is_online)) + + fake_channel.notify_subscribers(build_a01_message({209: 90})) + + assert updates == [True] + + +async def test_dyad_invalid_online_notice_ignored(dyad_api: DyadApi, fake_channel: FakeChannel): + updates: list[None] = [] + dyad_api.add_update_listener(lambda: updates.append(None)) + await dyad_api.start() + + fake_channel.notify_subscribers( + RoborockMessage(protocol=RoborockMessageProtocol.DEVICE_ONLINE, version=b"1.0", payload=b"{}") + ) + + assert dyad_api.is_online is None + assert updates == [] + + +async def test_dyad_cloud_status_does_not_mean_online(fake_channel: FakeChannel): + api = create(DEFAULT_DYAD_PRODUCT, fake_channel, device_status={"209": 90}) # type: ignore[arg-type] + assert api.is_online is None + + async def test_zeo_values_track_pushes(zeo_api: ZeoApi, fake_channel: FakeChannel): """Pushed values are merged into `values` after start().""" force_load_response = {int(dp): 0 for dp in build_force_load_dp_list(None)} diff --git a/tests/protocols/test_online_notice.py b/tests/protocols/test_online_notice.py new file mode 100644 index 000000000..aff3f98de --- /dev/null +++ b/tests/protocols/test_online_notice.py @@ -0,0 +1,35 @@ +"""Tests for the online notice decoder.""" + +import pytest + +from roborock.exceptions import RoborockException +from roborock.protocol import create_mqtt_decoder, create_mqtt_encoder +from roborock.protocols.online_notice import decode_online_notice +from roborock.roborock_message import RoborockMessage, RoborockMessageProtocol + + +def _notice(payload: bytes | None) -> RoborockMessage: + return RoborockMessage(protocol=RoborockMessageProtocol.DEVICE_ONLINE, version=b"1.0", payload=payload) + + +@pytest.mark.parametrize(("payload", "online"), [(b'{"online":true}', True), (b'{"online":false}', False)]) +def test_decode_online_notice(payload: bytes, online: bool) -> None: + assert decode_online_notice(_notice(payload)) is online + + +@pytest.mark.parametrize("payload", [None, b"", b"not json", b"[true]", b"{}", b'{"online":1}', b"\xff\xfe"]) +def test_decode_online_notice_invalid(payload: bytes | None) -> None: + with pytest.raises(RoborockException): + decode_online_notice(_notice(payload)) + + +def test_decode_online_notice_mqtt_round_trip() -> None: + """The notice keeps its protocol number through the MQTT encoder and decoder.""" + local_key = "0123456789abcdef" + data = create_mqtt_encoder(local_key)(_notice(b'{"online":false}')) + + messages = create_mqtt_decoder(local_key)(data) + + assert len(messages) == 1 + assert messages[0].protocol == RoborockMessageProtocol.DEVICE_ONLINE + assert decode_online_notice(messages[0]) is False diff --git a/tests/testing/test_a01_simulator.py b/tests/testing/test_a01_simulator.py index 188885cc0..3013e2973 100644 --- a/tests/testing/test_a01_simulator.py +++ b/tests/testing/test_a01_simulator.py @@ -204,3 +204,38 @@ async def test_a01_device_manager_integration() -> None: assert zeo_status[RoborockZeoProtocol.STATE] == ZeoState.standby.name await manager.close() + + +async def test_dyad_offline_and_online() -> None: + """Losing a simulator produces only the cloud's online notice, and commands are then ignored.""" + cloud = FakeRoborockCloud() + dyad_sim = DyadSimulator(duid="dyad_offline") + cloud.add_device(dyad_sim) + + with cloud.patch_device_manager(): + manager = await create_device_manager( + user_params=UserParams(username="test_user", user_data=UserData.from_dict(USER_DATA)), + ) + devices = await manager.get_devices() + + dyad = devices[0].dyad + assert dyad is not None + await dyad.query_values([RoborockDyadDataProtocol.POWER]) + + dyad_sim.set_online(False) + assert dyad.is_online is False + + await dyad.set_value(RoborockDyadDataProtocol.VOLUME_SET, 45) + assert dyad_sim.status[int(RoborockDyadDataProtocol.VOLUME_SET)] == 80 + dyad_sim.set_protocol_value(RoborockDyadDataProtocol.POWER, 50, push=True) + assert dyad.values == {RoborockDyadDataProtocol.POWER: 100} + assert dyad.is_online is False + + dyad_sim.set_online(True) + assert dyad.is_online is True + assert dyad.values == {RoborockDyadDataProtocol.POWER: 100} + + status = await dyad.query_values([RoborockDyadDataProtocol.POWER]) + assert status == {RoborockDyadDataProtocol.POWER: 50} + + await manager.close() From fbd33de3272fce4ce60c39c160a08cee72852d1c Mon Sep 17 00:00:00 2001 From: infy1995 Date: Mon, 30 Nov 2026 10:08:52 +0100 Subject: [PATCH 2/2] feat(v1): track whether the device is online The cloud sends the same online notice on a V1 device's topic when it loses or regains the device, for example when the vacuum is switched off or loses the network. Without it a consumer cannot tell such a vacuum from one that stopped answering. `device.v1_properties.is_online` follows the notice, and any other message or a local connection marks the device online. `add_online_listener()` reports changes. `set_online()` moved to the base simulator, so V1 devices can be simulated offline too. --- docs/DEVICES.md | 2 + roborock/devices/device_manager.py | 1 + roborock/devices/online_tracker.py | 31 +++++++++ roborock/devices/rpc/v1_channel.py | 23 +++++++ roborock/devices/traits/v1/__init__.py | 23 +++++++ roborock/testing/a01_simulator.py | 14 +--- roborock/testing/b01_q10_simulator.py | 2 + roborock/testing/channel.py | 9 ++- roborock/testing/simulator.py | 27 +++++++- roborock/testing/v1_simulator.py | 2 + tests/devices/rpc/test_v1_channel.py | 91 ++++++++++++++++++++++++++ tests/devices/test_online_tracker.py | 57 ++++++++++++++++ tests/devices/test_v1_device.py | 33 +++++++++- tests/devices/traits/v1/fixtures.py | 3 + tests/testing/test_q10_simulator.py | 18 +++++ tests/testing/test_v1_simulator.py | 71 +++++++++++++++++++- 16 files changed, 387 insertions(+), 20 deletions(-) create mode 100644 roborock/devices/online_tracker.py create mode 100644 tests/devices/test_online_tracker.py diff --git a/docs/DEVICES.md b/docs/DEVICES.md index 363ff74dc..262a7db02 100644 --- a/docs/DEVICES.md +++ b/docs/DEVICES.md @@ -14,6 +14,8 @@ Cloud and Network. * The `status` trait also updates from values the robot pushes on its own (fan power, water, state, battery). Register `device.v1_properties.status.add_update_listener(cb)` to be notified. After a pushed fan power or water change the library reads the full status back once, because water on water-slider models is pushed as a legacy level code and the mop route is never pushed. * A change of only the mop route made in the Roborock app is not pushed, so it shows up with the next `await device.v1_properties.status.refresh()`. * Use `device.v1_properties.command.send()` for raw commands (start/stop). + * `device.v1_properties.is_online` tells whether the robot is online. It is `None` until something arrives. The Roborock cloud's online notice sets it to what the notice says; any other message, or a local connection, means online. It is the last thing heard: a lost local connection or cloud session does not change it. Register `device.v1_properties.add_online_listener(cb)` to be notified when it changes. + * The cloud, not the robot, sends that notice when it loses or regains the robot (seen on a Saros 10R switched off and on, and cut off from the network), so it does not say why. In a test with only the internet blocked, a local message set `is_online` back to `True`. * **Washers (A01)**: Use `device.dyad` or `device.zeo` for Dyad/Zeo devices. * Read `api.values` for the latest known state, merged from query responses and unsolicited pushes. * Use `api.add_update_listener(callback)` to be notified when `values` or `api.is_online` changes. diff --git a/roborock/devices/device_manager.py b/roborock/devices/device_manager.py index 663df9208..52af64685 100644 --- a/roborock/devices/device_manager.py +++ b/roborock/devices/device_manager.py @@ -248,6 +248,7 @@ def device_creator(home_data: HomeData, device: HomeDataDevice, product: HomeDat channel.map_rpc_channel, channel.blob_rpc_channel, channel.add_dps_listener, + channel.online_tracker, web_api, device_cache=device_cache, map_parser_config=map_parser_config, diff --git a/roborock/devices/online_tracker.py b/roborock/devices/online_tracker.py new file mode 100644 index 000000000..3bf1a1360 --- /dev/null +++ b/roborock/devices/online_tracker.py @@ -0,0 +1,31 @@ +"""Tracks whether a device is online.""" + +import logging +from collections.abc import Callable + +from roborock.callbacks import CallbackList + + +class OnlineTracker: + """Holds the online state of a device and notifies listeners when it changes.""" + + def __init__(self, logger: logging.Logger | logging.LoggerAdapter) -> None: + """Initialize the tracker with an unknown state.""" + self._is_online: bool | None = None + self._callbacks: CallbackList[None] = CallbackList(logger) + + @property + def is_online(self) -> bool | None: + """Whether the device is online, or None until something arrives.""" + return self._is_online + + def set_online(self, online: bool) -> None: + """Record the online state, notifying listeners if it changed.""" + if online == self._is_online: + return + self._is_online = online + self._callbacks(None) + + def add_online_listener(self, callback: Callable[[], None]) -> Callable[[], None]: + """Register a callback for changes of `is_online`, returning a callable that removes it.""" + return self._callbacks.add_callback(lambda _: callback()) diff --git a/roborock/devices/rpc/v1_channel.py b/roborock/devices/rpc/v1_channel.py index 54355ca53..2256b22c4 100644 --- a/roborock/devices/rpc/v1_channel.py +++ b/roborock/devices/rpc/v1_channel.py @@ -14,12 +14,14 @@ from roborock.callbacks import CallbackList from roborock.data import HomeDataDevice, NetworkInfo, RoborockBase, UserData from roborock.devices.cache import DeviceCache +from roborock.devices.online_tracker import OnlineTracker from roborock.devices.transport.channel import Channel from roborock.devices.transport.local_channel import LocalChannel, LocalSession, create_local_session from roborock.devices.transport.mqtt_channel import MqttChannel from roborock.exceptions import RoborockException from roborock.mqtt.health_manager import HealthManager from roborock.mqtt.session import MqttParams, MqttSession +from roborock.protocols.online_notice import decode_online_notice from roborock.protocols.v1_protocol import ( CommandType, MapResponse, @@ -242,6 +244,7 @@ def __init__( self._reconnect_task: asyncio.Task[None] | None = None self._last_network_info_refresh: datetime.datetime | None = None self._dps_listeners = CallbackList[dict[RoborockDataProtocol, Any]](self._logger) + self._online_tracker = OnlineTracker(self._logger) @property def is_connected(self) -> bool: @@ -264,6 +267,11 @@ def is_mqtt_connected(self) -> bool: """ return self._mqtt_channel.is_connected and self._mqtt_unsub is not None + @property + def online_tracker(self) -> OnlineTracker: + """Return the online state of the device, which is kept across subscriptions.""" + return self._online_tracker + @property def rpc_channel(self) -> V1RpcChannel: """Return the combined RPC channel that prefers local with a fallback to MQTT. @@ -482,6 +490,7 @@ async def _local_connect(self, *, prefer_cache: bool = True) -> None: # Wire up the new channel self._local_channel = local_channel self._local_unsub = await self._local_channel.subscribe(self._on_local_message) + self._online_tracker.set_online(True) self._logger.info("Connected to local channel successfully") async def _background_reconnect(self) -> None: @@ -537,6 +546,7 @@ def _should_use_cache(self, local_connect_failures: int) -> bool: def _on_mqtt_message(self, message: RoborockMessage) -> None: """Handle incoming MQTT messages.""" self._logger.debug("V1Channel received MQTT message (seq=%s, protocol=%s)", message.seq, message.protocol) + self._update_online(message) if self._callback: self._callback(message) try: @@ -551,9 +561,22 @@ def _on_mqtt_message(self, message: RoborockMessage) -> None: def _on_local_message(self, message: RoborockMessage) -> None: """Handle incoming local messages.""" self._logger.debug("V1Channel received local message (seq=%s, protocol=%s)", message.seq, message.protocol) + self._update_online(message) if self._callback: self._callback(message) + def _update_online(self, message: RoborockMessage) -> None: + """Update the online state: the cloud's online notice carries it, any other message means online.""" + if message.protocol != RoborockMessageProtocol.DEVICE_ONLINE: + self._online_tracker.set_online(True) + return + try: + online = decode_online_notice(message) + except RoborockException as e: + self._logger.debug("Ignoring malformed online notice: %s", e) + return + self._online_tracker.set_online(online) + def create_v1_channel( user_data: UserData, diff --git a/roborock/devices/traits/v1/__init__.py b/roborock/devices/traits/v1/__init__.py index d53db961c..7e609ecc0 100644 --- a/roborock/devices/traits/v1/__init__.py +++ b/roborock/devices/traits/v1/__init__.py @@ -23,6 +23,9 @@ from the device. The state is not updated automatically in real-time unless specifically implemented by the trait or via polling. +`is_online` tells whether the device is online, and `add_online_listener()` +registers a callback invoked when that changes. + Adding New Traits ----------------- When adding a new trait, the most common pattern is to subclass `V1TraitMixin` @@ -67,6 +70,7 @@ from roborock.data.v1.v1_code_mappings import RoborockDockTypeCode from roborock.device_features import RoborockDockFeatures from roborock.devices.cache import DeviceCache +from roborock.devices.online_tracker import OnlineTracker from roborock.devices.traits import Trait from roborock.exceptions import RoborockException from roborock.map.map_parser import MapParserConfig @@ -213,6 +217,7 @@ def __init__( map_rpc_channel: V1RpcChannel, blob_rpc_channel: V1RpcChannel, add_dps_listener: Callable[[Callable[[dict[RoborockDataProtocol, Any]], None]], Callable[[], None]], + online_tracker: OnlineTracker, web_api: UserWebApiClient, device_cache: DeviceCache, map_parser_config: MapParserConfig | None = None, @@ -229,6 +234,7 @@ def __init__( self._region = region self._unsub: Callable[[], None] | None = None self._add_dps_listener = add_dps_listener + self._online_tracker = online_tracker self.device_features = DeviceFeaturesTrait(product, self._device_cache) self.status = StatusTrait(self.device_features, region=self._region) @@ -269,6 +275,21 @@ def _get_rpc_channel(self, trait: V1TraitMixin) -> V1RpcChannel: else: return self._rpc_channel + @property + def is_online(self) -> bool | None: + """Whether the device is online, or `None` until something arrives. + + `False` comes from the cloud, which does not say why. Losing a connection of our own does not change it. + """ + return self._online_tracker.is_online + + def add_online_listener(self, callback: Callable[[], None]) -> Callable[[], None]: + """Register a callback fired only when `is_online` changes. + + Trait updates do not fire it. Returns a callable that removes it. + """ + return self._online_tracker.add_online_listener(callback) + async def start(self) -> None: """Start the properties API and discover features.""" if self._unsub: @@ -443,6 +464,7 @@ def create( map_rpc_channel: V1RpcChannel, blob_rpc_channel: V1RpcChannel, add_dps_listener: Callable[[Callable[[dict[RoborockDataProtocol, Any]], None]], Callable[[], None]], + online_tracker: OnlineTracker, web_api: UserWebApiClient, device_cache: DeviceCache, map_parser_config: MapParserConfig | None = None, @@ -458,6 +480,7 @@ def create( map_rpc_channel, blob_rpc_channel, add_dps_listener, + online_tracker, web_api, device_cache, map_parser_config, diff --git a/roborock/testing/a01_simulator.py b/roborock/testing/a01_simulator.py index 847f2b0cb..54e04937f 100644 --- a/roborock/testing/a01_simulator.py +++ b/roborock/testing/a01_simulator.py @@ -132,18 +132,6 @@ def __init__( super().__init__(duid, device_info, product, has_local_channel=False) raw_status = status or {} self.status: dict[int, Any] = {int(_extract_int_value(k)): _extract_int_value(v) for k, v in raw_status.items()} - self._is_online = True - - def set_online(self, online: bool) -> None: - """Publish the cloud's online notice. While offline, commands are ignored and no data points are pushed.""" - self._is_online = online - self.mqtt_channel.notify_subscribers( - RoborockMessage( - protocol=RoborockMessageProtocol.DEVICE_ONLINE, - version=b"1.0", - payload=json.dumps({"online": online}).encode(), - ) - ) def set_protocol_value(self, protocol: enum.Enum | int, value: Any, push: bool = False) -> None: """Set a protocol value in the simulator status. @@ -160,7 +148,7 @@ def set_protocol_value(self, protocol: enum.Enum | int, value: Any, push: bool = async def _handle_publish(self, message: RoborockMessage, channel: Any) -> None: """Process incoming A01 encrypted payload and respond.""" - if not self._is_online or not message.payload: + if not message.payload: return try: diff --git a/roborock/testing/b01_q10_simulator.py b/roborock/testing/b01_q10_simulator.py index 859619dc4..6268cd3c2 100644 --- a/roborock/testing/b01_q10_simulator.py +++ b/roborock/testing/b01_q10_simulator.py @@ -195,6 +195,8 @@ async def _handle_publish(self, message: RoborockMessage, channel: Any) -> None: def push_dps(self, dps_updates: dict[int, Any]) -> None: """Push a set of status datapoint changes to the client.""" + if not self._is_online: + return payload = { "dps": { str(k): ({str(sub_k): sub_v for sub_k, sub_v in v.items()} if isinstance(v, dict) and k == 101 else v) diff --git a/roborock/testing/channel.py b/roborock/testing/channel.py index 65a36bc79..ee4ea5c63 100644 --- a/roborock/testing/channel.py +++ b/roborock/testing/channel.py @@ -11,6 +11,7 @@ from unittest.mock import AsyncMock, MagicMock from roborock.devices.transport.channel import Channel +from roborock.exceptions import RoborockConnectionException from roborock.mqtt.health_manager import HealthManager from roborock.mqtt.session import MqttQos from roborock.protocols.v1_protocol import LocalProtocolVersion @@ -53,6 +54,8 @@ def __init__(self, is_local: bool = False): self.response_queue: list[RoborockMessage] = [] self._is_connected = False self._is_local = is_local + # False refuses connects and reports the channel as not connected. + self.reachable = True # A callback to intercept published messages (e.g., bound simulator handler). # Must be asynchronous: Callable[[RoborockMessage], Awaitable[Any]]. @@ -89,6 +92,8 @@ def __init__(self, is_local: bool = False): self.health_manager = HealthManager(self.restart) async def _connect(self) -> None: + if not self.reachable: + raise RoborockConnectionException("Device is unreachable") self._is_connected = True def _close(self) -> None: @@ -97,12 +102,12 @@ def _close(self) -> None: @property def is_connected(self) -> bool: """Return true if connected.""" - return self._is_connected + return self._is_connected and self.reachable @property def is_local_connected(self) -> bool: """Return true if locally connected.""" - return self._is_connected and self._is_local + return self.is_connected and self._is_local async def _publish(self, message: RoborockMessage, qos: MqttQos = MqttQos.AT_MOST_ONCE) -> None: """Default publish implementation. diff --git a/roborock/testing/simulator.py b/roborock/testing/simulator.py index 6dd05240d..bb18e0830 100644 --- a/roborock/testing/simulator.py +++ b/roborock/testing/simulator.py @@ -5,10 +5,11 @@ variables, and write responses back to client subscribers. """ +import json import logging from roborock.data import HomeDataDevice, HomeDataProduct, RoborockCategory -from roborock.roborock_message import RoborockMessage +from roborock.roborock_message import RoborockMessage, RoborockMessageProtocol from roborock.testing.channel import FakeChannel _LOGGER = logging.getLogger(__name__) @@ -71,6 +72,8 @@ def __init__( pv="1.0", ) + self._is_online = True + # MQTT channel is always present — all protocols use it. self.mqtt_channel = FakeChannel(is_local=False) self.mqtt_channel.publish_handler = self._handle_mqtt_publish @@ -84,10 +87,12 @@ def __init__( async def _handle_local_publish(self, message: RoborockMessage) -> None: assert self.local_channel is not None - await self._handle_publish(message, self.local_channel) + if self._is_online: + await self._handle_publish(message, self.local_channel) async def _handle_mqtt_publish(self, message: RoborockMessage) -> None: - await self._handle_publish(message, self.mqtt_channel) + if self._is_online: + await self._handle_publish(message, self.mqtt_channel) async def _handle_publish(self, message: RoborockMessage, channel: FakeChannel) -> None: """To be overridden by subclasses to route commands.""" @@ -102,3 +107,19 @@ def close(self) -> None: if self.local_channel is not None: self.local_channel._is_connected = False self.mqtt_channel._is_connected = False + + def set_online(self, online: bool) -> None: + """Publish the cloud's online notice. After it, while offline, commands are ignored and nothing is pushed. + + An offline device also drops its local connection and refuses new ones. + """ + self._is_online = online + if self.local_channel is not None: + self.local_channel.reachable = online + self.mqtt_channel.notify_subscribers( + RoborockMessage( + protocol=RoborockMessageProtocol.DEVICE_ONLINE, + version=b"1.0", + payload=json.dumps({"online": online}).encode(), + ) + ) diff --git a/roborock/testing/v1_simulator.py b/roborock/testing/v1_simulator.py index 0fea10f21..ff9d8cef6 100644 --- a/roborock/testing/v1_simulator.py +++ b/roborock/testing/v1_simulator.py @@ -534,6 +534,8 @@ async def _handle_publish(self, message: RoborockMessage, channel: FakeChannel) def trigger_push_update(self) -> None: """Trigger an unsolicited push state update to all subscribers.""" + if not self._is_online: + return dps_payload = { str(int(RoborockDataProtocol.STATE)): self.status.state.value if self.status.state else 0, str(int(RoborockDataProtocol.BATTERY)): self.status.battery, diff --git a/tests/devices/rpc/test_v1_channel.py b/tests/devices/rpc/test_v1_channel.py index d676414a4..918f3525c 100644 --- a/tests/devices/rpc/test_v1_channel.py +++ b/tests/devices/rpc/test_v1_channel.py @@ -67,6 +67,11 @@ LOCAL_DECODER = create_local_decoder(TEST_LOCAL_KEY) +def build_online_notice(payload: bytes) -> RoborockMessage: + """Build the cloud's plain JSON online notice for a device.""" + return RoborockMessage(protocol=RoborockMessageProtocol.DEVICE_ONLINE, payload=payload) + + @pytest.fixture(name="mock_mqtt_channel") async def setup_mock_mqtt_channel() -> FakeChannel: """Mock MQTT channel for testing.""" @@ -842,6 +847,92 @@ async def test_v1_channel_subscribe_failure_is_atomic( unsub() +async def test_v1_channel_online_state_from_mqtt( + v1_channel: V1Channel, + mock_mqtt_channel: FakeChannel, + mock_local_channel: FakeChannel, +) -> None: + """Online notices set the state and any other MQTT message means online.""" + mock_mqtt_channel.response_queue.append(TEST_NETWORK_INFO_RESPONSE) + mock_local_channel.connect.side_effect = RoborockException("Connection failed") + seen: list[tuple[RoborockMessage, bool | None]] = [] + await v1_channel.subscribe(lambda message: seen.append((message, v1_channel.online_tracker.is_online))) + dps_listener = Mock() + v1_channel.add_dps_listener(dps_listener) + assert v1_channel.online_tracker.is_online is None + + offline = build_online_notice(b'{"online":false}') + mock_mqtt_channel.notify_subscribers(offline) + assert v1_channel.online_tracker.is_online is False + # The state is already updated when the device callback runs + assert seen == [(offline, False)] + dps_listener.assert_not_called() + + mock_mqtt_channel.notify_subscribers(build_online_notice(b"{}")) + assert v1_channel.online_tracker.is_online is False + + mock_mqtt_channel.notify_subscribers(TEST_RESPONSE) + assert v1_channel.online_tracker.is_online is True + assert seen[-1] == (TEST_RESPONSE, True) + + +async def test_v1_channel_online_state_updated_before_dps_listeners( + v1_channel: V1Channel, + mock_mqtt_channel: FakeChannel, +) -> None: + """DPS listeners already see the device as online.""" + mock_mqtt_channel.response_queue.append(TEST_NETWORK_INFO_RESPONSE) + await v1_channel.subscribe(Mock()) + mock_mqtt_channel.notify_subscribers(build_online_notice(b'{"online":false}')) + seen: list[bool | None] = [] + v1_channel.add_dps_listener(lambda _: seen.append(v1_channel.online_tracker.is_online)) + + mock_mqtt_channel.notify_subscribers( + RoborockMessage( + protocol=RoborockMessageProtocol.GENERAL_REQUEST, + payload=json.dumps({"dps": {"121": 5}}).encode(), + ) + ) + + assert seen == [True] + + +async def test_v1_channel_online_state_from_local( + v1_channel: V1Channel, + mock_mqtt_channel: FakeChannel, + mock_local_channel: FakeChannel, +) -> None: + """A local connection and local messages mean online.""" + mock_mqtt_channel.response_queue.append(TEST_NETWORK_INFO_RESPONSE) + await v1_channel.subscribe(Mock()) + assert v1_channel.online_tracker.is_online is True + + mock_mqtt_channel.notify_subscribers(build_online_notice(b'{"online":false}')) + assert v1_channel.online_tracker.is_online is False + + mock_local_channel.notify_subscribers(TEST_RESPONSE) + assert v1_channel.online_tracker.is_online is True + + +async def test_v1_channel_online_state_kept_after_unsubscribe( + v1_channel: V1Channel, + mock_mqtt_channel: FakeChannel, + mock_local_channel: FakeChannel, +) -> None: + """Unsubscribing and resubscribing over MQTT only does not change the state.""" + mock_mqtt_channel.response_queue.append(TEST_NETWORK_INFO_RESPONSE) + mock_local_channel.connect.side_effect = RoborockException("Connection failed") + unsub = await v1_channel.subscribe(Mock()) + mock_mqtt_channel.notify_subscribers(build_online_notice(b'{"online":false}')) + + unsub() + assert v1_channel.online_tracker.is_online is False + + unsub = await v1_channel.subscribe(Mock()) + assert v1_channel.online_tracker.is_online is False + unsub() + + @pytest.mark.parametrize( ("method", "params", "result", "secret"), [ diff --git a/tests/devices/test_online_tracker.py b/tests/devices/test_online_tracker.py new file mode 100644 index 000000000..d9e319ee8 --- /dev/null +++ b/tests/devices/test_online_tracker.py @@ -0,0 +1,57 @@ +"""Tests for the OnlineTracker class.""" + +import logging +from unittest.mock import Mock + +import pytest + +from roborock.devices.online_tracker import OnlineTracker + + +@pytest.fixture(name="tracker") +def tracker_fixture() -> OnlineTracker: + """Fixture to set up the tracker for tests.""" + return OnlineTracker(logging.getLogger(__name__)) + + +def test_starts_unknown(tracker: OnlineTracker) -> None: + """The state is unknown until it is set.""" + assert tracker.is_online is None + + +def test_listener_called_only_on_change(tracker: OnlineTracker) -> None: + """Listeners hear each change once and read the new state.""" + seen: list[bool | None] = [] + tracker.add_online_listener(lambda: seen.append(tracker.is_online)) + + tracker.set_online(False) + tracker.set_online(False) + tracker.set_online(True) + + assert seen == [False, True] + assert tracker.is_online is True + + +def test_remove_listener(tracker: OnlineTracker) -> None: + """A removed listener is not called again.""" + listener = Mock() + remove = tracker.add_online_listener(listener) + tracker.set_online(False) + + remove() + tracker.set_online(True) + + listener.assert_called_once_with() + + +def test_raising_listener_does_not_stop_others(tracker: OnlineTracker) -> None: + """A failing listener does not keep the next one from running.""" + failing = Mock(side_effect=Exception("listener failed")) + listener = Mock() + tracker.add_online_listener(failing) + tracker.add_online_listener(listener) + + tracker.set_online(True) + + failing.assert_called_once_with() + listener.assert_called_once_with() diff --git a/tests/devices/test_v1_device.py b/tests/devices/test_v1_device.py index 0b9b999a6..4bed1524f 100644 --- a/tests/devices/test_v1_device.py +++ b/tests/devices/test_v1_device.py @@ -1,5 +1,6 @@ """Tests for the Device class.""" +import logging import pathlib from collections.abc import Callable from typing import Any @@ -11,6 +12,7 @@ from roborock.data import HomeData, NetworkInfo, StatusV2, UserData from roborock.devices.cache import DeviceCache, DeviceCacheData, InMemoryCache, NoCache from roborock.devices.device import RoborockDevice +from roborock.devices.online_tracker import OnlineTracker from roborock.devices.rpc.v1_channel import V1Channel from roborock.devices.traits import v1 from roborock.devices.traits.v1.common import V1TraitMixin @@ -58,9 +60,19 @@ def blob_rpc_channel_fixture() -> AsyncMock: return AsyncMock() +@pytest.fixture(name="online_tracker") +def online_tracker_fixture() -> OnlineTracker: + """Fixture to set up the online state for tests.""" + return OnlineTracker(logging.getLogger(__name__)) + + @pytest.fixture(autouse=True, name="device") def device_fixture( - channel: AsyncMock, rpc_channel: AsyncMock, mqtt_rpc_channel: AsyncMock, blob_rpc_channel: AsyncMock + channel: AsyncMock, + rpc_channel: AsyncMock, + mqtt_rpc_channel: AsyncMock, + blob_rpc_channel: AsyncMock, + online_tracker: OnlineTracker, ) -> RoborockDevice: """Fixture to set up the device for tests.""" return RoborockDevice( @@ -76,6 +88,7 @@ def device_fixture( AsyncMock(), blob_rpc_channel, Mock(), + online_tracker, AsyncMock(), device_cache=DeviceCache(HOME_DATA.devices[0].duid, NoCache()), region=USER_DATA.region, @@ -126,6 +139,23 @@ async def test_connection_status( assert device.is_local_connected is local_connected +def test_online_state(device: RoborockDevice, online_tracker: OnlineTracker) -> None: + """The V1 properties expose the online state of the device.""" + assert device.v1_properties + properties = device.v1_properties + seen: list[bool | None] = [] + remove = properties.add_online_listener(lambda: seen.append(properties.is_online)) + assert properties.is_online is None + + online_tracker.set_online(False) + online_tracker.set_online(True) + remove() + online_tracker.set_online(False) + + assert seen == [False, True] + assert properties.is_online is False + + @pytest.fixture(name="payloads") def payloads_fixture() -> list[pathlib.Path]: """Fixture to provide the payload for the tests.""" @@ -270,6 +300,7 @@ async def test_connect_retries_after_transient_start_failure() -> None: AsyncMock(), AsyncMock(), Mock(), + v1_channel.online_tracker, AsyncMock(), device_cache=device_cache, region=USER_DATA.region, diff --git a/tests/devices/traits/v1/fixtures.py b/tests/devices/traits/v1/fixtures.py index b760d2589..9a698e5ca 100644 --- a/tests/devices/traits/v1/fixtures.py +++ b/tests/devices/traits/v1/fixtures.py @@ -1,5 +1,6 @@ """Fixtures for V1 trait tests.""" +import logging from copy import deepcopy from unittest.mock import AsyncMock, Mock @@ -8,6 +9,7 @@ from roborock.data import HomeData, HomeDataDevice, HomeDataProduct, RoborockDockTypeCode, StatusV2, UserData from roborock.devices.cache import Cache, DeviceCache, InMemoryCache from roborock.devices.device import RoborockDevice +from roborock.devices.online_tracker import OnlineTracker from roborock.devices.traits import v1 from tests import mock_data @@ -110,6 +112,7 @@ def device_fixture( mock_map_rpc_channel, mock_blob_rpc_channel, Mock(), + OnlineTracker(logging.getLogger(__name__)), web_api_client, device_cache=device_cache, region=USER_DATA.region, diff --git a/tests/testing/test_q10_simulator.py b/tests/testing/test_q10_simulator.py index ed6e84168..90201a582 100644 --- a/tests/testing/test_q10_simulator.py +++ b/tests/testing/test_q10_simulator.py @@ -124,6 +124,24 @@ def mock_notify(message: RoborockMessage) -> None: assert json.loads(last_msg.payload.decode())["dps"] == {"121": 3, "138": 0} +async def test_offline_sends_no_data(q10_sim: Q10VacuumSimulator) -> None: + """An offline simulator pushes no data points until it is back online.""" + notified_messages: list[RoborockMessage] = [] + q10_sim.set_online(False) + await q10_sim.mqtt_channel.subscribe(notified_messages.append) + + q10_sim.push_dps({122: 50}) + q10_sim.trigger_push_update() + assert notified_messages == [] + + q10_sim.set_online(True) + q10_sim.trigger_push_update() + assert [message.protocol for message in notified_messages] == [ + RoborockMessageProtocol.DEVICE_ONLINE, + RoborockMessageProtocol.RPC_RESPONSE, + ] + + async def test_setters(q10_sim: Q10VacuumSimulator) -> None: """Test setting fan speed, water level, and sound volume.""" notified_messages = [] diff --git a/tests/testing/test_v1_simulator.py b/tests/testing/test_v1_simulator.py index 2d8853a8b..bb0b37273 100644 --- a/tests/testing/test_v1_simulator.py +++ b/tests/testing/test_v1_simulator.py @@ -11,8 +11,9 @@ from roborock.devices.cache import InMemoryCache from roborock.devices.device_manager import UserParams, create_device_manager from roborock.devices.traits.v1.consumeable import ConsumableAttribute -from roborock.exceptions import RoborockException +from roborock.exceptions import RoborockConnectionException, RoborockException from roborock.map.map_parser import MapParser, MapParserConfig +from roborock.protocols.v1_protocol import RequestMessage from roborock.roborock_message import RoborockMessage, RoborockMessageProtocol from roborock.testing import ( DEFAULT_APP_INIT, @@ -167,6 +168,74 @@ async def test_trait_push_update_propagation(): assert device.v1_properties.status.state == RoborockStateCode.returning_home +async def test_set_online() -> None: + """Going offline produces the cloud's notice, then the simulator stays silent until it is back online.""" + fake_device = V1VacuumSimulator(duid="s7_online", status=replace(DEFAULT_STATUS, battery=99)) + device = await _create_connected_device(FakeRoborockCloud(), fake_device) + properties = device.v1_properties + await properties.status.refresh() + assert properties.is_online is True + seen: list[bool | None] = [] + properties.add_online_listener(lambda: seen.append(properties.is_online)) + + fake_device.set_online(False) + assert properties.is_online is False + assert seen == [False] + + fake_device.status.battery = 45 + fake_device.trigger_push_update() + assert properties.status.battery == 99 + assert properties.is_online is False + + replies: list[RoborockMessage] = [] + unsub = await fake_device.mqtt_channel.subscribe(replies.append) + request = RequestMessage(method="get_status", params=[]).encode_message( + RoborockMessageProtocol.RPC_REQUEST, fake_device.security_data + ) + await fake_device.mqtt_channel.publish(request) + unsub() + assert fake_device.local_channel is not None + unsub = await fake_device.local_channel.subscribe(replies.append) + await fake_device.local_channel.publish(request) + unsub() + assert replies == [] + + fake_device.set_online(True) + assert properties.is_online is True + assert seen == [False, True] + + unsub = await fake_device.local_channel.subscribe(replies.append) + await fake_device.local_channel.publish(request) + unsub() + assert [reply.protocol for reply in replies] == [RoborockMessageProtocol.RPC_RESPONSE] + + +async def test_offline_refuses_local_connections() -> None: + """An offline simulator has no local connection and accepts none until it is back online.""" + fake_device = V1VacuumSimulator(duid="s7_offline_local") + device = await _create_connected_device(FakeRoborockCloud(), fake_device) + local_channel = fake_device.local_channel + assert local_channel is not None + assert device.is_local_connected + + fake_device.set_online(False) + assert not device.is_local_connected + with pytest.raises(RoborockConnectionException): + await local_channel.connect() + # Clearing injected errors must not make the offline device reachable. + local_channel.inject_error(RoborockException("injected")) + local_channel.clear_error() + with pytest.raises(RoborockConnectionException): + await local_channel.connect() + assert not device.is_local_connected + assert device.v1_properties.is_online is False + + fake_device.set_online(True) + assert device.is_local_connected + await local_channel.connect() + assert local_channel.is_connected + + async def test_trait_custom_handler_override(): """Verify that custom_handlers override default behavior for specific commands."""