Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
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
29 changes: 29 additions & 0 deletions docs/last_known_state.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Last-known robot state

A robot that loses Wi-Fi, gets stuck or is switched off stops answering, and from then on nothing says where
it was or what it last reported. The server keeps that for every robot it manages, so a client can show the last
known picture instead of an empty screen.

## What is kept

Per robot, in `device_snapshots/` under the data directory (it survives a restart):

- When the robot last spoke or logged in, and when its connection last closed.
- The last status it sent: state, battery and error code.
- Its last position on the map and the map it was drawn on.
- Its room table (which map segment is which room), with the room names from the home data.

It is fed from the MQTT proxy: status pushes (`dps` 120, 121 and 122), the answers to `get_status` and
`get_room_mapping`, and the `get_map_v1` reply, which is decrypted with the nonce of the request that asked for
it. Mower pushes are skipped, since their `dps` 121 and 122 are not state and battery, and B01 robots (Q7, Q10) are not read for state: they only get the last-seen and offline times, because their `dps` keys mean something else. On startup the store is seeded from the existing MQTT log, so a freshly updated server does not begin empty. The seed counts only publishes on a topic whose username belongs to the robot with that device id. The log does not record which login sent a frame, so this is a weaker check than the live one.

## Reading it

```text
GET /user/devices/{duid}/last_known
GET /user/devices/{duid}/last_known?map=1
```

The answer is the usual `{"code": 200, "data": {...}}` envelope. `data.known` is `false` for a robot the server has
never heard from, which is how a client tells "never paired" from "paired and currently offline". With `?map=1` the
last map is included as base64 of the same bytes `get_map_v1` returns once decrypted and decompressed.
1 change: 1 addition & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ nav:
- Camera (Live Video): camera.md
- Reference:
- Log Retention: logging.md
- Last-Known State: last_known_state.md
- Known Limitations: known_limitations.md
- Schedule Support (Experimental): schedules.md
- Scene Validity Reports: scene_validity.md
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,8 @@
from .routes.user.devices.jobs import match_create as _match_create_schedule
from .routes.user.devices.jobs import match_delete as _match_delete_schedule
from .routes.user.devices.jobs import match_update as _match_update_schedule
from .routes.user.devices.last_known import build as _build_last_known
from .routes.user.devices.last_known import match as _match_last_known
from .routes.user.devices.newadd import build as _build_add_device
from .routes.user.devices.newadd import match as _match_add_device
from .routes.user.homes.item import build as _build_get_home_data
Expand Down Expand Up @@ -618,6 +620,7 @@ def default_endpoint_rules() -> Sequence[EndpointRule]:
EndpointRule("create_schedule", _match_create_schedule, _build_create_schedule),
EndpointRule("update_schedule", _match_update_schedule, _build_update_schedule),
EndpointRule("delete_schedule", _match_delete_schedule, _build_delete_schedule),
EndpointRule("get_device_last_known", _match_last_known, _build_last_known),
EndpointRule("post_app_info", _match_post_app_info, _build_post_app_info),
EndpointRule("get_inbox_latest", _match_get_inbox_latest, _build_get_inbox_latest),
EndpointRule("get_products_v4", _match_get_products_v4, _build_get_products_v4),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
from __future__ import annotations

import re
from typing import Any

from shared.context import ServerContext
from shared.http_helpers import wrap_response

from ..homes.service import home_rooms_payload


def match(path: str) -> bool:
clean = path.rstrip("/")
return bool(re.fullmatch(r"/user/devices/[^/]+/last_known", clean))


def build(
ctx: ServerContext,
query_params: dict[str, list[str]],
_body_params: dict[str, list[str]],
clean_path: str,
) -> dict[str, Any]:
"""The robot's last-known state: status, position, and when it last spoke or went offline.

``?map=1`` adds the last map the robot sent (base64 of the same bytes ``get_map_v1`` returns
once decrypted and decompressed), so a client can draw it while the robot cannot be asked.
"""
parts = [part for part in clean_path.rstrip("/").split("/") if part]
duid = parts[-2] if len(parts) >= 2 else ""
store = ctx.snapshot_store
snapshot = None
if store is not None:
include_map = (query_params.get("map") or [""])[0] in ("1", "true")
snapshot = store.get(duid, include_map=include_map)
if snapshot is None:
return wrap_response({"duid": duid, "known": False})
# The robot's room table says which segment is which room; the home data knows the names.
names = {str(room.get("id")): room.get("name") for room in home_rooms_payload(ctx) if isinstance(room, dict)}
for room in snapshot.get("rooms") or []:
room["name"] = names.get(str(room.get("iot_id")))
return wrap_response({**snapshot, "known": True})
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from shared.protocol_auth import ProtocolAuthStore
from shared.runtime_credentials import RuntimeCredentialsStore, parse_mqtt_connect_packet
from shared.runtime_state import RuntimeState
from shared.device_snapshot_store import DeviceSnapshotStore, is_mower_model, is_status_answer
from shared.zone_ranges_store import ZoneRangesStore

from .command_handlers import RpcCommandRegistry
Expand Down Expand Up @@ -57,6 +58,7 @@ def __init__(
runtime_state: RuntimeState | None = None,
runtime_credentials: RuntimeCredentialsStore | None = None,
zone_ranges_store: ZoneRangesStore | None = None,
snapshot_store: DeviceSnapshotStore | None = None,
tls_enabled: bool = True,
on_onboarding_credentials_learned: Callable[[], None] | None = None,
on_device_firmware_reported: Callable[[str, str], None] | None = None,
Expand All @@ -77,6 +79,9 @@ def __init__(
self.runtime_state = runtime_state
self.runtime_credentials = runtime_credentials
self.zone_ranges_store = zone_ranges_store
self.snapshot_store = snapshot_store
self._conn_duids: dict[str, set[str]] = {}
self._duid_conn: dict[str, str] = {}
self._on_onboarding_credentials_learned = on_onboarding_credentials_learned
self._on_device_firmware_reported = on_device_firmware_reported
self._server_socket: socket.socket | None = None
Expand Down Expand Up @@ -155,6 +160,20 @@ def _bind_authenticated_device_topic(self, conn_id: str, auth_reason: str, usern
did = str((device or {}).get("did") or "").strip()
if did:
self._set_conn_device_topic(conn_id, f"rr/d/i/{did}/{normalized_username}")
# Logging in with its own credentials means the robot is back, even before it publishes.
duid = str((device or {}).get("duid") or "").strip()
if duid and self.snapshot_store is not None:
try:
self._note_robot_online(conn_id, duid)
except Exception:
self.logger.exception("[conn %s] marking the robot online failed", conn_id)

def _note_robot_online(self, conn_id: str, duid: str) -> None:
with self._lock:
self._conn_duids.setdefault(conn_id, set()).add(duid)
self._duid_conn[duid] = conn_id
if self.snapshot_store is not None:
self.snapshot_store.mark_seen(duid)

@staticmethod
def _decode_remaining_length(data: bytes, start: int) -> tuple[int | None, int]:
Expand Down Expand Up @@ -594,6 +613,63 @@ def _report_device_firmware(self, conn_id: str, topic: str, payload_utf8: str |
except Exception:
self.logger.exception("recording firmware %s reported by %s failed", firmware_version, device_id)

def _duid_for_topic(self, topic: str) -> str:
parts = topic.split("/")
if topic.startswith("rr/m/") and len(parts) >= 6:
return parts[5]
if topic.startswith("rr/d/") and len(parts) >= 5 and self.runtime_credentials is not None:
device = self.runtime_credentials.resolve_device(did=parts[3])
return str(device.get("duid") or "") if device else ""
return ""

def _is_mower(self, duid: str) -> bool:
# Mower dps 121/122 are not state/battery, so their pushes must not fill the vacuum fields.
device = self.runtime_credentials.resolve_device(duid=duid) if self.runtime_credentials is not None else None
return is_mower_model((device or {}).get("model"))

def _observe_snapshot(
self,
conn_id: str,
direction: str,
topic: str,
proto_value: int,
decoded_entry: dict[str, Any],
payload_bytes: bytes,
) -> None:
"""Feed what the robot says into the last-known-state store."""
if self.snapshot_store is None:
return
try:
duid = self._duid_for_topic(topic)
if not duid:
return
payload_utf8 = decoded_entry.get("payload_utf8")
payload_utf8 = payload_utf8 if isinstance(payload_utf8, str) else None
if proto_value == 101:
# Any client's request: the nonce in it is what decrypts the map reply it gets.
self.snapshot_store.note_request(duid, payload_utf8)
return
# App and bootstrap logins can publish on any topic; only the vacuum's own login speaks for it.
if direction != "c2b" or topic != self._get_conn_device_topic(conn_id):
return
self._note_robot_online(conn_id, duid)
# B01 robots (Q7, Q10) use other dps keys; their 121 is not the V1 state.
if decoded_entry.get("version") == "B01":
return
if proto_value == 301:
self.snapshot_store.record_map(duid, payload_bytes)
elif proto_value == 102:
response_to = decoded_entry.get("response_to")
if isinstance(response_to, dict):
if is_status_answer(response_to) and response_to.get("error") is None:
self.snapshot_store.record_status_result(duid, response_to.get("result"))
elif response_to.get("request_method") == "get_room_mapping" and response_to.get("error") is None:
self.snapshot_store.record_room_mapping(duid, response_to.get("result"))
elif not self._is_mower(duid):
self.snapshot_store.record_dps(duid, payload_utf8)
except Exception:
self.logger.exception("[conn %s] snapshot update failed", conn_id)

def _trace_packet(self, conn_id: str, direction: str, packet: bytes) -> None:
packet_type = packet[0] >> 4
if packet_type in (12, 13): # PINGREQ, PINGRESP
Expand Down Expand Up @@ -748,6 +824,7 @@ def _trace_packet(self, conn_id: str, direction: str, packet: bytes) -> None:
response_to.get("request_method"),
response_to.get("error"),
)
self._observe_snapshot(conn_id, direction, topic, proto_value, decoded_entry, payload_bytes)
decoded_messages.append(decoded_entry)
self.logger.info(
"[conn %s %s] PUBLISH topic=%s proto=%s(%d) ver=%s seq=%s key_source=%s payload=%s",
Expand All @@ -772,6 +849,17 @@ def _forget_conn_trace_state(self, conn_id: str) -> None:
self._conn_protocol_levels.pop(conn_id, None)
self._conn_device_topics.pop(conn_id, None)
self._pending_onboarding_auth.pop(conn_id, None)
gone_duids = self._conn_duids.pop(conn_id, set())
# A robot that already reconnected on a newer connection is still online.
gone_duids = {duid for duid in gone_duids if self._duid_conn.get(duid) == conn_id}
for duid in gone_duids:
del self._duid_conn[duid]
if self.snapshot_store is not None:
try:
for duid in gone_duids:
self.snapshot_store.mark_offline(duid)
except Exception:
self.logger.exception("[conn %s] marking robots offline failed", conn_id)

def _run_trace_worker(self) -> None:
while True:
Expand Down Expand Up @@ -1027,4 +1115,7 @@ def stop(self) -> None:
if trace_thread is not None and trace_thread.is_alive():
self._trace_queue.put(None)
trace_thread.join(timeout=2.0)
# Updates traced while the worker drained its queue came after the caller's own flush.
if self.snapshot_store is not None:
self.snapshot_store.flush()
self.logger.info("TLS MQTT proxy stopped")
2 changes: 2 additions & 0 deletions src/roborock_local_server/bundled_backend/shared/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from .http_helpers import pick_first
from .runtime_credentials import RuntimeCredentialsStore
from .runtime_state import RuntimeState
from .device_snapshot_store import DeviceSnapshotStore
from .zone_ranges_store import ZoneRangesStore

_DEVICE_ID_KEYS = ("did", "d", "duid", "device_id", "deviceId", "device_did", "deviceDid")
Expand Down Expand Up @@ -70,6 +71,7 @@ class ServerContext:
runtime_state: RuntimeState | None = None
runtime_credentials: RuntimeCredentialsStore | None = None
zone_ranges_store: ZoneRangesStore | None = None
snapshot_store: DeviceSnapshotStore | None = None
timezone: str | None = None
# TURN/STUN advertised to the robot for camera sessions (see routes/fw/createca.py).
turn_enabled: bool = False
Expand Down
Loading