From 77962e0721c46eaa40ab95b2d4a2e229121adf82 Mon Sep 17 00:00:00 2001 From: Luke Date: Sun, 29 Nov 2026 13:07:40 -0500 Subject: [PATCH] fix(mqtt): only mark a vacuum online from its own MQTT traffic record_mqtt_message marked a vacuum connected on any message whose topic named it, including app and Home Assistant requests on rr/m/i/.../. An offline vacuum that a client polls then reported online until that client's MQTT connection closed. Only the vacuum's own c2b publishes on rr/d/i//... now mark it connected, and the proxy marks it connected as soon as it logs in with its own MQTT credentials. Co-Authored-By: Claude Opus 5.5 --- .../mqtt_tls_proxy_server/server.py | 5 + .../bundled_backend/shared/runtime_state.py | 63 +++++++-- tests/test_admin_api.py | 25 +++- tests/test_home_data_online.py | 131 ++++++++++++++++++ 4 files changed, 208 insertions(+), 16 deletions(-) diff --git a/src/roborock_local_server/bundled_backend/mqtt_tls_proxy_server/server.py b/src/roborock_local_server/bundled_backend/mqtt_tls_proxy_server/server.py index 6f3cf9e1..8cc8ef08 100644 --- a/src/roborock_local_server/bundled_backend/mqtt_tls_proxy_server/server.py +++ b/src/roborock_local_server/bundled_backend/mqtt_tls_proxy_server/server.py @@ -179,6 +179,11 @@ 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}") + if self.runtime_state is not None: + try: + self.runtime_state.record_device_mqtt_login(conn_id=conn_id, did=did) + except Exception: + self.logger.exception("[conn %s] recording the robot MQTT login failed", conn_id) # 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: diff --git a/src/roborock_local_server/bundled_backend/shared/runtime_state.py b/src/roborock_local_server/bundled_backend/shared/runtime_state.py index d048735b..4d5b4b9e 100644 --- a/src/roborock_local_server/bundled_backend/shared/runtime_state.py +++ b/src/roborock_local_server/bundled_backend/shared/runtime_state.py @@ -352,20 +352,16 @@ def record_mqtt_message( vac["id_kind"] = id_kind or vac.get("id_kind", "") if did: vac["did"] = did - vac["connected"] = True - vac["last_mqtt_at"] = now - vac["last_mqtt_topic"] = topic - vac["last_mqtt_direction"] = direction - vac["last_mqtt_payload_preview"] = payload_preview - vac["last_message_at"] = now - vac["last_message_source"] = "mqtt" - vac["last_mqtt_conn_id"] = conn_id - if conn is not None: - client_ip = str(conn.get("client_ip") or "") - if client_ip: - vac["ips"].add(client_ip) - vac["last_ip"] = client_ip - self._conn_to_vacuums.setdefault(conn_id, set()).add(device_id) + # Only the vacuum itself publishes on its rr/d/i//... topic. App and + # Home Assistant clients publish requests on rr/m/i/.../ whether or not + # the vacuum is reachable, so that traffic must not mark the vacuum connected + # or tie it to the app's MQTT connection (it would then report online until + # the app disconnects). + if id_kind == "did" and direction == "c2b": + self._mark_vacuum_mqtt_connected_locked(vac, vac_key=device_id, conn_id=conn_id, conn=conn, now=now) + vac["last_mqtt_topic"] = topic + vac["last_mqtt_direction"] = direction + vac["last_mqtt_payload_preview"] = payload_preview self._record_pairing_mqtt_event_locked( event_time=now, @@ -374,6 +370,45 @@ def record_mqtt_message( client_ip=str(conn.get("client_ip") or "") if conn is not None else "", ) + def record_device_mqtt_login(self, *, conn_id: str, did: str) -> None: + """Mark a vacuum connected as soon as it logs in with its own MQTT credentials.""" + normalized_did = (did or "").strip() + if not normalized_did: + return + now = utcnow_iso() + with self._lock: + vac = self._ensure_vacuum_locked(normalized_did) + vac["id_kind"] = vac.get("id_kind") or "did" + vac["did"] = normalized_did + self._mark_vacuum_mqtt_connected_locked( + vac, + vac_key=normalized_did, + conn_id=conn_id, + conn=self._mqtt_connections.get(conn_id), + now=now, + ) + + def _mark_vacuum_mqtt_connected_locked( + self, + vac: dict[str, Any], + *, + vac_key: str, + conn_id: str, + conn: dict[str, Any] | None, + now: str, + ) -> None: + vac["connected"] = True + vac["last_mqtt_at"] = now + vac["last_message_at"] = now + vac["last_message_source"] = "mqtt" + vac["last_mqtt_conn_id"] = conn_id + if conn is not None: + client_ip = str(conn.get("client_ip") or "") + if client_ip: + vac["ips"].add(client_ip) + vac["last_ip"] = client_ip + self._conn_to_vacuums.setdefault(conn_id, set()).add(vac_key) + def record_cloud_request(self, result: dict[str, Any]) -> None: with self._lock: self._cloud_request = { diff --git a/tests/test_admin_api.py b/tests/test_admin_api.py index c300ba7f..951f629f 100644 --- a/tests/test_admin_api.py +++ b/tests/test_admin_api.py @@ -1030,7 +1030,27 @@ def test_ui_api_health_and_vacuums_require_admin_auth(tmp_path: Path) -> None: + "\n", encoding="utf-8", ) + paths.runtime_credentials_path.parent.mkdir(parents=True, exist_ok=True) + paths.runtime_credentials_path.write_text( + json.dumps( + { + "schema_version": 2, + "devices": [ + { + "did": "1103811971559", + "duid": "inventory-s7-duid", + "name": "S7", + "model": "roborock.vacuum.a15", + "device_mqtt_usr": "dd211305e2d4873b", + } + ], + } + ) + + "\n", + encoding="utf-8", + ) supervisor = ReleaseSupervisor(config=config, paths=paths) + supervisor.refresh_inventory_state() supervisor.runtime_state.record_mqtt_connection( conn_id="ui-conn-1", client_ip="192.168.1.50", @@ -1039,7 +1059,7 @@ def test_ui_api_health_and_vacuums_require_admin_auth(tmp_path: Path) -> None: supervisor.runtime_state.record_mqtt_message( conn_id="ui-conn-1", direction="c2b", - topic="rr/m/i/test-user/test-client/inventory-s7-duid", + topic="rr/d/i/1103811971559/dd211305e2d4873b", payload_preview="{}", ) @@ -1055,7 +1075,8 @@ def test_ui_api_health_and_vacuums_require_admin_auth(tmp_path: Path) -> None: assert health.status_code == 200 health_payload = health.json() assert health_payload["active_mqtt_connections"] == 1 - assert [vac["duid"] for vac in health_payload["connected_vacuums"]] == ["inventory-s7-duid"] + # Raw runtime health keys the robot by the DID from its own rr/d topic. + assert [vac["did"] for vac in health_payload["connected_vacuums"]] == ["1103811971559"] vacuums = client.get("/ui/api/vacuums") assert vacuums.status_code == 200 diff --git a/tests/test_home_data_online.py b/tests/test_home_data_online.py index c42863aa..7cfc2426 100644 --- a/tests/test_home_data_online.py +++ b/tests/test_home_data_online.py @@ -597,3 +597,134 @@ def test_home_data_uses_firmware_version_reported_by_onboarded_device(tmp_path: "1103844865396": "02.44.86", "6HL2zfniaoYYV01CkVuhkO": "02.16.12", } + + +def test_home_data_does_not_mark_offline_devices_online_from_app_mqtt_requests(tmp_path: Path) -> None: + """App/HA clients publish rr/m/i/.../ requests to offline vacuums too. + + That traffic must not make an offline vacuum (or a received/shared one) report + ``online: true``; only the vacuum's own rr/d/i//... traffic counts. + """ + config_file = write_release_config(tmp_path) + config = load_config(config_file) + paths = resolve_paths(config_file, config) + + paths.runtime_dir.mkdir(parents=True, exist_ok=True) + paths.state_dir.mkdir(parents=True, exist_ok=True) + paths.inventory_path.write_text( + json.dumps( + { + "home": {"id": 1233716, "name": "My Home"}, + "devices": [ + { + "duid": "1dzp2UMXIAhnJIyoK9bCKT", + "name": "Q7", + "model": "roborock.vacuum.sc05", + "product_id": "q7-product", + "local_key": "q7localkey123456", + "online": False, + }, + { + "duid": "6HL2zfniaoYYV01CkVuhkO", + "name": "Roborock Qrevo MaxV 2", + "model": "roborock.vacuum.a87", + "product_id": "5gUei3OIJIXVD3eD85Balg", + "local_key": "xPd5Dr8CGGqtdDlH", + "online": False, + }, + ], + "received_devices": [ + { + "duid": "1OVJHS7cL6XxkYkoOGr2Hw", + "name": "S7", + "model": "roborock.vacuum.a15", + "product_id": "1YYW18rpgyAJTISwb1NM91", + "local_key": "GTWJJAA457z43dur", + "online": False, + } + ], + } + ) + + "\n", + encoding="utf-8", + ) + _seed_cloud_snapshot(paths.cloud_snapshot_path, {"id": 1233716, "name": "My Home"}) + paths.runtime_credentials_path.write_text( + json.dumps( + { + "schema_version": 2, + "devices": [ + {"did": "1103833856260", "duid": "1dzp2UMXIAhnJIyoK9bCKT", "model": "roborock.vacuum.sc05"}, + { + "did": "1103821560705", + "duid": "6HL2zfniaoYYV01CkVuhkO", + "model": "roborock.vacuum.a87", + "device_mqtt_usr": "c25b14ceac358d2a", + }, + {"did": "1103811971559", "duid": "1OVJHS7cL6XxkYkoOGr2Hw", "model": "roborock.vacuum.a15"}, + ], + } + ) + + "\n", + encoding="utf-8", + ) + + supervisor = ReleaseSupervisor(config=config, paths=paths) + supervisor.refresh_inventory_state() + runtime = supervisor.runtime_state + # The a87 is connected and publishing on its own device topic. + runtime.record_mqtt_connection(conn_id="a87", client_ip="192.168.20.250", client_port=1883) + runtime.record_mqtt_message( + conn_id="a87", + direction="c2b", + topic="rr/d/i/1103821560705/c25b14ceac358d2a", + payload_preview="{}", + ) + # Home Assistant / the app keeps polling the offline Q7 and S7 over MQTT. + runtime.record_mqtt_connection(conn_id="ha", client_ip="192.168.20.199", client_port=1883) + for duid in ("1dzp2UMXIAhnJIyoK9bCKT", "1OVJHS7cL6XxkYkoOGr2Hw", "6HL2zfniaoYYV01CkVuhkO"): + runtime.record_mqtt_message( + conn_id="ha", + direction="c2b", + topic=f"rr/m/i/hawk-user-123/3110ba68/{duid}", + payload_preview="{}", + ) + + client = TestClient(supervisor.app) + for path in ("/v3/user/homes/1233716", "/v2/user/homes/1233716"): + response = client.get(path, headers=_hawk_headers(paths.cloud_snapshot_path, path)) + assert response.status_code == 200 + home_data = response.json()["data"] + online = { + device["name"]: device["online"] + for device in [*home_data["devices"], *home_data.get("receivedDevices", [])] + } + assert online == {"Q7": False, "Roborock Qrevo MaxV 2": True, "S7": False}, path + + detail_path = "/user/devices/1dzp2UMXIAhnJIyoK9bCKT" + detail = client.get(detail_path, headers=_hawk_headers(paths.cloud_snapshot_path, detail_path)) + assert detail.status_code == 200 + assert detail.json()["data"]["online"] is False + + # Once the a87 drops off (and its 180 s grace window has passed), the app's + # continued polling must not bring it, or anything else, back online. + runtime.record_mqtt_disconnect(conn_id="a87") + runtime._vacuums["1103821560705"]["last_mqtt_at"] = "2026-01-01T00:00:00+00:00" + for duid in ("1dzp2UMXIAhnJIyoK9bCKT", "1OVJHS7cL6XxkYkoOGr2Hw", "6HL2zfniaoYYV01CkVuhkO"): + runtime.record_mqtt_message( + conn_id="ha", + direction="c2b", + topic=f"rr/m/i/hawk-user-123/3110ba68/{duid}", + payload_preview="{}", + ) + assert not any(vac["connected"] for vac in runtime.vacuum_snapshot()) + + +def test_runtime_state_marks_vacuum_connected_on_device_credential_login(tmp_path: Path) -> None: + from roborock_local_server.bundled_backend.shared.runtime_state import RuntimeState + + state = RuntimeState(log_dir=tmp_path, key_state_file=None) + state.record_mqtt_connection(conn_id="dev", client_ip="192.168.20.250", client_port=1883) + state.record_device_mqtt_login(conn_id="dev", did="1103821560705") + snapshot = state.vacuum_snapshot() + assert [(vac["did"], vac["connected"]) for vac in snapshot] == [("1103821560705", True)]