From f8d47c545e753405fd8fdd050dd73833d12e99dd Mon Sep 17 00:00:00 2001 From: Immanuel Date: Sun, 25 Oct 2026 08:01:06 +0100 Subject: [PATCH 1/4] feat(api): enable scene tiles via productTags and category cardSpec The Android app hides a device's scene quick-start tiles unless RRDeviceBeanV2.supportScene() is true: product.sceneProduct().forceShow && isRoborock() && hasFeature(0x21) && category.cardSpec != null isRoborock() and feature bit 33 (from featureSet in home data) were already satisfied. Missing were: - productTags with a "scene_2.0" entry (forceShow=true); sceneProduct() looks up exactly this tag in productTagsMap, which the app builds from the list. - a cardSpec on the category (CardSpecV2: state/extra/battery/offline data points, no "data" wrapper). Both spellings declared by CategoryEntity ("cardspec" and "cardSpec") are sent. Labels are English only. Co-Authored-By: Claude Opus 5.5 --- .../https_server/routes/api/card_spec.py | 77 +++++++++++++++++++ .../routes/api/product_service.py | 36 +++++++-- tests/test_product_response.py | 45 +++++++++++ 3 files changed, 150 insertions(+), 8 deletions(-) create mode 100644 src/roborock_local_server/bundled_backend/https_server/routes/api/card_spec.py diff --git a/src/roborock_local_server/bundled_backend/https_server/routes/api/card_spec.py b/src/roborock_local_server/bundled_backend/https_server/routes/api/card_spec.py new file mode 100644 index 00000000..98c16f9e --- /dev/null +++ b/src/roborock_local_server/bundled_backend/https_server/routes/api/card_spec.py @@ -0,0 +1,77 @@ +"""Home card specs (CardSpecV2) per product category. + +The Android app only shows the scene quick-start tiles of a device when its +category carries a card spec (RRDeviceBeanV2.supportScene() returns false when +CategoryEntity.cardSpec is null). CardSpecV2 holds four data points directly +as fields - state, extra, battery, offline - each {"dps", "desc", "value"}. +Note that the template bundled with the app wraps these in {"data": {...}}; +the API field holds the inner object. + +Labels are English only. The app's bundled template carries ~30 languages. +""" + +from __future__ import annotations + +import copy +from typing import Any + + +def _state(label: str, *codes: int) -> dict[str, Any]: + return {"desc": {"en": label}, "value": list(codes)} + + +_ROBOT_VACUUM_CARD_SPEC: dict[str, Any] = { + "state": { + "dps": 121, + "desc": {"en": "State"}, + "value": [ + _state("Sleeping", 2), + _state("Ready", 3), + _state("Cleaning", 5, 11, 17, 18, 102, 103, 104), + _state("Return to the dock", 6), + _state("Remote Control", 7, 39), + _state("Charging", 8), + _state("Charging error", 9), + _state("Pause", 10), + _state("Error", 12), + _state("Washing the mop", 13), + _state("Updating", 14), + _state("Return to the dock", 15), + _state("Pin n Go", 16), + _state("Emptying", 22), + _state("Washing the mop", 23), + _state("Return to the dock", 26), + _state("In call", 28), + _state("Mapping", 29), + _state("On cruise", 32), + _state("Reinstalling mop cloth mounts", 33), + _state("Detaching mop cloth mounts", 34), + _state("Demo Mode", 36, 37), + _state("Housework in progress", 38), + _state("Emergency Stop", 40), + _state("Positioning", 101), + _state("Charge Pending", 108), + ], + }, + "extra": {"dps": 128}, + "battery": {"dps": 122}, + "offline": { + "dps": 135, + "desc": {"en": "Offline State"}, + "value": [ + _state("Manual Shutdown", 1), + _state("Sleep & Powered Off", 2, 34), + _state("Low Battery & Powered Off", 3, 51), + _state("Updating & Restarting", 4, 103), + ], + }, +} + +CATEGORY_CARD_SPECS: dict[str, dict[str, Any]] = { + "robot.vacuum.cleaner": _ROBOT_VACUUM_CARD_SPEC, +} + + +def card_spec_for_category(category_name: str) -> dict[str, Any] | None: + spec = CATEGORY_CARD_SPECS.get(category_name) + return copy.deepcopy(spec) if spec is not None else None diff --git a/src/roborock_local_server/bundled_backend/https_server/routes/api/product_service.py b/src/roborock_local_server/bundled_backend/https_server/routes/api/product_service.py index e450d8e9..e3be50ab 100644 --- a/src/roborock_local_server/bundled_backend/https_server/routes/api/product_service.py +++ b/src/roborock_local_server/bundled_backend/https_server/routes/api/product_service.py @@ -9,6 +9,7 @@ from ..plugin.common import snapshot_plugin_catalog_data from ..user.homes.service import home_payload +from .card_spec import card_spec_for_category def build_product_response(ctx: ServerContext) -> dict[str, Any]: @@ -24,15 +25,23 @@ def build_product_response(ctx: ServerContext) -> dict[str, Any]: category_name = str(product.get("category") or "robot.vacuum.cleaner") if category_name not in categories: category_id = len(categories) + 1 + category_entry: dict[str, Any] = { + "id": category_id, + # CategoryEntity.code becomes Product.code in the app, which + # the device plugin receives as deviceCategory. + "code": category_name, + "displayName": category_name, + "iconUrl": "", + } + card_spec = card_spec_for_category(category_name) + if card_spec is not None: + # Required for the scene tiles. CategoryEntity declares both + # spellings; which one is the JSON name could not be decided + # from the bytecode, so both are sent. + category_entry["cardspec"] = card_spec + category_entry["cardSpec"] = card_spec categories[category_name] = { - "category": { - "id": category_id, - # CategoryEntity.code becomes Product.code in the app, which - # the device plugin receives as deviceCategory. - "code": category_name, - "displayName": category_name, - "iconUrl": "", - }, + "category": category_entry, "productList": [], } model = str(product.get("model") or "roborock.vacuum.a117") @@ -59,6 +68,17 @@ def build_product_response(ctx: ServerContext) -> dict[str, Any]: # Read by PluginSDKModule.getProductAgreements; a missing field is # null and the device plugin's privacy check never completes. "agreements": [], + # ProductEntity.sceneProduct() looks up the "scene_2.0" tag; without + # it the scene tiles stay hidden. The app builds productTagsMap from + # this list itself. + "productTags": [ + { + "name": "scene_2.0", + "forceShow": True, + "pluginLevel": 0, + "requirePlugin": False, + } + ], } icon_url = product.get("iconUrl") if isinstance(icon_url, str) and icon_url: diff --git a/tests/test_product_response.py b/tests/test_product_response.py index 35c05ebb..d621749a 100644 --- a/tests/test_product_response.py +++ b/tests/test_product_response.py @@ -141,3 +141,48 @@ def test_string_product_id_uses_cloud_numeric_id_by_model(tmp_path: Path) -> Non [product] = data["categoryDetailList"][0]["productList"] assert product["id"] == 199 assert product["rriotid"] == "30uADinyLKa3Qpga60B1Ke" + + +def test_product_entry_enables_scene_tiles(tmp_path: Path) -> None: + data = _products_v5(tmp_path, [_DEVICE]) + + category_detail = data["categoryDetailList"][0] + [product] = category_detail["productList"] + category = category_detail["category"] + + # ProductEntity.sceneProduct() looks up exactly this tag. + assert {"name": "scene_2.0", "forceShow": True, "pluginLevel": 0, "requirePlugin": False} in product[ + "productTags" + ] + # CardSpecV2 holds the four data points directly, without a "data" wrapper. + for key in ("cardspec", "cardSpec"): + card_spec = category[key] + assert set(card_spec) == {"state", "extra", "battery", "offline"} + assert card_spec["state"]["dps"] == 121 + assert card_spec["battery"]["dps"] == 122 + assert card_spec["extra"]["dps"] == 128 + assert card_spec["offline"]["dps"] == 135 + for entry in card_spec["state"]["value"]: + assert set(entry) == {"desc", "value"} + assert entry["desc"]["en"] + assert all(isinstance(code, int) for code in entry["value"]) + + +def test_card_spec_is_not_shared_between_responses(tmp_path: Path) -> None: + first = _products_v5(tmp_path, [_DEVICE]) + first["categoryDetailList"][0]["category"]["cardSpec"]["state"]["value"].clear() + + second = _products_v5(tmp_path, [_DEVICE]) + + assert second["categoryDetailList"][0]["category"]["cardSpec"]["state"]["value"] + + +def test_unknown_category_has_no_card_spec(tmp_path: Path) -> None: + device = dict(_DEVICE, category="other.category") + + data = _products_v5(tmp_path, [device]) + + category = data["categoryDetailList"][0]["category"] + assert category["displayName"] == "other.category" + assert "cardSpec" not in category + assert "cardspec" not in category From 657d95aa6eab29722a1d7c9489d1f2599459a1b2 Mon Sep 17 00:00:00 2001 From: Immanuel Date: Sun, 22 Nov 2026 07:22:26 +0100 Subject: [PATCH 2/4] feat(api): send cardspec and scene_2.0 tag in the cloud's format Follow the EU cloud's /api/v5/product answer: - category "cardspec" as a JSON string with the spec in {"data": ...} (decoded by the app as CardSpecV2Data); no extra "cardSpec" dict - vacuum spec: add offpeak (dps 133), cloud wording for states 6, 9, 15, 26 and offline code 1 - scene_2.0 tag with requirePlugin true, pluginLevel 3000 - tests check the string format, the labels and a non-vacuum category Co-Authored-By: Claude Opus 5.5 --- .../https_server/routes/api/card_spec.py | 42 +++++++---- .../routes/api/product_service.py | 14 ++-- tests/test_product_response.py | 74 +++++++++++++++---- 3 files changed, 93 insertions(+), 37 deletions(-) diff --git a/src/roborock_local_server/bundled_backend/https_server/routes/api/card_spec.py b/src/roborock_local_server/bundled_backend/https_server/routes/api/card_spec.py index 98c16f9e..9df53a8c 100644 --- a/src/roborock_local_server/bundled_backend/https_server/routes/api/card_spec.py +++ b/src/roborock_local_server/bundled_backend/https_server/routes/api/card_spec.py @@ -1,18 +1,22 @@ -"""Home card specs (CardSpecV2) per product category. +"""Home card specs per product category. The Android app only shows the scene quick-start tiles of a device when its category carries a card spec (RRDeviceBeanV2.supportScene() returns false when -CategoryEntity.cardSpec is null). CardSpecV2 holds four data points directly -as fields - state, extra, battery, offline - each {"dps", "desc", "value"}. -Note that the template bundled with the app wraps these in {"data": {...}}; -the API field holds the inner object. +CategoryEntity.cardSpec is null). The app reads the JSON field ``cardspec`` of +the category as a string and decodes it as CardSpecV2Data, i.e. the spec +wrapped in ``{"data": {...}}``. The Roborock cloud sends it the same way. -Labels are English only. The app's bundled template carries ~30 languages. +The vacuum spec follows the cloud's /api/v5/product answer (EU, Nov 2026) and +the template bundled with the app (assets/cardSpec/robot.vacuum.cleaner.json). +The state and offline codes that only the bundled template has are kept. + +Labels are English only. The cloud and the bundled template carry more than +20 languages. """ from __future__ import annotations -import copy +import json from typing import Any @@ -28,19 +32,19 @@ def _state(label: str, *codes: int) -> dict[str, Any]: _state("Sleeping", 2), _state("Ready", 3), _state("Cleaning", 5, 11, 17, 18, 102, 103, 104), - _state("Return to the dock", 6), + _state("Returning to Dock", 6), _state("Remote Control", 7, 39), _state("Charging", 8), - _state("Charging error", 9), + _state("Charging Error", 9), _state("Pause", 10), _state("Error", 12), _state("Washing the mop", 13), _state("Updating", 14), - _state("Return to the dock", 15), + _state("Returning to Dock", 15), _state("Pin n Go", 16), _state("Emptying", 22), _state("Washing the mop", 23), - _state("Return to the dock", 26), + _state("Going to wash the mop", 26), _state("In call", 28), _state("Mapping", 29), _state("On cruise", 32), @@ -59,12 +63,15 @@ def _state(label: str, *codes: int) -> dict[str, Any]: "dps": 135, "desc": {"en": "Offline State"}, "value": [ - _state("Manual Shutdown", 1), + _state("Powered Off Manually", 1), + # The cloud lists only 34, 51 and 103; the app's bundled template + # also maps 2, 3 and 4 to these labels. _state("Sleep & Powered Off", 2, 34), _state("Low Battery & Powered Off", 3, 51), _state("Updating & Restarting", 4, 103), ], }, + "offpeak": {"dps": 133}, } CATEGORY_CARD_SPECS: dict[str, dict[str, Any]] = { @@ -72,6 +79,13 @@ def _state(label: str, *codes: int) -> dict[str, Any]: } -def card_spec_for_category(category_name: str) -> dict[str, Any] | None: +def card_spec_for_category(category_name: str) -> str | None: + """Return the category's ``cardspec`` value as the app expects it. + + That is a JSON string holding ``{"data": }``, or None when the + category has no known spec. + """ spec = CATEGORY_CARD_SPECS.get(category_name) - return copy.deepcopy(spec) if spec is not None else None + if spec is None: + return None + return json.dumps({"data": spec}, ensure_ascii=False, separators=(",", ":")) diff --git a/src/roborock_local_server/bundled_backend/https_server/routes/api/product_service.py b/src/roborock_local_server/bundled_backend/https_server/routes/api/product_service.py index e3be50ab..bc3573e9 100644 --- a/src/roborock_local_server/bundled_backend/https_server/routes/api/product_service.py +++ b/src/roborock_local_server/bundled_backend/https_server/routes/api/product_service.py @@ -35,11 +35,9 @@ def build_product_response(ctx: ServerContext) -> dict[str, Any]: } card_spec = card_spec_for_category(category_name) if card_spec is not None: - # Required for the scene tiles. CategoryEntity declares both - # spellings; which one is the JSON name could not be decided - # from the bytecode, so both are sent. + # Required for the scene tiles. Like the cloud, a JSON string + # with the spec wrapped in {"data": ...}. category_entry["cardspec"] = card_spec - category_entry["cardSpec"] = card_spec categories[category_name] = { "category": category_entry, "productList": [], @@ -70,13 +68,15 @@ def build_product_response(ctx: ServerContext) -> dict[str, Any]: "agreements": [], # ProductEntity.sceneProduct() looks up the "scene_2.0" tag; without # it the scene tiles stay hidden. The app builds productTagsMap from - # this list itself. + # this list itself. Values as sent by the cloud: forceShow gates the + # tiles, requirePlugin/pluginLevel are only read when a scene entry + # opens the device plugin. "productTags": [ { "name": "scene_2.0", + "requirePlugin": True, + "pluginLevel": 3000, "forceShow": True, - "pluginLevel": 0, - "requirePlugin": False, } ], } diff --git a/tests/test_product_response.py b/tests/test_product_response.py index d621749a..482671d2 100644 --- a/tests/test_product_response.py +++ b/tests/test_product_response.py @@ -143,6 +143,10 @@ def test_string_product_id_uses_cloud_numeric_id_by_model(tmp_path: Path) -> Non assert product["rriotid"] == "30uADinyLKa3Qpga60B1Ke" +def _labels(data_point: dict) -> dict[int, str]: + return {code: entry["desc"]["en"] for entry in data_point["value"] for code in entry["value"]} + + def test_product_entry_enables_scene_tiles(tmp_path: Path) -> None: data = _products_v5(tmp_path, [_DEVICE]) @@ -150,31 +154,69 @@ def test_product_entry_enables_scene_tiles(tmp_path: Path) -> None: [product] = category_detail["productList"] category = category_detail["category"] - # ProductEntity.sceneProduct() looks up exactly this tag. - assert {"name": "scene_2.0", "forceShow": True, "pluginLevel": 0, "requirePlugin": False} in product[ + # ProductEntity.sceneProduct() looks up exactly this tag; values as the cloud sends them. + assert {"name": "scene_2.0", "requirePlugin": True, "pluginLevel": 3000, "forceShow": True} in product[ "productTags" ] - # CardSpecV2 holds the four data points directly, without a "data" wrapper. - for key in ("cardspec", "cardSpec"): - card_spec = category[key] - assert set(card_spec) == {"state", "extra", "battery", "offline"} - assert card_spec["state"]["dps"] == 121 - assert card_spec["battery"]["dps"] == 122 - assert card_spec["extra"]["dps"] == 128 - assert card_spec["offline"]["dps"] == 135 - for entry in card_spec["state"]["value"]: + # Like the cloud: lower-case "cardspec" on the category, a JSON string + # holding the spec in a "data" wrapper (decoded by the app as CardSpecV2Data). + assert "cardSpec" not in category + assert isinstance(category["cardspec"], str) + wrapper = json.loads(category["cardspec"]) + assert set(wrapper) == {"data"} + card_spec = wrapper["data"] + assert set(card_spec) == {"state", "extra", "battery", "offline", "offpeak"} + assert card_spec["state"]["dps"] == 121 + assert card_spec["battery"] == {"dps": 122} + assert card_spec["extra"] == {"dps": 128} + assert card_spec["offline"]["dps"] == 135 + assert card_spec["offpeak"] == {"dps": 133} + for data_point in (card_spec["state"], card_spec["offline"]): + for entry in data_point["value"]: assert set(entry) == {"desc", "value"} assert entry["desc"]["en"] assert all(isinstance(code, int) for code in entry["value"]) -def test_card_spec_is_not_shared_between_responses(tmp_path: Path) -> None: - first = _products_v5(tmp_path, [_DEVICE]) - first["categoryDetailList"][0]["category"]["cardSpec"]["state"]["value"].clear() +def test_vacuum_card_spec_matches_cloud_labels(tmp_path: Path) -> None: + data = _products_v5(tmp_path, [_DEVICE]) + + card_spec = json.loads(data["categoryDetailList"][0]["category"]["cardspec"])["data"] + states = _labels(card_spec["state"]) + offline = _labels(card_spec["offline"]) + + # Wording of the cloud's EU /api/v5/product answer (Nov 2026). + assert states[6] == "Returning to Dock" + assert states[15] == "Returning to Dock" + assert states[9] == "Charging Error" + assert states[26] == "Going to wash the mop" + assert offline[1] == "Powered Off Manually" + # Every state code of the cloud is mapped, plus the extra ones of the + # template bundled with the app. + cloud_codes = {2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 22, 23, 26, 28, 29, 32} + extra_codes = {13, 33, 34, 36, 37, 38, 39, 40, 101, 102, 103, 104, 108} + assert cloud_codes <= set(states) + assert set(states) == cloud_codes | extra_codes + assert {1, 34, 51, 103} <= set(offline) + + +def test_card_spec_only_on_known_categories(tmp_path: Path) -> None: + other = dict( + _DEVICE, + duid="device-b", + name="Other", + model="roborock.other.b1", + product_id="iot-product-b", + category="other.category", + ) - second = _products_v5(tmp_path, [_DEVICE]) + data = _products_v5(tmp_path, [_DEVICE, other]) - assert second["categoryDetailList"][0]["category"]["cardSpec"]["state"]["value"] + categories = {entry["category"]["code"]: entry["category"] for entry in data["categoryDetailList"]} + assert set(categories) == {"robot.vacuum.cleaner", "other.category"} + assert isinstance(categories["robot.vacuum.cleaner"]["cardspec"], str) + assert "cardspec" not in categories["other.category"] + assert "cardSpec" not in categories["other.category"] def test_unknown_category_has_no_card_spec(tmp_path: Path) -> None: From b94aab17a9eb322f39d930c34242925a72707181 Mon Sep 17 00:00:00 2001 From: Immanuel Date: Sun, 22 Nov 2026 19:19:56 +0100 Subject: [PATCH 3/4] feat(api): prefer the cloud snapshot's productTags and cardspec Since #224 the snapshot holds the cloud's own /api/v5/product answer. Use it when present: - productTags per product (by model) are passed through as the cloud sends them, including an empty list (no scene_2.0 then) - the category cardspec is taken from the cloud (all 22 languages); an empty string counts as missing The built-in values stay as the fallback when there is no snapshot or no entry. The fallback scene_2.0 tag (requirePlugin, pluginLevel 3000, forceShow) is now only added to robot.vacuum.cleaner: the tiles also need a category cardspec, which we only have for vacuums, and the tag values were only seen on a vacuum. Mowers, washers etc. get the tag only when the cloud sends it. Tests: snapshot values and languages win, a listed model without a scene tag stays without one, missing entry/empty cardspec falls back, non-vacuum categories with and without snapshot. Co-Authored-By: Claude Opus 5.5 --- .../https_server/routes/api/card_spec.py | 5 +- .../routes/api/product_service.py | 84 +++++++++-- tests/test_product_response.py | 131 ++++++++++++++++++ 3 files changed, 205 insertions(+), 15 deletions(-) diff --git a/src/roborock_local_server/bundled_backend/https_server/routes/api/card_spec.py b/src/roborock_local_server/bundled_backend/https_server/routes/api/card_spec.py index 9df53a8c..25018bb1 100644 --- a/src/roborock_local_server/bundled_backend/https_server/routes/api/card_spec.py +++ b/src/roborock_local_server/bundled_backend/https_server/routes/api/card_spec.py @@ -10,8 +10,9 @@ the template bundled with the app (assets/cardSpec/robot.vacuum.cleaner.json). The state and offline codes that only the bundled template has are kept. -Labels are English only. The cloud and the bundled template carry more than -20 languages. +This spec is only the fallback: when the cloud snapshot taken at import holds +the category's own ``cardspec`` (all 22 languages), product_service sends that +instead. The labels here are English only. """ from __future__ import annotations diff --git a/src/roborock_local_server/bundled_backend/https_server/routes/api/product_service.py b/src/roborock_local_server/bundled_backend/https_server/routes/api/product_service.py index bc3573e9..241e98e8 100644 --- a/src/roborock_local_server/bundled_backend/https_server/routes/api/product_service.py +++ b/src/roborock_local_server/bundled_backend/https_server/routes/api/product_service.py @@ -1,5 +1,6 @@ from __future__ import annotations +import json from typing import Any from shared.constants import MODEL_PRODUCT_ID_OVERRIDES @@ -11,12 +12,74 @@ from ..user.homes.service import home_payload from .card_spec import card_spec_for_category +# Fallback for products the cloud snapshot does not list. Values as the cloud +# sends them for a vacuum (a307): forceShow gates the scene tiles, +# requirePlugin/pluginLevel are only read when a scene entry opens the device +# plugin. +_FALLBACK_SCENE_TAG: dict[str, Any] = { + "name": "scene_2.0", + "requirePlugin": True, + "pluginLevel": 3000, + "forceShow": True, +} +# Only vacuums get the fallback tag: the tiles also need the category card +# spec, which we only have for vacuums, and the tag values were only seen on +# a vacuum. Mowers, washers etc. get it only when the cloud sends it. +_FALLBACK_SCENE_TAG_CATEGORIES = frozenset({"robot.vacuum.cleaner"}) + + +def _cloud_card_spec(value: Any) -> str | None: + """The category's cloud ``cardspec`` as the app reads it, or None if empty.""" + if isinstance(value, str): + return value if value.strip() else None + if isinstance(value, dict) and value: + wrapped = value if set(value) == {"data"} else {"data": value} + return json.dumps(wrapped, ensure_ascii=False, separators=(",", ":")) + return None + + +def _cloud_product_details( + cloud_products: Any, +) -> tuple[dict[str, list[dict[str, Any]]], dict[str, str]]: + """Map model -> productTags and category code -> cardspec from a cloud + /api/v5/product payload (the snapshot taken at import).""" + tags_by_model: dict[str, list[dict[str, Any]]] = {} + card_specs: dict[str, str] = {} + category_details = cloud_products.get("categoryDetailList") if isinstance(cloud_products, dict) else None + for category_detail in category_details or []: + if not isinstance(category_detail, dict): + continue + category = category_detail.get("category") + if isinstance(category, dict): + code = str(category.get("code") or "").strip() + card_spec = _cloud_card_spec(category.get("cardspec")) + if code and card_spec is not None: + card_specs.setdefault(code, card_spec) + for product in category_detail.get("productList") or []: + if not isinstance(product, dict): + continue + model = str(product.get("model") or "").strip().lower() + tags = product.get("productTags") + if model and isinstance(tags, list): + tags_by_model[model] = [dict(tag) for tag in tags if isinstance(tag, dict)] + return tags_by_model, card_specs + + +def _fallback_product_tags(category_name: str) -> list[dict[str, Any]]: + if category_name in _FALLBACK_SCENE_TAG_CATEGORIES: + return [dict(_FALLBACK_SCENE_TAG)] + return [] + def build_product_response(ctx: ServerContext) -> dict[str, Any]: home_data = home_payload(ctx) products_value = home_data.get("products") products = products_value if isinstance(products_value, list) else [] - cloud_product_ids = model_product_ids(snapshot_plugin_catalog_data(ctx, "product")) + cloud_products = snapshot_plugin_catalog_data(ctx, "product") + cloud_product_ids = model_product_ids(cloud_products) + # The cloud's own productTags and category cardspec (22 languages) win; + # the built-in values are only a fallback. + cloud_product_tags, cloud_card_specs = _cloud_product_details(cloud_products) categories: dict[str, dict[str, Any]] = {} for product in products: if not isinstance(product, dict): @@ -33,7 +96,7 @@ def build_product_response(ctx: ServerContext) -> dict[str, Any]: "displayName": category_name, "iconUrl": "", } - card_spec = card_spec_for_category(category_name) + card_spec = cloud_card_specs.get(category_name) or card_spec_for_category(category_name) if card_spec is not None: # Required for the scene tiles. Like the cloud, a JSON string # with the spec wrapped in {"data": ...}. @@ -68,17 +131,12 @@ def build_product_response(ctx: ServerContext) -> dict[str, Any]: "agreements": [], # ProductEntity.sceneProduct() looks up the "scene_2.0" tag; without # it the scene tiles stay hidden. The app builds productTagsMap from - # this list itself. Values as sent by the cloud: forceShow gates the - # tiles, requirePlugin/pluginLevel are only read when a scene entry - # opens the device plugin. - "productTags": [ - { - "name": "scene_2.0", - "requirePlugin": True, - "pluginLevel": 3000, - "forceShow": True, - } - ], + # this list itself. + "productTags": ( + cloud_product_tags[model_key] + if model_key in cloud_product_tags + else _fallback_product_tags(category_name) + ), } icon_url = product.get("iconUrl") if isinstance(icon_url, str) and icon_url: diff --git a/tests/test_product_response.py b/tests/test_product_response.py index 482671d2..6bb6d51b 100644 --- a/tests/test_product_response.py +++ b/tests/test_product_response.py @@ -148,6 +148,7 @@ def _labels(data_point: dict) -> dict[int, str]: def test_product_entry_enables_scene_tiles(tmp_path: Path) -> None: + # No cloud snapshot: the built-in fallback values. data = _products_v5(tmp_path, [_DEVICE]) category_detail = data["categoryDetailList"][0] @@ -228,3 +229,133 @@ def test_unknown_category_has_no_card_spec(tmp_path: Path) -> None: assert category["displayName"] == "other.category" assert "cardSpec" not in category assert "cardspec" not in category + + +def _write_cloud_product_snapshot(tmp_path: Path, category_details: list[dict]) -> None: + snapshot = {"web_api_cache": {"plugin_catalogs": {"product": {"data": {"categoryDetailList": category_details}}}}} + (tmp_path / "web_api_inventory_full_snapshot.json").write_text(json.dumps(snapshot), encoding="utf-8") + + +# Shape of the cloud's /api/v5/product answer: cardspec is a JSON string with +# the spec in {"data": ...}, the labels in many languages. +_CLOUD_VACUUM_SPEC = { + "state": { + "dps": 121, + "desc": {"en": "State", "de": "Status", "fr": "État"}, + "value": [{"desc": {"en": "Charging", "de": "Wird geladen", "fr": "En charge"}, "value": [8]}], + }, + "battery": {"dps": 122}, +} +_CLOUD_VACUUM_CARD_SPEC = json.dumps({"data": _CLOUD_VACUUM_SPEC}, ensure_ascii=False) +_CLOUD_SCENE_TAG = {"name": "scene_2.0", "requirePlugin": False, "pluginLevel": 1234, "forceShow": True} +_CLOUD_OTHER_TAG = {"name": "other_tag", "requirePlugin": False, "pluginLevel": 0, "forceShow": False} + + +def test_cloud_snapshot_product_tags_and_card_spec_win(tmp_path: Path) -> None: + _write_cloud_product_snapshot( + tmp_path, + [ + { + "category": {"id": 7, "code": "robot.vacuum.cleaner", "cardspec": _CLOUD_VACUUM_CARD_SPEC}, + "productList": [ + {"id": 101, "model": "roborock.vacuum.a15", "productTags": [_CLOUD_SCENE_TAG, _CLOUD_OTHER_TAG]} + ], + } + ], + ) + + data = _products_v5(tmp_path, [_DEVICE]) + + category_detail = data["categoryDetailList"][0] + [product] = category_detail["productList"] + # The cloud's tags are passed through unchanged, not the built-in values. + assert product["productTags"] == [_CLOUD_SCENE_TAG, _CLOUD_OTHER_TAG] + # The cloud's card spec string is passed through as is, all languages included. + card_spec = category_detail["category"]["cardspec"] + assert card_spec == _CLOUD_VACUUM_CARD_SPEC + charging = json.loads(card_spec)["data"]["state"]["value"][0]["desc"] + assert charging == {"en": "Charging", "de": "Wird geladen", "fr": "En charge"} + + +def test_cloud_snapshot_without_scene_tag_is_respected(tmp_path: Path) -> None: + # The cloud lists the model but sends no scene_2.0 tag: none is added. + _write_cloud_product_snapshot( + tmp_path, + [ + { + "category": {"id": 7, "code": "robot.vacuum.cleaner", "cardspec": _CLOUD_VACUUM_CARD_SPEC}, + "productList": [{"id": 101, "model": "roborock.vacuum.a15", "productTags": []}], + } + ], + ) + + data = _products_v5(tmp_path, [_DEVICE]) + + [product] = data["categoryDetailList"][0]["productList"] + assert product["productTags"] == [] + + +def test_model_missing_from_cloud_snapshot_uses_fallback(tmp_path: Path) -> None: + # Snapshot without an entry for this model and with an empty category + # cardspec (some bundles default it to ''): built-in values as fallback. + _write_cloud_product_snapshot( + tmp_path, + [ + { + "category": {"id": 7, "code": "robot.vacuum.cleaner", "cardspec": ""}, + "productList": [{"id": 199, "model": "roborock.vacuum.a226", "productTags": [_CLOUD_OTHER_TAG]}], + } + ], + ) + + data = _products_v5(tmp_path, [_DEVICE]) + + category_detail = data["categoryDetailList"][0] + [product] = category_detail["productList"] + assert product["productTags"] == [ + {"name": "scene_2.0", "requirePlugin": True, "pluginLevel": 3000, "forceShow": True} + ] + card_spec = json.loads(category_detail["category"]["cardspec"])["data"] + assert card_spec["state"]["dps"] == 121 + assert _labels(card_spec["state"])[8] == "Charging" + + +_MOWER = dict( + _DEVICE, + duid="device-m", + name="Mower", + model="roborock.mower.m1", + product_id="iot-product-m", + category="roborock.mower", +) + + +def test_non_vacuum_category_gets_no_fallback_scene_tag(tmp_path: Path) -> None: + data = _products_v5(tmp_path, [_DEVICE, _MOWER]) + + by_category = {entry["category"]["code"]: entry for entry in data["categoryDetailList"]} + [vacuum] = by_category["robot.vacuum.cleaner"]["productList"] + [mower] = by_category["roborock.mower"]["productList"] + assert [tag["name"] for tag in vacuum["productTags"]] == ["scene_2.0"] + assert mower["productTags"] == [] + assert "cardspec" not in by_category["roborock.mower"]["category"] + + +def test_non_vacuum_category_takes_scene_tag_and_card_spec_from_cloud(tmp_path: Path) -> None: + mower_spec = json.dumps({"data": {"state": {"dps": 201, "desc": {"en": "State"}, "value": []}}}) + _write_cloud_product_snapshot( + tmp_path, + [ + { + "category": {"id": 9, "code": "roborock.mower", "cardspec": mower_spec}, + "productList": [{"id": 301, "model": "roborock.mower.m1", "productTags": [_CLOUD_SCENE_TAG]}], + } + ], + ) + + data = _products_v5(tmp_path, [_MOWER]) + + category_detail = data["categoryDetailList"][0] + [mower] = category_detail["productList"] + assert mower["productTags"] == [_CLOUD_SCENE_TAG] + assert category_detail["category"]["cardspec"] == mower_spec From c82660fd6ab58c3ca29147b61bf38d892fd59b76 Mon Sep 17 00:00:00 2001 From: Immanuel Date: Sun, 22 Nov 2026 19:30:22 +0100 Subject: [PATCH 4/4] test(api): compare the fallback vacuum cardspec with the cloud's Add tests/fixtures/cloud_vacuum_cardspec_eu.json: the decoded cardspec of the robot.vacuum.cleaner category from the EU cloud's /api/v5/product answer (2026-11-21, provided by @Hoeze in #208). The fallback spec is checked against it: same data points and dps, the cloud's English label for every code the cloud maps. The only extras are the state and offline codes of the app's bundled template, listed and explained in the test. A second test passes the fixture through the snapshot and checks all 22 languages arrive. Replaces the hand-written label checks. Co-Authored-By: Claude Opus 5.5 --- tests/fixtures/cloud_vacuum_cardspec_eu.json | 672 +++++++++++++++++++ tests/test_product_response.py | 105 ++- 2 files changed, 759 insertions(+), 18 deletions(-) create mode 100644 tests/fixtures/cloud_vacuum_cardspec_eu.json diff --git a/tests/fixtures/cloud_vacuum_cardspec_eu.json b/tests/fixtures/cloud_vacuum_cardspec_eu.json new file mode 100644 index 00000000..ea9c5711 --- /dev/null +++ b/tests/fixtures/cloud_vacuum_cardspec_eu.json @@ -0,0 +1,672 @@ +{ + "data": { + "extra": { + "dps": 128 + }, + "state": { + "dps": 121, + "desc": { + "en": "State", + "zh": "状态" + }, + "value": [ + { + "desc": { + "ar": "نوم", + "de": "Im Ruhezustand", + "en": "Sleeping", + "es": "En suspenso", + "fr": "En veille", + "he": "במצב שינה", + "id": "Tidur", + "it": "In standby", + "ja": "スリープ中", + "ko": "절전 중", + "ms": "Tidur", + "pl": "Uśpienie", + "pt": "Em Suspensão", + "ro": "Repaus", + "ru": "Спящий режим", + "th": "กำลังอยู่ในโหมดสลีป", + "tr": "Uyuyor", + "uk": "Сон", + "vi": "Đang ngủ", + "es-LA": "Suspendido", + "zh-Hans": "休眠", + "zh-Hant": "休眠" + }, + "value": [ + 2 + ] + }, + { + "desc": { + "ar": "استعداد", + "de": "Bereit", + "en": "Ready", + "es": "Listo", + "fr": "Prêt", + "he": "מוכן", + "id": "Siap", + "it": "Pronto", + "ja": "準備完了", + "ko": "준비 완료", + "ms": "Sedia", + "pl": "Gotowy", + "pt": "Pronto", + "ro": "Pregătit", + "ru": "Готов", + "th": "พร้อมทำงาน", + "tr": "Hazır", + "uk": "Готовий", + "vi": "Sẵn sàng", + "es-LA": "Listo", + "zh-Hans": "等待指令", + "zh-Hant": "等待指令" + }, + "value": [ + 3 + ] + }, + { + "desc": { + "ar": "تنظيف", + "de": "Gerät reinigt", + "en": "Cleaning", + "es": "Limpiando", + "fr": "Nettoyage en cours", + "he": "ניקוי", + "id": "Membersihkan", + "it": "Pulizia in corso", + "ja": "掃除中", + "ko": "청소", + "ms": "Membersihkan", + "pl": "Sprzątanie", + "pt": "A Limpar", + "ro": "Curățare", + "ru": "Уборка", + "th": "กำลังทำความสะอาด", + "tr": "Temizliyor", + "uk": "Прибирання", + "vi": "Đang làm sạch", + "es-LA": "Limpiando", + "zh-Hans": "清洁中", + "zh-Hant": "清掃中" + }, + "value": [ + 5, + 11, + 17, + 18 + ] + }, + { + "desc": { + "ar": "العودة إلى قاعدة الشحن", + "de": "Rückfahrt zur Ladestation", + "en": "Returning to Dock", + "es": "Volviendo a la estación", + "fr": "Retour à la station", + "he": "עגינה", + "id": "Penambatan", + "it": "Torna in carica", + "ja": "ドッキング", + "ko": "충전기로 돌아갑니다", + "ms": "Kembali ke Dok", + "pl": "Wracając do doku", + "pt": "A Regressar à Base", + "ro": "Andocare", + "ru": "Возврат к док-станции", + "th": "กำลังอยู่บนแท่นวาง", + "tr": "Şarj İstasyonuna Dönüyor", + "uk": "Заряджання через док-станцію", + "vi": "Đang sạc", + "es-LA": "Volviendo a la base", + "zh-Hans": "回充中", + "zh-Hant": "回充中" + }, + "value": [ + 6 + ] + }, + { + "desc": { + "ar": "التحكم عن بُعد", + "de": "Fernsteuerung", + "en": "Remote Control", + "es": "Control remoto", + "fr": "Contrôle à distance", + "he": "שליטה מרחוק", + "id": "Kontrol jarak jauh", + "it": "Comando a distanza", + "ja": "リモート操作中", + "ko": "원격 제어", + "ms": "Kawalan Jauh", + "pl": "Zdalne sterowanie", + "pt": "Controlo Remoto", + "ro": "Telecomandă", + "ru": "Дистанционное управление", + "th": "รีโมทคอนโทรล", + "tr": "Uzaktan Kumanda", + "uk": "Дистанційне керування", + "vi": "Điều khiển từ xa", + "es-LA": "Control remoto", + "zh-Hans": "遥控中", + "zh-Hant": "正在遙控" + }, + "value": [ + 7 + ] + }, + { + "desc": { + "ar": "الشحن", + "de": "Aufladen", + "en": "Charging", + "es": "Cargando", + "fr": "En charge", + "he": "טעינה", + "id": "Mengisi daya", + "it": "Ricarica", + "ja": "充電します", + "ko": "충전 중", + "ms": "Mengecas", + "pl": "Ładowanie", + "pt": "A Carregar", + "ro": "Încărcare", + "ru": "Зарядка", + "th": "กำลังชาร์จ", + "tr": "Şarj Ediliyor", + "uk": "Заряджання", + "vi": "Đang sạc", + "es-LA": "Cargando", + "zh-Hans": "充电中", + "zh-Hant": "充電中" + }, + "value": [ + 8 + ] + }, + { + "desc": { + "ar": "خطأ في الشحن", + "de": "Ladefehler", + "en": "Charging Error", + "es": "Error de carga", + "fr": "Erreur de chargement", + "he": "שגיאת טעינה", + "id": "Kesalahan pengisian", + "it": "Errore di ricarica", + "ja": "充電エラー", + "ko": "충전 오류", + "ms": "Ralat Pengecasan", + "pl": "Błąd ładowania", + "pt": "Erro de Carregamento", + "ro": "Eroare de încărcare", + "ru": "Сбой зарядки", + "th": "เกิดข้อผิดพลาดขณะชาร์จ", + "tr": "Şarj Hatası", + "uk": "Помилка заряджання", + "vi": "Lỗi sạc", + "es-LA": "Error de carga", + "zh-Hans": "充电异常", + "zh-Hant": "充電錯誤" + }, + "value": [ + 9 + ] + }, + { + "desc": { + "ar": "إيقاف مؤقت", + "de": "Pause", + "en": "Pause", + "es": "Pausar", + "fr": "Pause", + "he": "השהיה", + "id": "Jeda", + "it": "Pausa", + "ja": "一時停止中", + "ko": "청소 멈춤", + "ms": "Jeda", + "pl": "Pauza", + "pt": "Pausa", + "ro": "Pauză", + "ru": "Пауза", + "th": "หยุดชั่วคราว", + "tr": "Durakladı", + "uk": "Пауза", + "vi": "Tạm dừng", + "es-LA": "Pausa", + "zh-Hans": "暂停", + "zh-Hant": "暫停" + }, + "value": [ + 10 + ] + }, + { + "desc": { + "ar": "خطأ", + "de": "Fehler", + "en": "Error", + "es": "Error", + "fr": "Erreur", + "he": "שגיאה", + "id": "Kesalahan", + "it": "Errore", + "ja": "エラー発生中", + "ko": "오류", + "ms": "Ralat", + "pl": "Błąd", + "pt": "Erro", + "ro": "Eroare", + "ru": "Ошибка", + "th": "เกิดข้อผิดพลาด", + "tr": "Hata", + "uk": "Помилка", + "vi": "Lỗi", + "es-LA": "Error", + "zh-Hans": "报错", + "zh-Hant": "通報錯誤" + }, + "value": [ + 12 + ] + }, + { + "desc": { + "ar": "تحديث", + "de": "Aktualisierung", + "en": "Updating", + "es": "Actualizando", + "fr": "Mise à jour en cours", + "he": "מעדכן", + "id": "Memperbarui", + "it": "Aggiornamento", + "ja": "アップデート中", + "ko": "업데이트 중", + "ms": "Mengemas kini", + "pl": "Aktualizacja", + "pt": "A Atualizar", + "ro": "Se actualizează", + "ru": "Обновление", + "th": "กำลังอัปเดต", + "tr": "Güncelleniyor", + "uk": "Оновлення", + "vi": "Đang cập nhật", + "es-LA": "Actualizando", + "zh-Hans": "升级中", + "zh-Hant": "升級中" + }, + "value": [ + 14 + ] + }, + { + "desc": { + "ar": "العودة إلى قاعدة الشحن", + "de": "Rückfahrt zur Ladestation", + "en": "Returning to Dock", + "es": "Volviendo a la estación", + "fr": "Retour à la station", + "he": "עגינה", + "id": "Penambatan", + "it": "Torna in carica", + "ja": "ドッキング", + "ko": "충전기로 돌아갑니다", + "ms": "Kembali ke Dok", + "pl": "Wracając do doku", + "pt": "A Regressar à Base", + "ro": "Andocare", + "ru": "Возврат к док-станции", + "th": "กำลังอยู่บนแท่นวาง", + "tr": "Şarj İstasyonuna Dönüyor", + "uk": "Заряджання через док-станцію", + "vi": "Đang sạc", + "es-LA": "Volviendo a la base", + "zh-Hans": "回充中", + "zh-Hant": "回充中" + }, + "value": [ + 15 + ] + }, + { + "desc": { + "ar": "تحديد وتحرك", + "de": "Pin-and-Go", + "en": "Pin n Go", + "es": "Limpieza de puntos de destino", + "fr": "Épingler et y aller", + "he": "ציין מקום וצא", + "id": "Sematkan & Lanjutkan", + "it": "Contrassegna e via", + "ja": "目的地指定", + "ko": "청소 목표지점 설정", + "ms": "Pin dan Gerak", + "pl": "Wskaż miejsce", + "pt": "Pin n Go", + "ro": "Pin n Go (Fixare și Plecare)", + "ru": "Точки маршрута", + "th": "ตรงจุดไหน", + "tr": "Pin n Go", + "uk": "Прибирання з відзначеної точки", + "vi": "Ghim lại và bắt đầu", + "es-LA": "Pin n Go", + "zh-Hans": "指哪到哪", + "zh-Hant": "指哪到哪" + }, + "value": [ + 16 + ] + }, + { + "desc": { + "ar": "تفريغ", + "de": "Entleeren", + "en": "Emptying", + "es": "Vaciando", + "fr": "Vidage", + "he": "אוסף אבק", + "id": "Mengosongkan", + "it": "Svuotando", + "ja": "ほこりを集める", + "ko": "먼지통 비우기", + "ms": "Mengosongkan Tong Sampah", + "pl": "Zbieranie kurzu", + "pt": "A Esvaziar", + "ro": "Golire", + "ru": "Уборка", + "th": "เก็บฝุ่น", + "tr": "Boşaltılıyor", + "uk": "Збір пилу", + "vi": "Thu gom bụi", + "es-LA": "Vaciando", + "zh-Hans": "集尘中", + "zh-Hant": "集塵中" + }, + "value": [ + 22 + ] + }, + { + "desc": { + "ar": "غسيل الممسحة", + "de": "Wischtuch reinigen", + "en": "Washing the mop", + "es": "Lavado del paño en curso", + "fr": "Lavage de la serpillière", + "he": "שוטף את הסחבה", + "id": "Mencuci lap", + "it": "Lavaggio del panno", + "ja": "クロスの洗浄", + "ko": "천 세탁", + "ms": "Menbasuh kain", + "pl": "Pranie materiału", + "pt": "A lavar o pano", + "ro": "Spălare cârpă", + "ru": "Мытье тряпки", + "th": "กำลังซักผ้า", + "tr": "Bezi yıkama", + "uk": "Прання ганчірки", + "vi": "Giặt giẻ lau", + "es-LA": "Lavado del paño", + "zh-Hans": "拖布清洗中", + "zh-Hant": "洗抹布" + }, + "value": [ + 23 + ] + }, + { + "desc": { + "ar": "الانتقال إلى غسل الممسحة", + "de": "Rückspülung", + "en": "Going to wash the mop", + "es": "Yendo a lavar el paño", + "fr": "Aller laver la serpillière", + "he": "הולך לשטוף את המגב", + "id": "Pergi untuk mencuci pel", + "it": "Controlavaggio", + "ja": "逆洗", + "ko": "충전기로 돌아가서 천 세탁", + "ms": "Akan mencuci mop", + "pl": "Idę do mycia mopa", + "pt": "A ir lavar a mopa", + "ro": "Merg să spăl mopul", + "ru": "Обратная промывка", + "th": "กำลังกลับไปที่แท่นเพื่อซักผ้า", + "tr": "paspas yıkamak için gidiyor", + "uk": "Збирається мити швабру", + "vi": "Chuẩn bị giặt khăn lau", + "es-LA": "Yendo a lavar el paño", + "zh-Hans": "回洗中", + "zh-Hant": "回洗中" + }, + "value": [ + 26 + ] + }, + { + "desc": { + "ar": "التخطيط", + "de": "Wird kartiert", + "en": "Mapping", + "es": "Mapeando", + "fr": "Cartographie en cours", + "he": "מיפוי", + "id": "Pemetaan", + "it": "Mappatura in corso", + "ja": "マッピング", + "ko": "매핑 중", + "ms": "Pemetaan", + "pl": "Mapowanie", + "pt": "Mapeamento em curso", + "ro": "Cartografiere", + "ru": "Составление карты", + "th": "กำลังทำแผนที่", + "tr": "Harita Çıkarma", + "uk": "Створення карти", + "vi": "Vẽ bản đồ", + "es-LA": "Mapeando", + "zh-Hans": "建图中", + "zh-Hant": "地圖建立中" + }, + "value": [ + 29 + ] + }, + { + "desc": { + "ar": "قيد الاتصال", + "de": "Im Gespräch", + "en": "In call", + "es": "Llamada en curso", + "fr": "Appel en cours", + "he": "בשיחה", + "id": "Sedang melakukan panggilan", + "it": "Chiamata in corso", + "ja": "通話中", + "ko": "통화 중", + "ms": "Sedang memanggil", + "pl": "Trwa połączenie", + "pt": "Em chamada", + "ro": "În apel", + "ru": "В процессе вызова", + "th": "กำลังโทร", + "tr": "Aramada", + "uk": "Виклик триває", + "vi": "Đang gọi", + "es-LA": "Llamando", + "zh-Hans": "通话中", + "zh-Hant": "正在通話中…" + }, + "value": [ + 28 + ] + }, + { + "desc": { + "ar": "في رحلة", + "de": "Beim Umherfahren", + "en": "On cruise", + "es": "En recorrido", + "fr": "En patrouille", + "he": "מסייר", + "id": "Sedang menjelajah", + "it": "In viaggio", + "ja": "巡回中", + "ko": "주행 중", + "ms": "Hidupkan jelajah", + "pl": "W podróży", + "pt": "Em cruzeiro", + "ro": "În deplasare", + "ru": "Выполнятся осмотр", + "th": "กำลังตรวจตรา", + "tr": "Gezinmede", + "uk": "Робот переїжджає", + "vi": "Đang kiểm tra", + "es-LA": "En crucero", + "zh-Hans": "巡航中", + "zh-Hant": "巡航中" + }, + "value": [ + 32 + ] + } + ] + }, + "battery": { + "dps": 122 + }, + "offline": { + "dps": 135, + "desc": { + "en": "Offline State", + "zh": "离线状态" + }, + "value": [ + { + "desc": { + "ar": "تم إيقاف التشغيل يدويًا", + "de": "Manuell ausgeschaltet", + "en": "Powered Off Manually ", + "es": "Se apagó manualmente", + "fr": "Éteintmanuellement", + "he": "כובה ידנית", + "id": "Dimatikan Secara Manual", + "it": "Spento manualmente", + "ja": "手動で電源オフになりました", + "ko": "수동으로 전원 꺼짐", + "ms": "Dimatikan Secara Manual", + "pl": "Zasilanie wyłączone ręcznie", + "pt": "Desligado manualmente", + "ro": "Închidere manuală", + "ru": "Отключение вручную", + "th": "ปิดแบบแมนนวล", + "tr": "Elle Kapatıldı", + "uk": "Живлення вимкнено вручну", + "vi": "Tắt nguồn Thủ công", + "es-LA": "Se apagó manualmente", + "zh-Hans": "手动关机", + "zh-Hant": "手動關機" + }, + "value": [ + 1 + ] + }, + { + "desc": { + "ar": "وضع السكون وإيقاف التشغيل", + "de": "Schlafmodus & ausgeschaltet", + "en": "Sleep & Powered Off", + "es": "Suspensión y se apagó", + "fr": "En veille et éteint", + "he": "במצב שינה ומכובה", + "id": "Tidur & Dimatikan", + "it": "Sospensione e Spento", + "ja": "スリープ状態で、電源オフになりました", + "ko": "절전 모드로 전원 꺼짐", + "ms": "Tidur & Dimatikan", + "pl": "Uśpienie i zasilanie wyłączone", + "pt": "Suspensão e desligado", + "ro": "Hibernare și închidere", + "ru": "Спящий режим и отключение", + "th": "นอนหลับและปิดเครื่อง", + "tr": "Uyku Nedeniyle Kapatıldı", + "uk": "Перехід у режим сну, живлення вимкнено", + "vi": "Ngủ & Tắt nguồn", + "es-LA": "Suspendido y se apagó", + "zh-Hans": "休眠关机", + "zh-Hant": "休眠關機" + }, + "value": [ + 34 + ] + }, + { + "desc": { + "ar": "بطارية منخفضة وإيقاف التشغيل", + "de": "Niedriger Akkustand & ausgeschaltet", + "en": "Low Battery & Powered Off", + "es": "Batería baja y se apagó", + "fr": "Batterie faible et éteint", + "he": "סוללה חלשה ומכובה", + "id": "Daya Baterai Rendah & Dimatikan", + "it": "Batteria scarica e Spento", + "ja": "バッテリ残量の低下で、電源オフになりました", + "ko": "배터리 잔량 부족으로 전원 꺼짐", + "ms": "Bateri Lemah & Dimatikan", + "pl": "Niski poziom baterii i zasilanie wyłączone", + "pt": "Bateria fraca e desligado", + "ro": "Închidere în caz de baterie descărcată", + "ru": "Низкий заряд аккумулятора и отключение", + "th": "แบตเตอรี่ต่ำและปิดเครื่อง", + "tr": "Düşük Pil Nedeniyle Kapatıldı", + "uk": "Низький заряд акумулятора, живлення вимкнено", + "vi": "Pin yếu & Tắt nguồn", + "es-LA": "Baja batería y se apagó", + "zh-Hans": "低电量关机", + "zh-Hant": "低電量關機" + }, + "value": [ + 51 + ] + }, + { + "desc": { + "ar": "التحديث وإعادة التشغيل", + "de": "Aktualisierung & Neustart", + "en": "Updating & Restarting", + "es": "Actualización y reinicio en curso", + "fr": "Mise à jour et redémarrage", + "he": "מעדכן ומתחיל מחדש", + "id": "Memperbarui & Memulai ulang", + "it": "Aggiornamento e riavvio", + "ja": "アップデートおよび再起動中", + "ko": "업데이트 및 재시작 중...", + "ms": "Mengemas Kini dan Menghidupkan Semula", + "pl": "Aktualizowanie i ponowne uruchamianie", + "pt": "A atualizar e reiniciar", + "ro": "În curs de actualizare și de repornire", + "ru": "Обновление и перезапуск", + "th": "กำลังอัปเดตและรีสตาร์ท", + "tr": "Güncelleme ve Yeniden Başlatma", + "uk": "Виконується оновлення і повторний запуск", + "vi": "Cập nhật & Khởi động lại", + "es-LA": "Actualizando y reiniciando", + "zh-Hans": "升级重启中", + "zh-Hant": "升級重啟中" + }, + "value": [ + 103 + ] + } + ] + }, + "offpeak": { + "dps": 133 + } + } +} diff --git a/tests/test_product_response.py b/tests/test_product_response.py index 6bb6d51b..c2e11215 100644 --- a/tests/test_product_response.py +++ b/tests/test_product_response.py @@ -179,26 +179,95 @@ def test_product_entry_enables_scene_tiles(tmp_path: Path) -> None: assert all(isinstance(code, int) for code in entry["value"]) -def test_vacuum_card_spec_matches_cloud_labels(tmp_path: Path) -> None: +# Decoded cardspec of the robot.vacuum.cleaner category in the EU cloud's +# GET /api/v5/product answer, fetched 2026-11-21 by @Hoeze (account without +# devices; all 56 vacuum models share it). Posted in PR #208 and kept unchanged. +CLOUD_VACUUM_CARD_SPEC_EU = json.loads( + (Path(__file__).parent / "fixtures" / "cloud_vacuum_cardspec_eu.json").read_text(encoding="utf-8") +) + +# Deliberate differences of the built-in fallback from the cloud spec. The app's +# bundled template (assets/cardSpec/robot.vacuum.cleaner.json, 4.60.06) maps +# these extra codes; they only add labels for codes the cloud leaves unmapped. +_TEMPLATE_ONLY_STATE_LABELS = { + 13: "Washing the mop", + 33: "Reinstalling mop cloth mounts", + 34: "Detaching mop cloth mounts", + 36: "Demo Mode", + 37: "Demo Mode", + 38: "Housework in progress", + 39: "Remote Control", + 40: "Emergency Stop", + 101: "Positioning", + 102: "Cleaning", + 103: "Cleaning", + 104: "Cleaning", + 108: "Charge Pending", +} +# The template also maps the offline codes 2, 3, 4 to the labels of 34, 51, 103. +_TEMPLATE_ONLY_OFFLINE_LABELS = { + 2: "Sleep & Powered Off", + 3: "Low Battery & Powered Off", + 4: "Updating & Restarting", +} + + +def _en_labels(data_point: dict) -> dict[int, str]: + # The cloud's English label for offline code 1 has a trailing space + # ("Powered Off Manually "); the fallback drops it. + return {code: entry["desc"]["en"].strip() for entry in data_point["value"] for code in entry["value"]} + + +def test_fallback_vacuum_card_spec_matches_cloud_fixture(tmp_path: Path) -> None: + data = _products_v5(tmp_path, [_DEVICE]) + + ours = json.loads(data["categoryDetailList"][0]["category"]["cardspec"]) + cloud = CLOUD_VACUUM_CARD_SPEC_EU + assert set(ours) == set(cloud) == {"data"} + ours, cloud = ours["data"], cloud["data"] + + # Same data points with the same dps. + assert set(ours) == set(cloud) + for name in cloud: + assert ours[name]["dps"] == cloud[name]["dps"], name + for name in ("extra", "battery", "offpeak"): + assert ours[name] == cloud[name] + for name in ("state", "offline"): + assert ours[name]["desc"]["en"] == cloud[name]["desc"]["en"] + + # Every code the cloud maps has the cloud's English label; the only extra + # codes are the documented template ones. Only English is built in; the + # cloud's 22 languages come from the snapshot when there is one. + cloud_states, our_states = _en_labels(cloud["state"]), _en_labels(ours["state"]) + assert {code: our_states.get(code) for code in cloud_states} == cloud_states + assert {code: label for code, label in our_states.items() if code not in cloud_states} == ( + _TEMPLATE_ONLY_STATE_LABELS + ) + cloud_offline, our_offline = _en_labels(cloud["offline"]), _en_labels(ours["offline"]) + assert {code: our_offline.get(code) for code in cloud_offline} == cloud_offline + assert {code: label for code, label in our_offline.items() if code not in cloud_offline} == ( + _TEMPLATE_ONLY_OFFLINE_LABELS + ) + + +def test_cloud_fixture_card_spec_is_passed_through_with_all_languages(tmp_path: Path) -> None: + cloud_card_spec = json.dumps(CLOUD_VACUUM_CARD_SPEC_EU, ensure_ascii=False) + _write_cloud_product_snapshot( + tmp_path, + [ + { + "category": {"id": 1, "code": "robot.vacuum.cleaner", "cardspec": cloud_card_spec}, + "productList": [{"id": 101, "model": "roborock.vacuum.a15", "productTags": []}], + } + ], + ) + data = _products_v5(tmp_path, [_DEVICE]) - card_spec = json.loads(data["categoryDetailList"][0]["category"]["cardspec"])["data"] - states = _labels(card_spec["state"]) - offline = _labels(card_spec["offline"]) - - # Wording of the cloud's EU /api/v5/product answer (Nov 2026). - assert states[6] == "Returning to Dock" - assert states[15] == "Returning to Dock" - assert states[9] == "Charging Error" - assert states[26] == "Going to wash the mop" - assert offline[1] == "Powered Off Manually" - # Every state code of the cloud is mapped, plus the extra ones of the - # template bundled with the app. - cloud_codes = {2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 22, 23, 26, 28, 29, 32} - extra_codes = {13, 33, 34, 36, 37, 38, 39, 40, 101, 102, 103, 104, 108} - assert cloud_codes <= set(states) - assert set(states) == cloud_codes | extra_codes - assert {1, 34, 51, 103} <= set(offline) + category = data["categoryDetailList"][0]["category"] + assert json.loads(category["cardspec"]) == CLOUD_VACUUM_CARD_SPEC_EU + languages = {lang for entry in json.loads(category["cardspec"])["data"]["state"]["value"] for lang in entry["desc"]} + assert len(languages) == 22 def test_card_spec_only_on_known_categories(tmp_path: Path) -> None: