Skip to content

fix(v1): refresh status after fan or water pushes - #1067

Merged
allenporter merged 3 commits into
Python-roborock:mainfrom
infy1995:claude/v1-push-refresh
Nov 23, 2026
Merged

allenporter merged 3 commits into
Python-roborock:mainfrom
infy1995:claude/v1-push-refresh

Conversation

@infy1995

@infy1995 infy1995 commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

What

Two fixes for how V1 data protocol pushes update the status trait:

  1. On water-slide devices, a pushed water_box_mode that the slider cannot name is ignored. The robot pushes the old level codes (201/202/203, and 208 for the top of the slider), while get_status returns slider codes (200, 221-250). Storing the pushed code left water_mode_name as None ("unknown") until the next poll. Codes 200, 204, 209 and 221-250 are still applied, and devices without a water slider are unchanged.
  2. After a push that contains fan_power or water_box_mode, PropertiesApi reads the status back once, about one second later (StatusTrait.refresh_and_notify()). Status listeners are notified only if the status changed. This corrects the water level and mop_mode shortly after a mode change made elsewhere (for example leaving SmartPlan or switching vacuum and mop to vacuum), which mop_mode never gets from a push.

Why

Measured on a Saros 10R: after changing water in the Roborock app, Home Assistant showed "unknown" for a few seconds, and the cleaning mode stayed stale after a mode change. Push log: 124=202 was followed by a get_status that returned 235, 124=203 by 246.

Behavior notes

  • At most one read-back per one-second window: pushes inside the window share it, and a push that arrives during a running read-back schedules another. Pushes without fan_power or water_box_mode cause no request.
  • PropertiesApi.close() cancels pending and running read-backs. A RoborockException from the read-back is logged and does not stop later ones.
  • A response that is already in flight can briefly overwrite a newer pushed value; the scheduled follow-up read-back corrects it.
  • A change of only the mop route is never pushed by the robot, so route-only changes still wait for the client's next poll.
  • docs/DEVICES.md now describes the pushed status updates, the read-back and the route-only limitation.
  • New tests are in tests/devices/traits/v1/test_status.py and in tests/devices/traits/v1/test_init.py (new, the mirror file for traits/v1/__init__.py; nothing covered the push handler before).

Conflicts with open PRs

Test-merged with every open PR that touches the same files:

Checks

uv run pre-commit run --all-files (ruff, mypy, codespell) passes, and tests/devices passes (961 tests).

@Lash-L Lash-L left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Automated code review by Gemini 4 Neon in Antigravity using our /review (/code-review) skill (.agents/skills/code-review/SKILL.md / AGENTS.md).

Summary by Architectural Layer

  • Priority 1 — Public Trait APIs & Consumer Contracts: Clean. StatusTrait.refresh_and_notify() has a concrete signature (async def refresh_and_notify(self) -> None), keeps refresh() silent for polling consumers (avoiding double-notifications), and remains consumer-agnostic. _drop_unresolvable_water_level() is a pure value-returning helper that avoids mutating the incoming dps dict so PropertiesApi._on_dps_update() still sees WATER_BOX_MODE to schedule the read-back.
  • Priority 2 — Lifecycle, Concurrency & Teardown: PropertiesApi.close() cleanly unsubscribes _unsub and cancels pending/in-flight read-back tasks, and RoborockDevice.close() invokes v1_properties.close(). One finding (inline below): clearing _status_refresh_pending before await self.status.refresh_and_notify() allows overlapping concurrent get_status calls when a push arrives during a slow (>1 s) read-back, risking out-of-order stale overwrites; serializing into a single task with a dirty flag eliminates the race and simplifies state.
  • Priority 3 — Wire Protocols, Codecs & Resilience (RR_API verified): Verified against the Roborock Tanos app bundle (convertWaterMode in module_1631.js / module_1614.js): on isWaterSlideModeSupported() devices, legacy water codes 201/202/203/208 (and 207) map to slider equivalents (225/235/245/250) while 200 (off), 204 (custom), 209 (smart mode), 210 (smart water), and 221–250 pass through, and mop_mode has no V1 DP push code (123 = FAN_POWER, 124 = WATER_BOX_MODE). One finding (inline below): _drop_unresolvable_water_level() passes raw wire JSON values (Any) straight into get_water_slide_mode_name(code), which will raise TypeError on stringified/non-int payloads that DpsDataConverter previously handled gracefully.
  • Tests & Scoping: Well-scoped PR with all CI checks passing. Tests follow mirror colocation (tests/devices/traits/v1/test_init.py and tests/devices/traits/v1/test_status.py), use @pytest.mark.parametrize, and assert on public behavior.

Comment thread roborock/devices/traits/v1/__init__.py Outdated
"""Read status back after a short delay to pick up values that are not pushed."""
await asyncio.sleep(_STATUS_REFRESH_DELAY)
# Clear first so a push arriving during the refresh schedules another one.
self._status_refresh_pending = False

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Priority 2 (Concurrency & Stale Overwrites): Clearing self._status_refresh_pending = False before await self.status.refresh_and_notify() allows a second read-back task to start and run concurrently if a push arrives while the first get_status call takes longer than _STATUS_REFRESH_DELAY (e.g., during local-to-MQTT fallback or cloud latency). If the older in-flight get_status response finishes after the newer one, it overwrites self.status with stale state and notifies listeners, with no further read-back scheduled.

Serializing read-backs through a single task + dirty flag prevents concurrent get_status RPCs and out-of-order overwrites while also simplifying task tracking (no set or done callback needed):

# In __init__:
self._status_refresh_needed = False
self._status_refresh_task: asyncio.Task[None] | None = None

# In close():
self._status_refresh_needed = False
if self._status_refresh_task is not None:
    self._status_refresh_task.cancel()
    self._status_refresh_task = None

def _schedule_status_refresh(self) -> None:
    self._status_refresh_needed = True
    if self._status_refresh_task is None or self._status_refresh_task.done():
        self._status_refresh_task = asyncio.create_task(self._refresh_status_after_push())

async def _refresh_status_after_push(self) -> None:
    while self._status_refresh_needed:
        await asyncio.sleep(_STATUS_REFRESH_DELAY)
        self._status_refresh_needed = False
        try:
            await self.status.refresh_and_notify()
        except RoborockException as err:
            _LOGGER.warning("Failed to refresh status after a push: %s", err)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch. Fixed in a661416: read-backs are now serialized through a single task plus a "needed" flag. A push that arrives while a get_status is in flight sets the flag, and the loop runs one more read-back after the current one returns, so two get_status calls never overlap and the newest response is applied last. Bursts still produce one read-back per delay window, and close() cancels the task. The tests cover a push during an in-flight read-back, at most one call running at a time, and the final state coming from the newer response.

Comment thread roborock/devices/traits/v1/status.py Outdated
returns. Only slider codes, off, smart water, smart mode and custom are kept.
"""
code = decoded_dps.get(RoborockDataProtocol.WATER_BOX_MODE)
if code is None or code in _WATER_MODE_CODES_KEPT or get_water_slide_mode_name(code) is not None:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Priority 3 (Wire Payload Resilience): decoded_dps contains raw JSON values (dict[RoborockDataProtocol, Any]) before DpsDataConverter / RoborockBase.convert_dict coerces them to int. If a push carries a stringified integer (e.g. "235" — which the Roborock app itself parses via parseInt) or an unexpected non-int value, get_water_slide_mode_name(code) evaluates code - 220 and raises an unhandled TypeError, aborting PropertiesApi._on_dps_update() before consumables.update_from_dps() and _schedule_status_refresh() run.

Safely coerce/narrow before checking:

def _drop_unresolvable_water_level(decoded_dps: dict[RoborockDataProtocol, Any]) -> dict[RoborockDataProtocol, Any]:
    code = decoded_dps.get(RoborockDataProtocol.WATER_BOX_MODE)
    if code is None:
        return decoded_dps
    if isinstance(code, bool):
        return {key: value for key, value in decoded_dps.items() if key != RoborockDataProtocol.WATER_BOX_MODE}
    try:
        code_int = int(code)
    except (TypeError, ValueError):
        return {key: value for key, value in decoded_dps.items() if key != RoborockDataProtocol.WATER_BOX_MODE}
    if code_int in _WATER_MODE_CODES_KEPT or get_water_slide_mode_name(code_int) is not None:
        return decoded_dps
    return {key: value for key, value in decoded_dps.items() if key != RoborockDataProtocol.WATER_BOX_MODE}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 7a391ee. The water code is now narrowed to an int before it is resolved: bools, non-numeric strings and other types are dropped without raising, and a numeric string such as "235" is resolved as 235. A malformed water code no longer aborts the rest of _on_dps_update (consumables update and read-back scheduling still run); tests cover "235", "abc", bool, float, None and list values.

@Lash-L Lash-L added the /review run Code review skill (/review) has been run label Nov 21, 2026
@infy1995

Copy link
Copy Markdown
Contributor Author

About mapping legacy 201/202/203/208 to the slider codes 225/235/245/250: I kept dropping the pushed code and reading the status back instead. The read-back is needed anyway for the mop route and the exact slider position, and it returns the real value (for example 124=202 was followed by 235 and 124=203 by 246 on a Saros 10R), so a static mapping would only be a guess that the read-back then corrects.

@Lash-L Lash-L left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Automated code review by Gemini 4 Neon in Antigravity using our /review (/code-review) skill (.agents/skills/code-review/SKILL.md / AGENTS.md).

Follow-up Review (71e345b → 7a391ee)

Both findings from the prior review on 71e345b have been cleanly resolved, with no new issues introduced:

  • Priority 2 — Serialized Status Read-Back (roborock/devices/traits/v1/__init__.py, a661416): Resolved. Replacing the pending flag + task set with a single worker task (_status_refresh_task) and dirty flag (_status_refresh_needed) guarantees at most one in-flight get_status read-back at a time, eliminates out-of-order stale overwrites, and keeps teardown in PropertiesApi.close() clean. test_push_during_refresh_schedules_another now verifies single-flight execution (max_running == 1) and final state ordering.
  • Priority 3 — Wire Payload Type Narrowing (roborock/devices/traits/v1/status.py, 7a391ee): Resolved. _drop_unresolvable_water_level() now explicitly narrows raw JSON values to int (excluding bool, parsing numeric strings, and dropping non-integer/malformed payloads without raising), preserving immutability of the incoming dps dict so consumables updates and read-back scheduling continue uninterrupted. Unit tests cover numeric strings and malformed values ("abc", "", True, 1.5, None, list, dict) as well as end-to-end push handling.

All CI checks pass on 7a391ee. No surviving findings — this PR passes /review and looks ready to approve/merge.

@Lash-L Lash-L added the Passed /review Passed the /review skill check label Nov 21, 2026
Comment thread roborock/devices/traits/v1/__init__.py Outdated
_LOGGER.debug("Received message from device: %s", dps)
self.status.update_from_dps(dps)
self.consumables.update_from_dps(dps)
if RoborockDataProtocol.FAN_POWER in dps or RoborockDataProtocol.WATER_BOX_MODE in dps:

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.

can this all live in the status trait, which is invoked a couple lines above? given this is all about refreshing the status trait, i dont think the logic needs to live in the main trait property holder.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed, moved. The whole read-back (delay, single task plus a "needed" flag, scheduling, cancellation) now lives in StatusTrait and is triggered from StatusTrait.update_from_dps; PropertiesApi only forwards the push and calls the new StatusTrait.close() from its own close(). Behavior is unchanged: one get_status at a time, one read-back per delay window, and a push during an in-flight read-back leads to another one afterwards. The tests moved to test_status.py. I also squashed the branch into three commits (water code filter, status read-back, docs) so the changelog stays readable.

…ider cannot name

Water-slide devices push legacy water codes (201-203 and 208) while
get_status returns slider codes. Applying the pushed legacy code left
water_mode_name as None until the next poll.

On water-slide devices a pushed water code is now kept only when the slider
can name it, or when it is the off, smart water, smart mode or custom code.
Non-integer payloads are dropped without raising, so the rest of the push is
still applied.
The robot pushes fan power and water mode changes but never pushes the mop
mode, so the cleaning mode stayed stale after such a push until the next poll.

After a fan power or water mode push the status trait now reads get_status
back once, debounced. At most one get_status is in flight at a time, a burst
of pushes causes one read-back per window, and a push during a running
read-back is followed by another one after it finishes. Listeners are
notified only if the read-back changed the status. PropertiesApi.close()
cancels a pending or running read-back.
@@ -0,0 +1,55 @@
"""Tests for the V1 trait properties API."""

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.

I don't think we need this given we have sufficient coverage in test_status.py? I'm going to merge to get the change and we can clean up in a followup.

@allenporter
allenporter merged commit f72b355 into Python-roborock:main Nov 23, 2026
9 checks passed
@infy1995
infy1995 deleted the claude/v1-push-refresh branch November 23, 2026 06:40
infy1995 added a commit to infy1995/python-roborock that referenced this pull request Nov 23, 2026
Follow-up to Python-roborock#1067 requested by the maintainer: test_status.py already covers
closing the status trait, so test_init.py is redundant. Closing through
PropertiesApi.close() is now covered there as well.
allenporter pushed a commit that referenced this pull request Nov 24, 2026
Follow-up to #1067, where the maintainer noted that test_init.py is redundant
because test_status.py already covers closing the status trait. Closing through
PropertiesApi.close() is now covered in test_status.py as well.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Passed /review Passed the /review skill check /review run Code review skill (/review) has been run

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants