Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/known_limitations.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ I have tried to copy over most functionality into this server, but some is not 1

- Vacuum camera live streaming — supported with a TURN relay and a short camera bootstrap hostname; see [camera.md](camera.md). Verified on the Saros 10R and Qrevo MaxV; other camera models may bootstrap differently and need validation.
- Firmware Updates
- Schedules (Routines/Scenes do work though)
- Schedules are experimental. A scheduled start has been reported on an S7; broader hardware compatibility, DST parity, and expired one-time jobs still need validation. See [schedule support](schedules.md). Routines/Scenes are separate.
- China-market devices do not work outside of China. Their firmware checks the region they are used in (via `rrcheck`), and after local onboarding they reject ordinary commands such as `get_status` with `-10002 / rrcheck access denied`. See [#81](https://github.com/Python-roborock/local_roborock_server/issues/81).
- Some users have gotten China-market vacuums working outside China on the official cloud by routing the robot's traffic through a VPN that exits in China (the robot's WAN IP is what matters, not the phone's). See [this comment](https://github.com/iobroker-community-adapters/ioBroker.mihome-vacuum/issues/842#issuecomment-1736230673). This has not been tested with this local server yet, so it may or may not help.
137 changes: 137 additions & 0 deletions docs/schedules.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
# Experimental schedule support

This implementation provides schedule storage, job APIs, time calculation, and dispatch. It does
not establish complete Roborock cloud compatibility on every model.

## Responsibilities and compatibility

Homebridge retains schedule switches, pause/delay decisions, original-time
restoration, daily reset, and recovery. The server provides the underlying APIs.

| Operation | Behavior in this branch |
| --- | --- |
| GET `/user/devices/{duid}/jobs` | Stored jobs with calculated UTC `nextFireTime` for enabled, valid jobs |
| POST to the collection | Persist a new job with a unique numeric ID |
| PUT/PATCH `/user/devices/{duid}/jobs/{id}` | Verify native enablement when supplied, then save; preserve omitted fields and unknown model fields |
| DELETE an item | Remove the stored job and its occurrence record |
| `get/set/upd/del_server_timer` | Forward unchanged to the robot, which owns these timer entries |
| Legacy `get/set/upd/del_timer` | Local compatibility view for jobs without a native timer name |
| Native scheduled execution | Verify the robot timer is on, then send `server_scheduled_start` with the complete settings entry |

A job's numeric `id` is different from the robot timer's string ID in
`param.params[0].name`. Imported or previously unsynchronized jobs can disagree with the native timer.
The server now reconciles enablement and still checks both before execution.
Native jobs are not duplicated in the legacy `get_timer` view; clients must read the jobs API to list native-linked jobs.

Time updates accept the existing-job JSON PUT used by Homebridge, without
requiring `id` or `nextFireTime` in the body. If `param` is supplied, it replaces
the previous object exactly, so app removal of an optional field is preserved.
Settings such as `clean_order_mode`, `mop_template_id`, `map_index`, room-list
strings, and unknown future options survive storage and native dispatch.
Invalid cron/timezone/body values are rejected. A persistence failure does not
receive a successful write acknowledgement.

## Enablement synchronization across clients

Native schedule on/off changes are synchronized by the server, independent of
whether Homebridge, LocalRock, the OEM app, or the dashboard made the change.
A forwarded `upd/set/del_server_timer` request prompts a fresh native timer read.
The request and the robot's reply remain unchanged; sending a request or receiving
an `ok` is not used as proof of the final state. No client-specific HTTP write is
required after a native toggle.

A background read also runs at startup and approximately every 30 seconds to
recover missed traffic, reconnects, and changes made directly over the LAN.
Successful reconciliation changes only `enabled` on existing, uniquely matched
jobs. It preserves IDs, cron/timezone, settings, unknown fields, and occurrence
claims. The dashboard's normal refresh shows the updated saved state. Other
clients see it on their next normal read; this is eventual synchronization,
not an unsolicited push into every app.

An HTTP job PUT/PATCH that supplies `enabled` verifies the matching native timer
before saving. A timer already in the requested state needs no extra write,
so the OEM app's native-update-then-PUT sequence remains compatible. A lost
acknowledgement is checked with one read-back, without repeating the write.
Time-only requests that omit `enabled` remain store-only edits.

Background reads and server edits share a per-vacuum lock. A native write that
overlaps a background read invalidates that read; edits/deletions during a read
are checked again before persistence. Missing, malformed, ambiguous or unreachable
timers leave the last saved state intact and never create replacement timers.
A normally polled, still-on timer does not re-enable a consumed one-time job.
An explicit native enable request can do so only after a fresh matching read;
that intent expires after two minutes. Unlinked server-only jobs retain their
existing behavior. Native timer time/settings edits are not imported into job
cron/settings by this enablement reconciliation.

## Execution and missed runs

The scheduler evaluates five-field cron expressions in each job's IANA timezone.
It checks approximately every 20 seconds, allowing less than 60 seconds of normal
dispatch latency. Startup establishes a fresh baseline; suspended/late ticks do
not drain historical jobs. Recurring jobs remain enabled for future occurrences.

Before dispatch, the server saves an occurrence claim in the persistent inventory
under `schedule_occurrences`. A repeated tick, restart, or backward clock change
cannot dispatch the same claimed occurrence again. If that write fails, no start
is attempted. This is an at-most-once policy: a crash after claiming but before
sending can miss a clean. Run only one server process against an inventory; the
inventory lock does not coordinate multiple containers or external file editors.
Cloud re-import replaces schedule definitions, so back up local edits before
refreshing. Occurrence claims are retained across that refresh.

A fresh native timer read must find exactly one matching `on` entry. Off, missing,
ambiguous, malformed, or unreachable timer state prevents a start. After that
network wait, dispatch rechecks the stored job and its deadline, so a concurrent
time edit or deletion cancels stale work. The remaining read-to-start race is
resolved by the robot's native command; real firmware behavior needs testing.

A refused or timed-out native scheduled start is never retried as `app_start` or
`app_segment_clean`, and action-locked native starts are not automatically retried.
A robot refusal can mean a disabled/deleted timer; substituting an ordinary clean
could bypass that state. Legacy jobs retain upstream's separate cleaning-command
path; they do not establish native timer support on other firmware.

## Provisional behavior and remaining validation

- Native dispatch preserves the job's method and complete settings entry.
Validate room selection, map, cleaning order, mop mode and history on each model.
- DST policy currently skips nonexistent spring-forward times and runs only the
first occurrence of an ambiguous fall-back time. Automated tests cover this
policy; matching cloud behavior has not been established.
- One-time jobs are consumed when evaluated as due, including when dispatch
subsequently fails. Expired imported one-time jobs and extended downtime need
further investigation: a five-field cron has no year and can match again in a
later year. Begin hardware testing with recurring jobs.
- Test create/edit/delete through the actual app, disabled/missing native timers,
robot reboot, server/container restart, offline/reconnect, and busy/DND refusal.
- B01 and other scheduling protocols require separate model validation.
Scene/routine scheduling is separate from these device job routes.
- A startup log saying a job task was accepted is not proof of a clean; check
subsequent timer-read/start replies, robot status, and cleaning history.

## First hardware test

Build the selected Git commit into a versioned Docker image. Run `uv sync --locked --extra dev`
and `uv run pytest -q` to execute the Python test suite before deployment.

1. Prepare the runtime configuration, DNS/certificate path, data backup, and
explicit cloud-to-local onboarding procedure. Start with one robot.
2. Import current jobs and verify every numeric job ID maps to the expected
native timer name. Confirm local jobs reads and robot timer reads separately.
3. Disable a recurring test schedule through Homebridge. Confirm the robot timer
reads off and the saved job becomes disabled without a separate HTTP update.
Re-enable it and confirm both states agree and a later occurrence runs once.
4. Test a room schedule and a whole-home schedule. Compare settings, rooms, map,
and history against the app. A refusal should stop dispatch, with no fallback
ordinary clean.
5. Exercise Homebridge delay and cancellation/restoration. Confirm only intended
times change, settings survive, and each resulting occurrence runs once.
6. Disconnect the robot across a due time and reconnect. Verify no replay, then
a future occurrence. Repeat with a server restart across the due time and
after a run. Test pending edits while a timer read is delayed.

Record image tag/commit, model and firmware, timezone, expected time, actual time,
timer state, settings, and relevant sanitized replies for each result. Returning
to the cloud requires the appropriate onboarding transition; stopping Docker is
not an automatic cloud/local switch.
1 change: 1 addition & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ nav:
- Reference:
- Log Retention: logging.md
- Known Limitations: known_limitations.md
- Schedule Support (Experimental): schedules.md
- Scene Validity Reports: scene_validity.md
- Tested Vacuums: tested_vacuums.md
- Reverse Proxy: reverse_proxy.md
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,16 @@

import json
import re
import time
from typing import Any
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError

from shared.constants import DEFAULT_TIMEZONE
from shared.context import ServerContext
from shared.data_helpers import as_bool
from shared.http_helpers import wrap_response
from shared.schedule_runner import CronError, parse_cron
from shared.schedule_store import delete_job, list_jobs, upsert_job
from shared.schedule_runner import parse_cron
from shared.schedule_store import SettingsError, delete_job, list_jobs, native_timer_name, upsert_job
from shared.native_schedule_sync import TimerSyncError, sync_timer

from .service import device_jobs_payload

Expand Down Expand Up @@ -45,7 +46,16 @@ def _json_body(body_params: dict[str, list[str]]) -> dict[str, Any]:
continue
if isinstance(parsed, dict):
return parsed
return {}
raise ValueError("request body must be a JSON object")


def _validate_zone(value: Any) -> str:
name = str(value or "").strip()
try:
ZoneInfo(name)
except (ZoneInfoNotFoundError, ValueError) as exc:
raise ValueError("timeZoneId must be a valid IANA timezone") from exc
return name


def _parse_param(value: Any) -> dict[str, Any] | None:
Expand All @@ -68,65 +78,120 @@ def build_create(
clean_path: str,
) -> dict[str, Any]:
duid = _COLLECTION_RE.fullmatch(clean_path.rstrip("/")).group(1) # type: ignore[union-attr]
body = _json_body(body_params)
cron = str(body.get("cron") or "").strip()
try:
body = _json_body(body_params)
cron = str(body.get("cron") or "").strip()
parse_cron(cron)
except CronError as exc:
return _error(400, f"invalid cron: {exc}")
zone = _validate_zone(body.get("timeZoneId", getattr(ctx, "timezone", "") or DEFAULT_TIMEZONE))
except ValueError as exc:
return _error(400, str(exc))
param = _parse_param(body.get("param"))
if body.get("param") is not None and param is None:
return _error(400, "param must be a JSON object")
job_id = body.get("id") or int(time.time())
created = upsert_job(
ctx,
duid,
job_id=job_id,
cron=cron,
enabled=as_bool(body.get("enabled", True), True),
time_zone=str(body.get("timeZoneId") or getattr(ctx, "timezone", "") or DEFAULT_TIMEZONE),
repeated=as_bool(body.get("repeated", True), True),
param=param,
)
try:
created = upsert_job(
ctx, duid, job_id=body.get("id"), cron=cron,
enabled=as_bool(body.get("enabled", True), True), time_zone=zone,
repeated=as_bool(body.get("repeated", True), True), param=param,
extra_fields=body, create_only=True,
)
except ValueError as exc:
return _error(409, str(exc))
except OSError:
return _error(500, "unable to persist schedule")
return wrap_response(created)


def match_update(path: str, method: str = "GET") -> bool:
return method.upper() in ("PUT", "PATCH") and bool(_ITEM_RE.fullmatch(path.rstrip("/")))


def build_update(
ctx: ServerContext,
_query_params: dict[str, list[str]],
body_params: dict[str, list[str]],
clean_path: str,
) -> dict[str, Any]:
match_ = _ITEM_RE.fullmatch(clean_path.rstrip("/"))
duid, job_id = match_.group(1), match_.group(2) # type: ignore[union-attr]
existing = next((job for job in list_jobs(ctx, duid) if str(job.get("id")) == job_id), None)
if existing is None:
return _error(404, "schedule not found")
body = _json_body(body_params)
cron = str(body.get("cron") or existing.get("cron") or "").strip()
class ScheduleUpdateError(ValueError):
def __init__(self, code: int, message: str) -> None:
super().__init__(message)
self.code = code


def _prepare_update(ctx, duid, job_id, body_params):
matches = [job for job in list_jobs(ctx, duid) if str(job.get("id")) == job_id]
if not matches:
raise ScheduleUpdateError(404, "schedule not found")
if len(matches) != 1:
raise ScheduleUpdateError(409, "duplicate schedule IDs")
existing = matches[0]
try:
body = _json_body(body_params)
cron = str(body.get("cron", existing.get("cron")) or "").strip()
parse_cron(cron)
except CronError as exc:
return _error(400, f"invalid cron: {exc}")
zone = _validate_zone(body["timeZoneId"]) if "timeZoneId" in body else ""
except ValueError as exc:
raise ScheduleUpdateError(400, str(exc)) from exc
param = _parse_param(body.get("param")) if "param" in body else None
if "param" in body and param is None:
return _error(400, "param must be a JSON object")
updated = upsert_job(
ctx,
duid,
job_id=job_id,
cron=cron,
raise ScheduleUpdateError(400, "param must be a JSON object")
values = dict(
job_id=job_id, cron=cron,
enabled=as_bool(body.get("enabled", existing.get("enabled", True)), True),
time_zone=str(body.get("timeZoneId") or ""),
time_zone=zone,
repeated=as_bool(body["repeated"], True) if "repeated" in body else None,
param=param,
override_time_zone=bool(body.get("timeZoneId")),
param=param, override_time_zone=bool(zone), extra_fields=body, expected_job=existing,
)
return wrap_response(updated)
return existing, body, values


def _save_update(ctx, duid, values):
try:
return wrap_response(upsert_job(ctx, duid, **values))
except ValueError as exc:
return _error(409, str(exc))
except OSError:
return _error(500, "unable to persist schedule")


def build_update(ctx, _query_params, body_params, clean_path):
match_ = _ITEM_RE.fullmatch(clean_path.rstrip("/"))
duid, job_id = match_.group(1), match_.group(2)
try:
_, _, values = _prepare_update(ctx, duid, job_id, body_params)
except ScheduleUpdateError as exc:
return _error(exc.code, str(exc))
return _save_update(ctx, duid, values)


async def build_update_synced(ctx, _query_params, body_params, clean_path, coordinator):
"""Authenticated HTTP edits share the same native state as every MQTT client."""
match_ = _ITEM_RE.fullmatch(clean_path.rstrip("/"))
duid, job_id = match_.group(1), match_.group(2)
async with coordinator.lock(duid):
try:
existing, body, values = _prepare_update(ctx, duid, job_id, body_params)
candidate = {**existing}
if values["param"] is not None:
candidate["param"] = values["param"]
name = native_timer_name(candidate) if "enabled" in body else None

def check_current():
jobs = list_jobs(ctx, duid)
if [job for job in jobs if str(job.get("id")) == job_id] != [existing]:
raise TimerSyncError("Schedule changed during timer verification; read it again", 409)
for other in jobs:
if str(other.get("id")) != job_id and native_timer_name(other) == name:
raise TimerSyncError("Multiple schedules reference this native timer", 409)

if name is not None:
check_current()
await sync_timer(ctx, duid, name, values["enabled"], check_current=check_current)
check_current()
result = _save_update(ctx, duid, values)
if name is not None and not result.get("success"):
result["msg"] = "Robot timer was verified, but the schedule could not be saved; refresh before retrying"
return result
except ScheduleUpdateError as exc:
return _error(exc.code, str(exc))
except SettingsError as exc:
return _error(409, str(exc))
except TimerSyncError as exc:
return _error(exc.status, str(exc))


def match_delete(path: str, method: str = "GET") -> bool:
Expand All @@ -141,6 +206,9 @@ def build_delete(
) -> dict[str, Any]:
match_ = _ITEM_RE.fullmatch(clean_path.rstrip("/"))
duid, job_id = match_.group(1), match_.group(2) # type: ignore[union-attr]
if not delete_job(ctx, duid, job_id):
return _error(404, "schedule not found")
try:
if not delete_job(ctx, duid, job_id):
return _error(404, "schedule not found")
except OSError:
return _error(500, "unable to persist schedule")
return wrap_response({"id": job_id})
Original file line number Diff line number Diff line change
Expand Up @@ -656,6 +656,8 @@ def device_jobs_payload(ctx: ServerContext, device_id: str) -> list[dict[str, An
upcoming = next_fire_time_utc(payload, default_timezone=str(getattr(ctx, "timezone", "") or ""))
if upcoming is not None:
payload["nextFireTime"] = upcoming.strftime("%Y-%m-%dT%H:%M:%S.000+00:00")
else:
payload.pop("nextFireTime", None)
schedules.append(payload)
return schedules

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

import argparse
import asyncio
import copy
from dataclasses import asdict, is_dataclass
from datetime import datetime, timezone
import json
Expand Down Expand Up @@ -757,6 +758,12 @@ def _merge_existing_inventory_mutations(

merged = dict(cloud_inventory)

# Refreshing cloud definitions must not erase the local scheduler's record
# of occurrences already attempted (including a clean with a lost reply).
occurrences = existing_inventory.get("schedule_occurrences")
if isinstance(occurrences, dict):
merged["schedule_occurrences"] = copy.deepcopy(occurrences)

rooms = _merge_record_lists_by_identity(
_inventory_rooms(merged),
_inventory_rooms(existing_inventory),
Expand Down
Loading