Repository navigation
fix(v1): refresh status after fan or water pushes - #1067
Conversation
Lash-L
left a comment
There was a problem hiding this comment.
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), keepsrefresh()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 incomingdpsdict soPropertiesApi._on_dps_update()still seesWATER_BOX_MODEto schedule the read-back. - Priority 2 — Lifecycle, Concurrency & Teardown:
PropertiesApi.close()cleanly unsubscribes_unsuband cancels pending/in-flight read-back tasks, andRoborockDevice.close()invokesv1_properties.close(). One finding (inline below): clearing_status_refresh_pendingbeforeawait self.status.refresh_and_notify()allows overlapping concurrentget_statuscalls 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_APIverified): Verified against the Roborock Tanos app bundle (convertWaterModeinmodule_1631.js/module_1614.js): onisWaterSlideModeSupported()devices, legacy water codes201/202/203/208(and207) map to slider equivalents (225/235/245/250) while200(off),204(custom),209(smart mode),210(smart water), and221–250pass through, andmop_modehas 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 intoget_water_slide_mode_name(code), which will raiseTypeErroron stringified/non-int payloads thatDpsDataConverterpreviously handled gracefully. - Tests & Scoping: Well-scoped PR with all CI checks passing. Tests follow mirror colocation (
tests/devices/traits/v1/test_init.pyandtests/devices/traits/v1/test_status.py), use@pytest.mark.parametrize, and assert on public behavior.
| """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 |
There was a problem hiding this comment.
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)There was a problem hiding this comment.
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.
| 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: |
There was a problem hiding this comment.
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}There was a problem hiding this comment.
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.
|
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 |
Lash-L
left a comment
There was a problem hiding this comment.
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-flightget_statusread-back at a time, eliminates out-of-order stale overwrites, and keeps teardown inPropertiesApi.close()clean.test_push_during_refresh_schedules_anothernow 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 toint(excludingbool, parsing numeric strings, and dropping non-integer/malformed payloads without raising), preserving immutability of the incomingdpsdict 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.
| _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: |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
7a391ee to
82fee57
Compare
| @@ -0,0 +1,55 @@ | |||
| """Tests for the V1 trait properties API.""" | |||
There was a problem hiding this comment.
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.
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.
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.
What
Two fixes for how V1 data protocol pushes update the status trait:
water_box_modethat the slider cannot name is ignored. The robot pushes the old level codes (201/202/203, and 208 for the top of the slider), whileget_statusreturns slider codes (200, 221-250). Storing the pushed code leftwater_mode_nameasNone("unknown") until the next poll. Codes 200, 204, 209 and 221-250 are still applied, and devices without a water slider are unchanged.fan_powerorwater_box_mode,PropertiesApireads 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 andmop_modeshortly after a mode change made elsewhere (for example leaving SmartPlan or switching vacuum and mop to vacuum), whichmop_modenever 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=202was followed by aget_statusthat returned 235,124=203by 246.Behavior notes
fan_powerorwater_box_modecause no request.PropertiesApi.close()cancels pending and running read-backs. ARoborockExceptionfrom the read-back is logged and does not stop later ones.tests/devices/traits/v1/test_status.pyand intests/devices/traits/v1/test_init.py(new, the mirror file fortraits/v1/__init__.py; nothing covered the push handler before).Conflicts with open PRs
Test-merged with every open PR that touches the same files:
tests/devices/traits/v1/test_status.pyonly (new tests appended in the same place). No conflict in code. Whichever merges second rebases and keeps both sets of tests. feat(v1): expose clean-then-mop status from the device #959 and feat(v1): offer SmartPlan and custom modes in the cleaning mode options #1055/feat(v1): add fan speed, water and mop route setters that refuse changes in SmartPlan and custom mode #1064 also touchstatus.pynearupdate_from_dpswithout a text conflict.Checks
uv run pre-commit run --all-files(ruff, mypy, codespell) passes, andtests/devicespasses (961 tests).