diff --git a/src/roborock_local_server/bundled_backend/https_server/endpoint_rules.py b/src/roborock_local_server/bundled_backend/https_server/endpoint_rules.py index c4f88b6..f94a4be 100644 --- a/src/roborock_local_server/bundled_backend/https_server/endpoint_rules.py +++ b/src/roborock_local_server/bundled_backend/https_server/endpoint_rules.py @@ -109,7 +109,9 @@ from .routes.auth.login import match_login_sms_code_send as _match_login_sms_code_send_v1 from .routes.user.devices.detail import build as _build_get_device from .routes.user.devices.detail import build_extra as _build_get_device_extra +from .routes.user.devices.detail import build_put as _build_put_device from .routes.user.devices.detail import match as _match_get_device +from .routes.user.devices.detail import match_put as _match_put_device from .routes.user.devices.detail import match_extra as _match_get_device_extra from .routes.user.deviceshare import build_received_devices as _build_get_received_devices from .routes.user.deviceshare import build_rooms as _build_get_shared_device_rooms @@ -596,6 +598,7 @@ def default_endpoint_rules() -> Sequence[EndpointRule]: EndpointRule("put_scene_validity", _match_put_scene_validity, _build_put_scene_validity), EndpointRule("execute_scene", _match_execute_scene, _build_execute_scene), EndpointRule("delete_scene", _match_delete_scene, _build_delete_scene), + EndpointRule("put_device", _match_put_device, _build_put_device), EndpointRule("get_device", _match_get_device, _build_get_device), EndpointRule("get_device_extra", _match_get_device_extra, _build_get_device_extra), EndpointRule("get_schedules", _match_get_schedules, _build_get_schedules), diff --git a/src/roborock_local_server/bundled_backend/https_server/routes/user/devices/detail.py b/src/roborock_local_server/bundled_backend/https_server/routes/user/devices/detail.py index ebf293d..41f5c68 100644 --- a/src/roborock_local_server/bundled_backend/https_server/routes/user/devices/detail.py +++ b/src/roborock_local_server/bundled_backend/https_server/routes/user/devices/detail.py @@ -6,7 +6,7 @@ from shared.context import ServerContext from shared.http_helpers import wrap_response -from .service import device_detail_payload +from .service import device_detail_payload, parse_device_name, parse_strict_bool, store_device_settings def _device_id_from_path(clean_path: str) -> str: @@ -33,6 +33,38 @@ def build( return wrap_response(device_detail_payload(ctx, device_id)) +def match_put(path: str, method: str = "GET") -> bool: + return method.upper() == "PUT" and match(path) + + +def _first_value(body_params: dict[str, list[str]], key: str) -> str | None: + values = body_params.get(key) or [] + return str(values[0]) if values else None + + +def build_put( + ctx: ServerContext, + _query_params: dict[str, list[str]], + body_params: dict[str, list[str]], + clean_path: str, +) -> dict[str, Any]: + device_id = _device_id_from_path(clean_path) + updates: dict[str, Any] = {} + raw_name = _first_value(body_params, "name") + if raw_name is not None: + name = parse_device_name(raw_name) + if name is not None: + updates["name"] = name + raw_switch = _first_value(body_params, "silentOtaSwitch") + if raw_switch is not None: + switch = parse_strict_bool(raw_switch) + if switch is not None: + updates["silentOtaSwitch"] = switch + if updates: + store_device_settings(ctx, device_id, updates) + return wrap_response(device_detail_payload(ctx, device_id)) + + def match_extra(path: str) -> bool: clean = path.rstrip("/") return bool(re.fullmatch(r"/user/devices/[^/]+/extra", clean)) diff --git a/src/roborock_local_server/bundled_backend/https_server/routes/user/devices/service.py b/src/roborock_local_server/bundled_backend/https_server/routes/user/devices/service.py index 0f6990c..aaa8051 100644 --- a/src/roborock_local_server/bundled_backend/https_server/routes/user/devices/service.py +++ b/src/roborock_local_server/bundled_backend/https_server/routes/user/devices/service.py @@ -12,8 +12,83 @@ from shared.constants import DEFAULT_PRODUCT_SCHEMA, DEFAULT_TIMEZONE from shared.context import ServerContext from shared.data_helpers import as_bool, as_int, default_product_name, get_value -from shared.inventory_io import WEB_API_INVENTORY_FILE, load_inventory +from shared.inventory_io import ( + DEVICE_OVERRIDES_KEY, + WEB_API_INVENTORY_FILE, + device_overrides, + inventory_mutation, + load_inventory, + write_inventory, +) _DEFAULT_DEVICE_NAME = "Vacuum 1" +_MAX_DEVICE_NAME_LENGTH = 64 +_DEVICE_COLLECTIONS = ("devices", "receivedDevices", "received_devices") + + +def _apply_device_overrides(ctx: ServerContext, home_data: dict[str, Any]) -> dict[str, Any]: + overrides = device_overrides(load_inventory(ctx)) + if not overrides: + return home_data + out = dict(home_data) + for key in _DEVICE_COLLECTIONS: + devices = home_data.get(key) + if not isinstance(devices, list): + continue + updated: list[Any] = [] + for device in devices: + override = overrides.get(str(get_value(device, "duid", "did", default="")).strip()) if isinstance(device, dict) else None + if override: + device = {**device, **override} + updated.append(device) + out[key] = updated + return out + + +def parse_device_name(value: Any) -> str | None: + name = str(value or "").strip() + if not name or len(name) > _MAX_DEVICE_NAME_LENGTH: + return None + return name + + +def parse_strict_bool(value: Any) -> bool | None: + text = str(value or "").strip().lower() + if text == "true": + return True + if text == "false": + return False + return None + + +def _device_known(ctx: ServerContext, device_id: str) -> bool: + if not device_id: + return False + inventory = load_inventory(ctx) + if _find_device_record((_load_cloud_home_data(ctx), inventory), device_id): + return True + return any( + str(get_value(item, "duid", "did", default="")).strip() == device_id + for key in ("devices", "receivedDevices") + for item in (_home_data(ctx).get(key) or []) + if isinstance(item, dict) + ) + + +@inventory_mutation +def store_device_settings(ctx: ServerContext, device_id: str, updates: dict[str, Any]) -> bool: + """Persist local name/silentOtaSwitch overrides for a known device; False if unknown or unwritable.""" + if not updates or not _device_known(ctx, device_id): + return False + inventory = load_inventory(ctx) + stored = device_overrides(inventory) + stored[device_id] = {**stored.get(device_id, {}), **updates} + inventory[DEVICE_OVERRIDES_KEY] = stored + # Also mirror onto inventory records so readers of the raw inventory see the change. + for key in ("devices", "received_devices", "receivedDevices"): + for item in inventory.get(key) or []: + if isinstance(item, dict) and str(get_value(item, "duid", "did", default="")).strip() == device_id: + item.update(updates) + return write_inventory(ctx, inventory) def _has_value(value: Any) -> bool: @@ -314,7 +389,7 @@ def _apply_runtime_online_status(ctx: ServerContext, home_data: dict[str, Any]) def enrich_home_data_with_cloud_snapshot(ctx: ServerContext, home_data: dict[str, Any]) -> dict[str, Any]: cloud_home_data = _load_cloud_home_data(ctx) or {} if not cloud_home_data: - return home_data + return _apply_device_overrides(ctx, home_data) enriched_home = dict(home_data) @@ -389,7 +464,7 @@ def enrich_home_data_with_cloud_snapshot(ctx: ServerContext, home_data: dict[str if enriched_devices: enriched_home[collection_key] = enriched_devices - return enriched_home + return _apply_device_overrides(ctx, enriched_home) def _home_data(ctx: ServerContext) -> dict[str, Any]: @@ -427,7 +502,7 @@ def _home_data(ctx: ServerContext) -> dict[str, Any]: home["id"] = resolve_home_id(home, cloud_home_data, default=0) home["name"] = str(get_value(home, "name", "home_name", default="Local Home")) - return _apply_runtime_online_status(ctx, home) + return _apply_runtime_online_status(ctx, _apply_device_overrides(ctx, home)) def device_detail_payload(ctx: ServerContext, device_id: str) -> dict[str, Any]: @@ -449,6 +524,7 @@ def device_detail_payload(ctx: ServerContext, device_id: str) -> dict[str, Any]: {}, ) raw_device = _find_device_record((cloud_home_data, inventory), device_id) + raw_device.update(device_overrides(inventory).get(device_id, {})) product_id = str( get_value( diff --git a/src/roborock_local_server/bundled_backend/import_web_inventory_from_cloud.py b/src/roborock_local_server/bundled_backend/import_web_inventory_from_cloud.py index b79dfd0..ede4b30 100644 --- a/src/roborock_local_server/bundled_backend/import_web_inventory_from_cloud.py +++ b/src/roborock_local_server/bundled_backend/import_web_inventory_from_cloud.py @@ -785,6 +785,15 @@ def _merge_existing_inventory_mutations( merged["home_scenes"] = home_scenes merged["scene_order"] = _merge_scene_order(merged.get("scene_order"), existing_inventory.get("scene_order")) + + overrides = existing_inventory.get("device_overrides") + if isinstance(overrides, dict) and overrides: + merged["device_overrides"] = overrides + for key in ("devices", "received_devices", "receivedDevices"): + for item in merged.get(key) or []: + override = overrides.get(str(item.get("duid") or "").strip()) if isinstance(item, dict) else None + if isinstance(override, dict): + item.update(override) return merged diff --git a/src/roborock_local_server/bundled_backend/mqtt_tls_proxy_server/command_handlers.py b/src/roborock_local_server/bundled_backend/mqtt_tls_proxy_server/command_handlers.py index 57c7cd6..5e568c7 100644 --- a/src/roborock_local_server/bundled_backend/mqtt_tls_proxy_server/command_handlers.py +++ b/src/roborock_local_server/bundled_backend/mqtt_tls_proxy_server/command_handlers.py @@ -26,8 +26,14 @@ def handle_request(self, request: dict[str, Any]) -> HandlerResult | None: def _parse_fan_power(params: Any) -> int | None: if isinstance(params, int): return params + if isinstance(params, dict): + # set_clean_motor_mode sends [{"fan_power": 102, "water_box_mode": 202, ...}]. + value = params.get("fan_power") + return value if isinstance(value, int) and not isinstance(value, bool) else None if isinstance(params, list) and params: first = params[0] + if isinstance(first, dict): + return _parse_fan_power(first) if isinstance(first, int): return first if isinstance(first, str): diff --git a/src/roborock_local_server/bundled_backend/shared/inventory_io.py b/src/roborock_local_server/bundled_backend/shared/inventory_io.py index addf2cb..7ceab9f 100644 --- a/src/roborock_local_server/bundled_backend/shared/inventory_io.py +++ b/src/roborock_local_server/bundled_backend/shared/inventory_io.py @@ -14,6 +14,7 @@ from .context import ServerContext WEB_API_INVENTORY_FILE = "web_api_inventory.json" +DEVICE_OVERRIDES_KEY = "device_overrides" _LOGGER = logging.getLogger(__name__) _LOCKS: dict[Path, Any] = {} _LOCKS_GUARD = threading.Lock() @@ -82,3 +83,11 @@ def write_inventory(ctx: ServerContext, inventory: dict[str, Any]) -> bool: _LOGGER.exception("Unable to persist inventory") return False return True + + +def device_overrides(inventory: dict[str, Any]) -> dict[str, dict[str, Any]]: + """Return the local per-duid device overrides (name, silentOtaSwitch) stored in the inventory.""" + value = inventory.get(DEVICE_OVERRIDES_KEY) + if not isinstance(value, dict): + return {} + return {str(duid): dict(item) for duid, item in value.items() if isinstance(item, dict)} diff --git a/src/roborock_local_server/server.py b/src/roborock_local_server/server.py index 105a2aa..c0412ef 100644 --- a/src/roborock_local_server/server.py +++ b/src/roborock_local_server/server.py @@ -670,6 +670,7 @@ def _is_public_protocol_path(cls, clean_path: str) -> bool: "/api/v1/appplugin", "/api/v1/plugins", "/api/v4/agreement/latest", + "/api/v4/app/agreement/latest", } @classmethod diff --git a/tests/test_device_put.py b/tests/test_device_put.py new file mode 100644 index 0000000..7ebfe43 --- /dev/null +++ b/tests/test_device_put.py @@ -0,0 +1,189 @@ +import json +from pathlib import Path + +from fastapi.testclient import TestClient + +from conftest import write_release_config +from roborock_local_server.bundled_backend.import_web_inventory_from_cloud import ( + _merge_existing_inventory_mutations, +) +from roborock_local_server.config import load_config, resolve_paths +from roborock_local_server.server import ReleaseSupervisor +from shared.protocol_auth import ProtocolAuthStore, build_hawk_authorization + +DUID = "6HL2zfniaoYYV01CkVuhkO" +_NONCES: list[int] = [] +PATH = f"/user/devices/{DUID}" + + +def _build(tmp_path: Path): + 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": DUID, + "name": "Old Name", + "model": "roborock.vacuum.a87", + "product_id": "5gUei3OIJIXVD3eD85Balg", + "local_key": "xPd5Dr8CGGqtdDlH", + "silentOtaSwitch": False, + } + ], + } + ) + + "\n", + encoding="utf-8", + ) + paths.cloud_snapshot_path.write_text( + json.dumps( + { + "user_data": { + "uid": 1001, + "token": "t", + "rruid": "r", + "rriot": { + "u": "hu", + "s": "hs", + "h": "hh", + "k": "hk", + "r": {"r": "US", "a": "https://api-us.roborock.com", "m": "ssl://m:8883", "l": "https://w"}, + }, + }, + "home_data": { + "id": 1233716, + "name": "My Home", + "devices": [ + {"duid": DUID, "name": "Cloud Name", "productId": "5gUei3OIJIXVD3eD85Balg", "silentOtaSwitch": False} + ], + "products": [ + {"id": "5gUei3OIJIXVD3eD85Balg", "name": "Q", "model": "roborock.vacuum.a87", "category": "x"} + ], + }, + } + ) + + "\n", + encoding="utf-8", + ) + paths.runtime_credentials_path.write_text( + json.dumps( + { + "schema_version": 2, + "devices": [ + { + "did": "1103821560705", + "duid": DUID, + "name": "Old Name", + "model": "roborock.vacuum.a87", + "product_id": "5gUei3OIJIXVD3eD85Balg", + "localkey": "xPd5Dr8CGGqtdDlH", + "local_key_source": "inventory_cloud", + "device_mqtt_usr": "c25b14ceac358d2a", + "updated_at": "2026-03-17T22:50:00+00:00", + "last_nc_at": "", + "last_mqtt_seen_at": "", + } + ], + } + ) + + "\n", + encoding="utf-8", + ) + return config, paths + + +def _client(config, paths) -> TestClient: + supervisor = ReleaseSupervisor(config=config, paths=paths) + supervisor.refresh_inventory_state() + return TestClient(supervisor.app) + + +def _headers(paths, method: str, path: str, form=None) -> dict[str, str]: + user = ProtocolAuthStore(paths.cloud_snapshot_path).availability().user + assert user is not None + _NONCES.append(0) + return {"Authorization": build_hawk_authorization(user=user, path=path, form_values=form, nonce=f"n{len(_NONCES)}")} + + +def _put(client, paths, path, data): + return client.put(path, data=data, headers=_headers(paths, "PUT", path, data)) + + +def _get(client, paths, path): + return client.get(path, headers=_headers(paths, "GET", path)) + + +def test_put_stores_name_and_switch_and_get_shows_them(tmp_path: Path) -> None: + config, paths = _build(tmp_path) + client = _client(config, paths) + assert _get(client, paths, PATH).json()["data"]["name"] == "Cloud Name" + + response = _put(client, paths, PATH, {"name": " Kitchen Bot "}) + assert response.status_code == 200 + body = response.json() + assert body["success"] is True and body["data"]["name"] == "Kitchen Bot" + + _put(client, paths, PATH, {"silentOtaSwitch": "true"}) + data = _get(client, paths, PATH).json()["data"] + assert data["name"] == "Kitchen Bot" + assert data["silentOtaSwitch"] is True + + _put(client, paths, PATH, {"silentOtaSwitch": "false"}) + assert _get(client, paths, PATH).json()["data"]["silentOtaSwitch"] is False + + +def test_put_shows_in_home_data(tmp_path: Path) -> None: + config, paths = _build(tmp_path) + client = _client(config, paths) + _put(client, paths, PATH, {"name": "Kitchen Bot", "silentOtaSwitch": "true"}) + home_path = "/v3/user/homes/1233716" + devices = _get(client, paths, home_path).json()["data"]["devices"] + assert devices[0]["name"] == "Kitchen Bot" + assert devices[0]["silentOtaSwitch"] is True + + +def test_put_rejects_bad_values_and_ignores_other_fields(tmp_path: Path) -> None: + config, paths = _build(tmp_path) + client = _client(config, paths) + _put(client, paths, PATH, {"silentOtaSwitch": "yes", "name": " ", "localKey": "evil", "online": "false"}) + data = _get(client, paths, PATH).json()["data"] + assert data["name"] == "Cloud Name" + assert data["silentOtaSwitch"] is False + assert data["localKey"] != "evil" + _put(client, paths, PATH, {"name": "x" * 500}) + assert _get(client, paths, PATH).json()["data"]["name"] == "Cloud Name" + assert "device_overrides" not in json.loads(paths.inventory_path.read_text(encoding="utf-8")) + + +def test_put_unknown_duid_stores_nothing(tmp_path: Path) -> None: + config, paths = _build(tmp_path) + client = _client(config, paths) + other = "/user/devices/unknownduid" + response = _put(client, paths, other, {"name": "Ghost"}) + assert response.status_code == 200 + assert response.json()["data"]["name"] != "Ghost" + assert "device_overrides" not in json.loads(paths.inventory_path.read_text(encoding="utf-8")) + + +def test_override_survives_reload_and_cloud_import(tmp_path: Path) -> None: + config, paths = _build(tmp_path) + client = _client(config, paths) + _put(client, paths, PATH, {"name": "Kitchen Bot", "silentOtaSwitch": "true"}) + stored = json.loads(paths.inventory_path.read_text(encoding="utf-8")) + assert stored["device_overrides"][DUID] == {"name": "Kitchen Bot", "silentOtaSwitch": True} + + reloaded = _client(config, paths) + data = _get(reloaded, paths, PATH).json()["data"] + assert data["name"] == "Kitchen Bot" and data["silentOtaSwitch"] is True + + fresh = {"devices": [{"duid": DUID, "name": "Cloud Name", "silentOtaSwitch": False}]} + merged = _merge_existing_inventory_mutations(fresh, stored) + assert merged["devices"][0]["name"] == "Kitchen Bot" + assert merged["devices"][0]["silentOtaSwitch"] is True + assert merged["device_overrides"][DUID]["name"] == "Kitchen Bot" diff --git a/tests/test_fan_power_handler.py b/tests/test_fan_power_handler.py new file mode 100644 index 0000000..d6aa384 --- /dev/null +++ b/tests/test_fan_power_handler.py @@ -0,0 +1,25 @@ +import roborock_local_server.server # noqa: F401 (puts the bundled backend on sys.path) +from mqtt_tls_proxy_server.command_handlers import FanPowerHandler + + +def _handled(method: str, params: object) -> dict | None: + result = FanPowerHandler().handle_request({"method": method, "params": params}) + return None if result is None else result.state_updates + + +def test_set_custom_mode_still_reads_a_plain_list() -> None: + assert _handled("set_custom_mode", [103]) == {"fan_power": 103} + + +def test_set_clean_motor_mode_reads_the_dict_the_app_sends() -> None: + params = [{"fan_power": 102, "water_box_mode": 202, "mop_mode": 300}] + assert _handled("set_clean_motor_mode", params) == {"fan_power": 102} + + +def test_a_bare_dict_is_read_too() -> None: + assert _handled("set_clean_motor_mode", {"fan_power": 104}) == {"fan_power": 104} + + +def test_a_dict_without_fan_power_records_nothing() -> None: + assert _handled("set_clean_motor_mode", [{"water_box_mode": 202}]) is None + assert _handled("set_clean_motor_mode", [{"fan_power": True}]) is None diff --git a/tests/test_protocol_auth.py b/tests/test_protocol_auth.py index 87249eb..49ffd17 100644 --- a/tests/test_protocol_auth.py +++ b/tests/test_protocol_auth.py @@ -585,3 +585,10 @@ def test_persisted_sessions_are_still_capped(tmp_path: Path) -> None: auth_store.issue_local_session(base_user_data, source=f"login_{index}") assert len(auth_store.persisted_sessions()) == 3 + + +def test_agreement_latest_is_readable_before_login_on_both_paths() -> None: + # The route that answers is /api/v4/app/agreement/latest; it must be as public as the older path. + assert ReleaseSupervisor._required_protocol_auth("/api/v4/agreement/latest") is None + assert ReleaseSupervisor._required_protocol_auth("/api/v4/app/agreement/latest") is None + assert ReleaseSupervisor._required_protocol_auth("/api/v4/app/agreement/latest/") is None