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
5 changes: 4 additions & 1 deletion docs/DEVICES.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,12 @@ 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` 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.
Expand Down
1 change: 1 addition & 0 deletions roborock/devices/device_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
31 changes: 31 additions & 0 deletions roborock/devices/online_tracker.py
Original file line number Diff line number Diff line change
@@ -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())
23 changes: 23 additions & 0 deletions roborock/devices/rpc/v1_channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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:
Expand All @@ -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.
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand All @@ -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,
Expand Down
42 changes: 33 additions & 9 deletions roborock/devices/traits/a01/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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:
Expand All @@ -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))

Expand All @@ -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()
Expand All @@ -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:
Expand All @@ -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.
Expand All @@ -312,17 +333,20 @@ 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:
continue
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()

Expand Down
23 changes: 23 additions & 0 deletions roborock/devices/traits/v1/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -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)
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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,
Expand All @@ -458,6 +480,7 @@ def create(
map_rpc_channel,
blob_rpc_channel,
add_dps_listener,
online_tracker,
web_api,
device_cache,
map_parser_config,
Expand Down
20 changes: 20 additions & 0 deletions roborock/protocols/online_notice.py
Original file line number Diff line number Diff line change
@@ -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
1 change: 1 addition & 0 deletions roborock/roborock_message.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
2 changes: 2 additions & 0 deletions roborock/testing/a01_simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,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)
Expand Down
2 changes: 2 additions & 0 deletions roborock/testing/b01_q10_simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
9 changes: 7 additions & 2 deletions roborock/testing/channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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]].
Expand Down Expand Up @@ -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:
Expand All @@ -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.
Expand Down
Loading
Loading