Skip to content

Keep each robot's last-known state and serve it at /user/devices/{duid}/last_known - #251

Merged
Lash-L merged 16 commits into
Python-roborock:mainfrom
virtitnerd:pr/last-known-state
Nov 22, 2026
Merged

Lash-L merged 16 commits into
Python-roborock:mainfrom
virtitnerd:pr/last-known-state

Conversation

@virtitnerd

@virtitnerd virtitnerd commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Why

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. A client has no way to show anything for it, and no way to tell "never paired" from
"paired but offline right now".

What

The server keeps, per robot and across restarts: when it last spoke and when its connection last closed, the last
status it sent (state, battery, error), its last position and the map it was drawn on, and its room table with the
room names from the home data. It is fed from the MQTT proxy (status pushes, the answers to get_status and
get_room_mapping, and the decrypted get_map_v1 reply) and seeded from the existing MQTT log on startup.

GET /user/devices/{duid}/last_known returns it. data.known is false for a robot the server has never heard
from. ?map=1 adds the last map. Like the other /user/ routes it relies on the global protocol_auth_enabled
check (on by default).

Details of what is recorded and when:

  • Only publishes on a robot's own device topic count as the robot speaking. Requests (protocol 101) are read from any
    client, since the nonce is needed to decrypt the map reply.
  • The map request's security block is parsed as JSON, so base64 endpoints and any key order work.
  • A robot's close marks it offline only when it is the connection that spoke last. The mark is set by the trace worker
    after the packets queued before the close are traced. A robot rebuilt from the MQTT log or loaded from disk is
    reported offline (offline_at is its last-seen time) until it speaks again.
  • Mowers get last-seen and offline times only (their dps 121 and 122 are not state and battery). B01 robots (Q7, Q10)
    are not read at all; I have no capture of their status.
  • The store is flushed on shutdown, and flushes are serialised and written outside the store lock.

Testing

New tests cover the store, the route, the room table, base64 and nonce-first security blocks, the reconnect race,
device-topic binding and the offline marks. Full suite: 540 passed. I also used it daily against a Qrevo Pro and
a Qrevo Curv 2 Flow. No mower or B01 robot was available to test.

Notes

@Lash-L Lash-L left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated review: changes requested

The idea and structure are fine, and all 508 tests pass.

Endpoint:

  • It's server-invented. The APK has no last_known. The nearest real routes are GET user/devices/{duid}/lw and GET devices/{duid}/shadow (IotApi.java:46,84), and the new path collides with neither.
  • Exposure: Hawk auth applies only when protocol_auth_enabled is on. With it off, ?map=1 serves the home's floor plan to anyone who knows the duid, and there's no per-device ownership check.

Confirmed:

  • Status pushes are dps 120/121/122 in protocol 102.
  • get_status returns a 1-item list.
  • The map reply layout (24-byte header, <8s endpoint, CBC with the nonce, then gzip) matches python-roborock's v1_protocol.py.

Blocking:

  1. _SECURITY_RE misses real requests (device_snapshot_store.py:41). It only matches when endpoint comes before nonce and the endpoint is all \w characters.
    • Endpoints are base64 (v1_protocol.py:65), and about 22% of 8-character endpoints contain + or /, so those users never get maps or positions.
    • The app builds security from a Java HashMap, so nonce-first order is possible (not confirmed from a capture).
    • Fix: parse the JSON instead.
  2. Merging with #283/#285 needs real changes (git merge-tree).
    • Those PRs replace the inline close cleanup with _queue_conn_closed, so the _conn_duids pop and mark_offline have to move into the trace worker's close handler.
    • Otherwise packets still in the queue call mark_seen after mark_offline and clear the offline mark.
    • #282 is clean, and #263 conflicts in tests only.
  3. Wrong offline state.
    • mark_offline on the old connection's close (mqtt_tls_proxy_server/server.py:870-876) marks a robot offline even though it has already reconnected on a new connection.
    • Entries rebuilt from the log never get offline_at (device_snapshot_store.py:424), so a long-dead robot looks online.
  4. Any rr/d/i/ publish counts as the robot speaking. App and bootstrap logins can publish on any topic. #283 adds _get_conn_device_topic, so use that binding.

Should fix:
5. B01 (Q7/Q10) status is never captured, and mower dps (121 = battery, 122 = mow type) would be mislabelled. Handle both or document them.
6. The docs say last_known/, but the code writes device_snapshots/ (docs/last_known_state.md:9 vs device_snapshot_store.py:32).
7. Minor:

  • There's no flush on shutdown, so up to 30s of updates are lost.
  • Flushes, including map files, run under the store lock on the MQTT thread.
  1. Tests:
    • The fixtures only use endpoint-first JSON with alphanumeric endpoints, so add base64 and nonce-first cases.
    • Add a test for the reconnect race.

#255 depends on this PR.

I've converted this PR to draft while these are addressed. Mark it ready for review again once they're fixed and it will go through another review.


This is an automated review by Claude Code, checked against the decompiled Roborock app (APK + device plugin bundles), python-roborock and a vacuum firmware dump. It can be incorrect, so please reply if any finding looks wrong.

@Lash-L Lash-L added the failing auto review Automated review requested changes before merge label Nov 21, 2026
@Lash-L
Lash-L marked this pull request as draft November 21, 2026 16:07
@virtitnerd

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review. The branch is rebased onto current main (the conflicts with #283 and #285 are resolved), and the history was rewritten, so the hashes below are from the current head (8abfcf9). #255 contains this PR until it merges.

  1. _SECURITY_RE misses real requests. Fixed in 99a5653. The request is now parsed as JSON (the dps["101"] string is decoded, and a top-level security also works), so base64 endpoints with + and / and nonce-first order both work. A non-hex nonce or an empty endpoint is ignored.
  2. Merge with fix(devices): use the firmware version an onboarded vacuum reports #283 and fix(mqtt): update a vacuum's device record only from its own MQTT login #285. Fixed in d61fcea. The _conn_duids pop and mark_offline moved into _forget_conn_trace_state, which the trace worker runs when it reaches the close item. Packets queued before the close are traced first, so mark_seen can no longer clear the offline mark.
  3. Wrong offline state. Fixed. d61fcea keeps the newest connection that spoke for each robot and skips mark_offline when the closing connection is an older one. 99a5653 sets offline_at to the last-seen time for entries rebuilt from the log, and the next real packet clears it. 8abfcf9 does the same for entries loaded from disk, so a robot that was connected when the server stopped and never returns is not served as online.
  4. Any rr/d/i/ publish counts as the robot speaking. Fixed in d61fcea. A publish counts only when its topic equals _get_conn_device_topic(conn_id). Requests (protocol 101) are still read from any client, because the nonce is needed to decrypt the map reply.
  5. B01 and mowers. Mower pushes (model starting roborock.mower) no longer fill state or battery (d61fcea); they still update last-seen and offline. The startup seed skips mowers too (8abfcf9). B01 (Q7, Q10) is documented as not read, only last-seen and offline (4609149). I did not add B01 status parsing because I have no capture of it.
  6. Docs path. Fixed in 4609149: the docs say device_snapshots/.
  7. Minor. The store is flushed after the MQTT proxy stops (4609149). Flush builds the file contents under the store lock and writes them after releasing it (99a5653), so map files are no longer written under the lock. Flushes are now serialised, and a failed write keeps the entry dirty so the next flush retries it (8abfcf9). Writes still run on the calling thread; I did not add a background flusher.
  8. Tests. Added for base64 endpoints (parse and a full map decrypt), nonce-first order, a bad nonce, offline_at for rebuilt and loaded entries, the flush round trip, device-topic binding, the reconnect race, and packets queued before a close (99a5653, d61fcea, 8abfcf9). Test fixtures use obviously fake ids (65b7e10).

Exposure. I did not change ?map=1. Like every other /user/ route, it relies on the global protocol_auth_enabled Hawk check, which defaults to on. With that setting off, nothing under /user/ is authenticated. There is no per-device ownership check, because the server holds one account.

Full suite on this head: 540 passed. It stays in draft as you set it; it is ready for another review whenever you want to run one.

@virtitnerd
virtitnerd marked this pull request as ready for review November 22, 2026 02:52

@Lash-L Lash-L left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated review: passed (should-fix) (re-review at 8abfcf91)

Now that this has passed the automated review, I'll do a human review and then either request changes or merge it.

Earlier findings:

Finding Status
_SECURITY_RE missed base64 endpoints and nonce-first order Fixed: the request is now parsed as JSON, and the nonce must be hex. Tests cover a base64 endpoint with a full decrypt, and nonce-first order.
Merge with #283/#285 Fixed. The _conn_duids pop and mark_offline run in _forget_conn_trace_state when the trace worker reaches the close item, after the packets queued before it.
Reconnect race; rebuilt entries never offline Fixed. _duid_conn tracks the newest connection that spoke. Entries seeded from the log or loaded from disk get offline_at.
Any rr/d/i/ publish counted Fixed for live traffic: only client-to-broker publishes on the robot's bound _get_conn_device_topic count. The log seed still trusts any such line; minor.
Docs path, flush on shutdown, I/O under the store lock, tests Fixed.
?map=1 with protocol auth off Your point stands: every /user/ route shares the same global Hawk check, which is on by default. The docs could mention it.

Should fix:

  • The B01 claim in the docs doesn't match the code. The docs say B01 robots aren't read, but _observe_snapshot calls record_dps for every non-mower 102 push (mqtt_tls_proxy_server/server.py:654-655).
  • On a Q10, dps 121 is dpStatus (python-roborock b01_q10_code_mappings.py:106), so its status codes end up stored as the V1 state. The Q7 is unaffected.
  • This is from reading the code, not from a Q10 capture.
  • Fix: skip B01 messages, both live and in the seed.

Minor:

  • stop() waits only 2s for the trace worker, so updates traced after the shutdown flush can be lost. Flush once more after the worker exits.
  • A robot that reconnects without publishing yet shows offline until its first message. This corrects itself.

Checks: all 540 tests pass, and it merges cleanly with main.


This is an automated review by Claude Code, checked against the decompiled Roborock app (APK + device plugin bundles, refreshed 2026-11-21), python-roborock and a vacuum firmware dump. It can be incorrect, so please reply if any finding looks wrong.

@Lash-L Lash-L added passed auto review Automated review found no blocking issues and removed failing auto review Automated review requested changes before merge labels Nov 22, 2026
virtitnerd and others added 12 commits November 22, 2026 14:14
The last status, battery and error a robot sent, its last position and the map it was on,
and when it last spoke or went offline, written under device_snapshots/ so it survives a
restart. A robot that dies or loses Wi-Fi stops answering; this is what is left to say
where it was.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Robot-originated frames update the store: status pushes (dps 120/121/122), get_status
answers, and the map reply, which is decrypted with the nonce of whichever client's
request asked for it. A closing robot connection marks the device offline at once.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Returns status, position, last_seen_at and offline_at; ?map=1 adds the last map the robot
sent so a client can draw it while the robot cannot be asked.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
A robot that went quiet before the store existed still has its last status, battery and map
in the decoded MQTT log. On startup, in a background thread, devices the store has no snapshot
for are filled in from that log: last time heard, last status, and the last map decoded with
the nonce of the request that asked for it. Devices that already have a snapshot are left alone.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…h it

The snapshot had the last map but not which segment is which room, so an
offline map could only show generic labels. The proxy now records each
get_room_mapping answer, the startup seed reads it from the MQTT log, and
/last_known adds each room's name from the home data.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Both calls return the same status object, so either one now updates the stored state.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…fline

The regex needed endpoint before nonce and an all-word endpoint, but endpoints are
base64 (they can hold + and /) and the app may send the keys in either order, so
those robots never got maps or positions. Read the JSON instead.

Robots rebuilt from the MQTT log now get offline_at set to when they last spoke,
since nothing is connected right after a start; a long-dead robot no longer shows
as online. Flushes write files after releasing the store lock.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
… the trace worker

Any rr/d/i publish used to count as the robot speaking, but app and bootstrap logins
can publish on any topic; use the connection's device topic binding. The offline mark
moves into the trace worker's close handler so queued packets cannot call mark_seen
after mark_offline, and a close is ignored when the robot has already spoken on a
newer connection. Mower pushes are skipped because their dps 121/122 are not
state and battery.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…in the docs

The docs said last_known/ but the store writes device_snapshots/. Also note that
mowers and B01 robots only get last-seen and offline times.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The tests added by this PR carried a real device id, device ids and a captured
nonce and endpoint. Replace them with placeholder values.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Entries loaded from disk had no offline_at, so a robot connected at shutdown that
never returned looked online forever; they now start offline until they speak.
The startup seed now skips mowers like the live path (optional is_mower argument).
Flushes are serialised so an older snapshot cannot be written last, and a failed
write leaves the entry dirty for the next flush.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
virtitnerd and others added 4 commits November 22, 2026 14:15
On a Q10, dps 121 is dpStatus, whose codes are not V1 state values, so a B01 push was stored as the robot's state. B01 messages now only mark the robot seen, both live and when seeding from the log. The docs claim now matches that.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The seed trusted any rr/d/i/ client-to-broker line. It now requires the topic's username to be the one the device with that id logs in with. The log does not record which login sent a frame, so this is weaker than the live bound-topic check, and the docs say so.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
stop() waits only 2 seconds for the worker, and updates traced while it drained came after the server's own shutdown flush. The proxy now flushes after the join.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
A robot that reconnected but had not published yet showed offline until its first message. Its own-credential login now clears the offline mark and registers the connection, so closing it marks the robot offline again.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@Lash-L
Lash-L force-pushed the pr/last-known-state branch from 6879de4 to f9dae4c Compare November 22, 2026 19:16

@Lash-L Lash-L left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good, TY. Rebased

@Lash-L
Lash-L merged commit c836f4f into Python-roborock:main Nov 22, 2026
3 checks passed
Lash-L added a commit to virtitnerd/local_roborock_server that referenced this pull request Nov 22, 2026
Resolves the conflicts left by the squash merges of Python-roborock#251 and Python-roborock#253:
keeps the firmware routes, store and admin endpoints from this branch,
keeps main's schedule create/update/delete routes, and checks the OTA
routes before the schedule update in the HTTP handler.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@virtitnerd
virtitnerd deleted the pr/last-known-state branch November 22, 2026 19:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feature PR adding capability; under this two-type scheme also covers additive documentation. passed auto review Automated review found no blocking issues

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants