diff --git a/config.example.toml b/config.example.toml index 02302870..e0957bf1 100644 --- a/config.example.toml +++ b/config.example.toml @@ -14,9 +14,10 @@ mqtt_tls_port = 8881 # traffic to the server; the proxy must present a valid cert to clients. See docs/reverse_proxy.md. # listener_mode = "local_tls" region = "us" -# Optional timezone returned by the bootstrap location route. +# Optional timezone returned by the bootstrap location route, and for devices without their own timezone. # Defaults to the region default if unset ("Europe/Berlin" for "eu", "America/New_York" for "us", -# "Asia/Shanghai" for "cn", "Europe/Moscow" for "ru"). +# "Asia/Shanghai" for "cn", "Europe/Moscow" for "ru"). Set it if your timezone differs from that +# default, for example "Europe/London" in the "eu" region. # timezone = "Europe/Berlin" [broker] 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 e0987da0..ed6d2441 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 @@ -7,9 +7,17 @@ import time from typing import Any, Callable, Sequence -from shared.constants import DEFAULT_HOME_NAME, DEFAULT_PRODUCT_SCHEMA, DEFAULT_TIMEZONE, MODEL_PRODUCT_ID_OVERRIDES +from shared.constants import DEFAULT_HOME_NAME, DEFAULT_PRODUCT_SCHEMA, MODEL_PRODUCT_ID_OVERRIDES from shared.context import ServerContext -from shared.data_helpers import as_bool, as_int, default_home_id, default_product_name, get_value, stable_int +from shared.data_helpers import ( + as_bool, + as_int, + default_home_id, + default_product_name, + default_timezone, + get_value, + stable_int, +) from shared.http_helpers import wrap_response from shared.inventory_io import WEB_API_INVENTORY_FILE, load_inventory, write_inventory @@ -306,6 +314,7 @@ def _normalize_devices( connected_ids = runtime_connected_ids or set() products_by_id: dict[str, dict[str, Any]] = {} devices: list[dict[str, Any]] = [] + fallback_timezone = default_timezone(ctx) for index, raw in enumerate(devices_raw): raw_item = raw if isinstance(raw, dict) else {} fallback_duid = ctx.duid if index == 0 else f"{ctx.duid}_{index + 1}" @@ -323,7 +332,7 @@ def _normalize_devices( model = str(get_value(raw_item, "model", default="roborock.vacuum.a117")) category = str(get_value(raw_item, "category", default="robot.vacuum.cleaner")) product_name = str(get_value(raw_item, "product_name", "productName", default=default_product_name(model))) - timezone = str(get_value(raw_item, "timezone", "timeZoneId", "time_zone_id", default=DEFAULT_TIMEZONE)) + timezone = str(get_value(raw_item, "timezone", "timeZoneId", "time_zone_id", default=fallback_timezone)) room_id_value = get_value(raw_item, "room_id", "roomId") room_id = as_int(room_id_value, 0) if room_id_value is not None else None runtime_online = _runtime_online_for_device( diff --git a/src/roborock_local_server/bundled_backend/https_server/routes/bootstrap/location.py b/src/roborock_local_server/bundled_backend/https_server/routes/bootstrap/location.py index caf933ff..9c1cb35e 100644 --- a/src/roborock_local_server/bundled_backend/https_server/routes/bootstrap/location.py +++ b/src/roborock_local_server/bundled_backend/https_server/routes/bootstrap/location.py @@ -3,30 +3,14 @@ from typing import Any from shared.context import ServerContext +from shared.data_helpers import default_timezone from shared.http_helpers import wrap_response -REGION_TIMEZONES: dict[str, str] = { - "eu": "Europe/Berlin", - "us": "America/New_York", - "cn": "Asia/Shanghai", - "ru": "Europe/Moscow", -} - -DEFAULT_FALLBACK_TIMEZONE = "America/New_York" - def match(path: str) -> bool: return "location" in path -def determine_timezone(ctx: ServerContext) -> str: - if ctx.timezone and ctx.timezone.strip(): - return ctx.timezone.strip() - - region = (ctx.region or "").strip().lower() - return REGION_TIMEZONES.get(region, DEFAULT_FALLBACK_TIMEZONE) - - def build( ctx: ServerContext, _query_params: dict[str, list[str]], @@ -34,6 +18,6 @@ def build( _clean_path: str, ) -> dict[str, Any]: country = (ctx.region or "us").strip().upper() or "US" - timezone = determine_timezone(ctx) + timezone = default_timezone(ctx) return wrap_response({"country": country, "timezone": timezone}) 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 04642bf4..c3ff5259 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 @@ -9,9 +9,9 @@ from roborock_local_server.inventory import _extract_inventory_vacuums from roborock_local_server.inventory import _merge_vacuum_state -from shared.constants import DEFAULT_PRODUCT_SCHEMA, DEFAULT_TIMEZONE +from shared.constants import DEFAULT_PRODUCT_SCHEMA from shared.context import ServerContext -from shared.data_helpers import as_bool, as_int, default_product_name, get_value +from shared.data_helpers import as_bool, as_int, default_product_name, default_timezone, get_value from shared.inventory_io import ( DEVICE_OVERRIDES_KEY, WEB_API_INVENTORY_FILE, @@ -244,6 +244,7 @@ def _normalize_devices( ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: products_by_id: dict[str, dict[str, Any]] = {} devices: list[dict[str, Any]] = [] + fallback_timezone = default_timezone(ctx) for index, raw in enumerate(devices_raw): raw_item = raw if isinstance(raw, dict) else {} fallback_duid = ctx.duid if index == 0 else f"{ctx.duid}_{index + 1}" @@ -261,7 +262,7 @@ def _normalize_devices( model = str(get_value(raw_item, "model", default="roborock.vacuum.a117")) category = str(get_value(raw_item, "category", default="robot.vacuum.cleaner")) product_name = str(get_value(raw_item, "product_name", "productName", default=default_product_name(model))) - timezone = str(get_value(raw_item, "timezone", "timeZoneId", "time_zone_id", default=DEFAULT_TIMEZONE)) + timezone = str(get_value(raw_item, "timezone", "timeZoneId", "time_zone_id", default=fallback_timezone)) room_id_value = get_value(raw_item, "room_id", "roomId") room_id = as_int(room_id_value, 0) if room_id_value is not None else None device = { @@ -629,7 +630,7 @@ def device_detail_payload(ctx: ServerContext, device_id: str) -> dict[str, Any]: "timeZoneId", "time_zone_id", "timezone", - default=get_value(normalized_device, "timeZoneId", default=DEFAULT_TIMEZONE), + default=get_value(normalized_device, "timeZoneId", default=default_timezone(ctx)), ) ), "iconUrl": str( @@ -729,7 +730,8 @@ def device_jobs_payload(ctx: ServerContext, device_id: str) -> list[dict[str, An payload["repeated"] = as_bool(get_value(raw, "repeated", default=True), True) payload["enabled"] = as_bool(get_value(raw, "enabled", default=True), True) payload["param"] = get_value(raw, "param", default={}) or {} - upcoming = next_fire_time_utc(payload, default_timezone=str(getattr(ctx, "timezone", "") or "")) + # The same zone as the schedule runner, so nextFireTime names the time the job runs. + upcoming = next_fire_time_utc(payload, default_timezone=default_timezone(ctx)) if upcoming is not None: payload["nextFireTime"] = upcoming.strftime("%Y-%m-%dT%H:%M:%S.000+00:00") else: diff --git a/src/roborock_local_server/bundled_backend/shared/constants.py b/src/roborock_local_server/bundled_backend/shared/constants.py index 561bb070..39f8b24f 100644 --- a/src/roborock_local_server/bundled_backend/shared/constants.py +++ b/src/roborock_local_server/bundled_backend/shared/constants.py @@ -3,6 +3,7 @@ from typing import Any DEFAULT_HOME_NAME = "Local Home" +# default_timezone falls back to it for a region without its own timezone. DEFAULT_TIMEZONE = "America/New_York" DEFAULT_PRODUCT_SCHEMA: list[dict[str, Any]] = [ diff --git a/src/roborock_local_server/bundled_backend/shared/data_helpers.py b/src/roborock_local_server/bundled_backend/shared/data_helpers.py index b0b90629..22847e1d 100644 --- a/src/roborock_local_server/bundled_backend/shared/data_helpers.py +++ b/src/roborock_local_server/bundled_backend/shared/data_helpers.py @@ -4,6 +4,8 @@ from datetime import datetime, timezone from typing import Any, TYPE_CHECKING +from .constants import DEFAULT_TIMEZONE + if TYPE_CHECKING: from .context import ServerContext @@ -61,6 +63,23 @@ def default_home_id(ctx: ServerContext) -> int: return stable_int(f"{ctx.duid}:home") +REGION_TIMEZONES: dict[str, str] = { + "eu": "Europe/Berlin", + "us": "America/New_York", + "cn": "Asia/Shanghai", + "ru": "Europe/Moscow", +} + + +def default_timezone(ctx: ServerContext) -> str: + """Return network.timezone if set, else the timezone of the region.""" + if ctx.timezone and ctx.timezone.strip(): + return ctx.timezone.strip() + + region = (ctx.region or "").strip().lower() + return REGION_TIMEZONES.get(region, DEFAULT_TIMEZONE) + + def default_product_name(model: str) -> str: short_model = model.split(".")[-1].upper() if model else "VACUUM" return f"Roborock {short_model}" diff --git a/tests/conftest.py b/tests/conftest.py index f4b4d43b..a17994b8 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -18,9 +18,11 @@ def write_release_config( tmp_path: Path, *, stack_fqdn: str = "api-roborock.example.com", + region: str = "us", listener_mode: str = "local_tls", https_port: int = 443, mqtt_tls_port: int = 8883, + timezone: str = "", broker_mode: str = "external", enable_topic_bridge: bool = False, protocol_auth_enabled: bool = True, @@ -33,14 +35,17 @@ def write_release_config( (cert_dir / "fullchain.pem").write_text("test-cert\n", encoding="utf-8") (cert_dir / "privkey.pem").write_text("test-key\n", encoding="utf-8") + timezone_line = f'timezone = "{timezone}"' if timezone else "" config_file = tmp_path / "config.toml" config_file.write_text( f""" [network] stack_fqdn = "{stack_fqdn}" +region = "{region}" listener_mode = "{listener_mode}" https_port = {https_port} mqtt_tls_port = {mqtt_tls_port} +{timezone_line} [broker] mode = "{broker_mode}" diff --git a/tests/test_home_data_online.py b/tests/test_home_data_online.py index 1aaeed39..c42863aa 100644 --- a/tests/test_home_data_online.py +++ b/tests/test_home_data_online.py @@ -242,6 +242,85 @@ def test_home_data_response_does_not_emit_empty_snake_case_received_devices(tmp_ assert "6HL2zfniaoYYV01CkVuhkO" in parsed_home.device_products +@pytest.mark.parametrize( + ("region", "timezone", "device_timezone", "expected"), + [ + ("eu", "", None, "Europe/Berlin"), + ("us", "", None, "America/New_York"), + ("eu", "Europe/Vienna", None, "Europe/Vienna"), + ("eu", "", "Asia/Tokyo", "Asia/Tokyo"), + ], +) +def test_device_time_zone_defaults_to_the_server_time_zone( + tmp_path: Path, + region: str, + timezone: str, + device_timezone: str | None, + expected: str, +) -> None: + config_file = write_release_config(tmp_path, region=region, timezone=timezone) + config = load_config(config_file) + paths = resolve_paths(config_file, config) + + duid = "6HL2zfniaoYYV01CkVuhkO" + device: dict[str, object] = { + "duid": duid, + "name": "Roborock Qrevo MaxV", + "model": "roborock.vacuum.a87", + "product_id": "5gUei3OIJIXVD3eD85Balg", + "local_key": "xPd5Dr8CGGqtdDlH", + } + if device_timezone is not None: + device["timezone"] = device_timezone + + 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": 1316433, "name": "My Home"}, "devices": [device]}) + "\n", + encoding="utf-8", + ) + _seed_cloud_snapshot(paths.cloud_snapshot_path, {"id": 1316433, "name": "My Home"}) + paths.runtime_credentials_path.write_text( + json.dumps( + { + "schema_version": 2, + "devices": [ + { + "did": "1103821560705", + "duid": duid, + "name": "Roborock Qrevo MaxV", + "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", + ) + + supervisor = ReleaseSupervisor(config=config, paths=paths) + supervisor.refresh_inventory_state() + client = TestClient(supervisor.app) + + home_path = "/v3/user/homes/1316433" + home_response = client.get(home_path, headers=_hawk_headers(paths.cloud_snapshot_path, home_path)) + assert home_response.status_code == 200 + home_devices = home_response.json()["result"]["devices"] + assert [item["timeZoneId"] for item in home_devices] == [expected] + + detail_path = f"/user/devices/{duid}" + detail_response = client.get(detail_path, headers=_hawk_headers(paths.cloud_snapshot_path, detail_path)) + assert detail_response.status_code == 200 + assert detail_response.json()["data"]["timeZoneId"] == expected + + def test_device_detail_uses_runtime_connection_and_preserves_inventory_fields(tmp_path: Path) -> None: config_file = write_release_config(tmp_path) config = load_config(config_file) diff --git a/tests/test_schedule_runner.py b/tests/test_schedule_runner.py index 22b50879..2f708515 100644 --- a/tests/test_schedule_runner.py +++ b/tests/test_schedule_runner.py @@ -346,11 +346,15 @@ def test_server_timezone_prefers_the_configured_zone(): def test_server_timezone_without_the_region_helper_falls_back_to_new_york(monkeypatch): - # Main has no data_helpers.default_timezone (the branch that adds it is not merged here). + # Covers a data_helpers without default_timezone. monkeypatch.delattr(sr.data_helpers, "default_timezone", raising=False) assert sr.server_timezone(SimpleNamespace(timezone="", region="eu")) == NEW_YORK +def test_server_timezone_without_a_configured_zone_uses_the_region_zone(): + assert sr.server_timezone(SimpleNamespace(timezone="", region="eu")) == "Europe/Berlin" + + def test_server_timezone_uses_the_region_helper_when_present(monkeypatch): monkeypatch.setattr(sr.data_helpers, "default_timezone", lambda ctx: "Europe/Berlin", raising=False) assert sr.server_timezone(SimpleNamespace(timezone="", region="eu")) == "Europe/Berlin" diff --git a/tests/test_schedules.py b/tests/test_schedules.py index 41a6228f..9a5a168e 100644 --- a/tests/test_schedules.py +++ b/tests/test_schedules.py @@ -59,8 +59,9 @@ def _hawk_headers(snapshot_path: Path, path: str) -> dict[str, str]: } -def test_device_jobs_endpoint_returns_imported_schedules(tmp_path: Path) -> None: - config_file = write_release_config(tmp_path) +@pytest.mark.parametrize(("region", "next_fire_utc"), [("us", "T18:03"), ("eu", "T12:03")]) +def test_device_jobs_endpoint_returns_imported_schedules(tmp_path: Path, region: str, next_fire_utc: str) -> None: + config_file = write_release_config(tmp_path, region=region) config = load_config(config_file) paths = resolve_paths(config_file, config) @@ -110,10 +111,10 @@ def test_device_jobs_endpoint_returns_imported_schedules(tmp_path: Path) -> None assert payload["success"] is True assert payload["data"] == payload["result"] # nextFireTime is computed from the cron against "now", so check its shape, not its value. - # No timezone is configured, so the cron runs in the zone the robot is told (America/New_York): - # 13:03 local on Dec 15 is 18:03Z. + # No timezone is configured, so the cron runs in the region's zone, which the robot is told too. + # 13:03 local on Dec 15 is 18:03Z in America/New_York (us) and 12:03Z in Europe/Berlin (eu). next_fire_time = payload["result"][0].pop("nextFireTime") - assert next_fire_time.endswith("T18:03:00.000+00:00") + assert next_fire_time.endswith(f"{next_fire_utc}:00.000+00:00") assert payload["result"] == [ { **schedule,