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
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 `last_known/` under the data directory (it survives a restart):

- When the robot last spoke, 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. On startup the store is seeded from the existing MQTT log, so a freshly updated server does not begin empty.

## 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
- Scene Validity Reports: scene_validity.md
- Tested Vacuums: tested_vacuums.md
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,8 @@
from .routes.user.deviceshare import match_rooms as _match_get_shared_device_rooms
from .routes.user.devices.jobs import build as _build_get_schedules
from .routes.user.devices.jobs import match as _match_get_schedules
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 @@ -609,6 +611,7 @@ def default_endpoint_rules() -> Sequence[EndpointRule]:
EndpointRule("get_device", _match_get_device, _build_get_device),
EndpointRule("get_device_extra", _match_get_device_extra, _build_get_device_extra),
EndpointRule("get_schedules", _match_get_schedules, _build_get_schedules),
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 @@ -19,6 +19,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_status_answer
from shared.zone_ranges_store import ZoneRangesStore

from .command_handlers import RpcCommandRegistry
Expand Down Expand Up @@ -46,6 +47,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,
) -> None:
Expand All @@ -65,6 +67,8 @@ 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._on_onboarding_credentials_learned = on_onboarding_credentials_learned
self._server_socket: socket.socket | None = None
self._running = False
Expand Down Expand Up @@ -521,6 +525,56 @@ def _parse_v1_rpc_payload(payload_utf8: str | None, protocol_value: int) -> dict
parsed["error"] = rpc_obj.get("error")
return parsed

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 _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
if not (topic.startswith("rr/d/i/") and direction == "c2b"):
return
with self._lock:
self._conn_duids.setdefault(conn_id, set()).add(duid)
self.snapshot_store.mark_seen(duid)
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"))
else:
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 @@ -661,6 +715,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 Down Expand Up @@ -815,6 +870,10 @@ def _handle_client(self, tls_conn: socket.socket | ssl.SSLSocket, addr: tuple[st
self.runtime_state.record_mqtt_disconnect(conn_id=conn_id)
with self._lock:
self._conn_protocol_levels.pop(conn_id, None)
gone_duids = self._conn_duids.pop(conn_id, set())
if self.snapshot_store is not None:
for duid in gone_duids:
self.snapshot_store.mark_offline(duid)
self.logger.info("[conn %s] closed", conn_id)

def start(self) -> threading.Thread:
Expand Down
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
Loading