Skip to content
Closed
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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ Additional docs:
- [Tested vacuums](docs/tested_vacuums.md)
- [Home Assistant](docs/home_assistant.md) for the add-on install path and integration setup
- [Mobile App Options](docs/roborock_app.md)
- [Voice packs](docs/voice_packs.md) for changing the robot's voice without internet access
- [Custom MQTT](docs/custom_mqtt.md)
- [Custom certificate management](docs/custom_cert_management.md)

Expand Down
7 changes: 7 additions & 0 deletions config.example.toml
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,10 @@ username = ""
password = ""
realm = "api-roborock.example.com"
ttl = 86400

[voice_packs]
# Voice packs for robots without internet access (see docs/voice_packs.md). mirror fetches
# Roborock's list and each pack the first time a robot or app asks, then serves the copies kept
# under data_dir/voice_packs. offline serves only those copies and never contacts Roborock.
# disabled turns the /voice-pkg routes off.
mode = "mirror" # mirror | offline | disabled
1 change: 1 addition & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ If you want to support this project, next time you buy a Roborock, use one of my
- [Known limitations](known_limitations.md)
- [Home Assistant](home_assistant.md)
- [Mobile App Options](roborock_app.md)
- [Voice Packs](voice_packs.md)
- [Updating](updating.md)
- [Tested vacuums](tested_vacuums.md)
- [Reverse proxy](reverse_proxy.md)
Expand Down
65 changes: 65 additions & 0 deletions docs/voice_packs.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# Voice Packs

A robot changes its voice when an app sends it `dnld_install_sound` with a URL to download the pack
from. The official Roborock app takes that URL from Roborock's own list, so the robot is told to fetch
the pack from Roborock's servers. A robot whose internet access is blocked, as it usually is in a
local setup, cannot do that and the voice change fails.

This server keeps its own copy of the list and the packs and serves them from your stack, so a client
can hand the robot a URL on your server instead.

## How it works

- `GET https://<stack_fqdn>/voice-pkg/<bucket>/info` returns Roborock's list for a product, with every
pack, picture and preview URL rewritten to point at this server.
- `GET https://<stack_fqdn>/voice-pkg/<bucket>/{package,pic,wav}/<file>` serves a file. The first
request fetches it from Roborock, checks it against the checksum Roborock's storage sends with it (when there is one), and keeps it under
`<data_dir>/voice_packs/<bucket>/`; later requests are served from that copy.
- The first time a bucket's list is asked for, the server starts downloading every pack in it in the
background, so later voice changes need no internet at all.
- The list is refreshed from Roborock at most once a day. When Roborock can't be reached, the last
stored list is used.

The routes need no login, as the robot downloads without credentials (Roborock's own copies are
public too). Only bucket names and plain file names from the list are accepted.

The upstream host follows `network.region` (`eu`, `us` or `cn`; other regions use `eu`).

## Buckets

Roborock keeps each product's voice packs in a folder named after the product's code name in its
device plugin:

| Bucket | Models |
|---|---|
| `vida` | Saros 20 Neo (`roborock.vacuum.a295`, `roborock.vacuum.a296`) |

Other products' buckets can be found in their device plugin (the `bucket` value next to the
voice-pack page). Add them here when you confirm one.

## Clients

The official Roborock app reads the list from Roborock directly, so it still sends Roborock's URLs
and voice changes from it keep failing on a robot without internet access. A client that wants to
use this mirror reads `/voice-pkg/<bucket>/info` and sends the robot:

```json
{"method": "dnld_install_sound", "params": {"sid": <voice_id>, "url": "<voice_pkg_url>", "md5": "<voice_pkg_md5>", "sver": <version>}}
```

with the values of one `voice_list` entry, then follows progress with `get_sound_progress`.
`voice_pkg_md5` is passed to the robot exactly as listed (it is not the MD5 of the file).

## Configuration

```toml
[voice_packs]
mode = "mirror" # mirror | offline | disabled
```

- `mirror` (default): fetch from Roborock on first use and keep copies, as described above.
- `offline`: serve only the copies already stored and never contact Roborock. Use this after the
packs have been mirrored once, or after copying a `voice_packs` folder into `<data_dir>` yourself.
- `disabled`: the `/voice-pkg` routes answer 404.

In the Home Assistant add-on the same choice is the `voice_packs_mode` option.
1 change: 1 addition & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ nav:
- Integrations:
- Mobile App Options: roborock_app.md
- Camera (Live Video): camera.md
- Voice Packs: voice_packs.md
- Reference:
- Log Retention: logging.md
- Known Limitations: known_limitations.md
Expand Down
2 changes: 2 additions & 0 deletions roborock_local_server_addon/DOCS.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ It publishes two TLS ports directly:

For camera live view, set `turn_mode` to `provided` to start coturn inside the add-on. It uses `stack_fqdn` as the advertised host and generates a persistent password when `turn_password` is blank. Set `turn_mode` to `external` with `turn_host`, `turn_port`, `turn_username`, `turn_password`, and optionally `turn_realm` to advertise your existing relay. `disabled` leaves TURN off. In provided mode, allow UDP 3478 and 49160-49179 between the robot, viewer, and Home Assistant host.

`voice_packs_mode` controls the voice-pack mirror for robots without internet access: `mirror` (default) fetches Roborock's packs on first use and keeps copies, `offline` serves only stored copies, `disabled` turns it off. See the Voice Packs page of the documentation.

Before choosing the TLS mode, check the tested-vacuum certificate guidance in `docs/tested_vacuums.md`. Different models may need `zerossl`, `actalis`, or your own certificate chain. For most users, prefer `zerossl`. Use `actalis` mainly for older vacuums or when your model is already known to need it.

The add-on always runs the embedded MQTT broker and keeps the topic bridge enabled.
Expand Down
2 changes: 2 additions & 0 deletions roborock_local_server_addon/config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ options:
turn_password: ""
turn_realm: ""
turn_ttl: 86400
voice_packs_mode: "mirror"
schema:
stack_fqdn: str
https_port: port
Expand Down Expand Up @@ -119,3 +120,4 @@ schema:
turn_password: password?
turn_realm: str?
turn_ttl: int?
voice_packs_mode: list(mirror|offline|disabled)?
19 changes: 19 additions & 0 deletions src/roborock_local_server/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,20 @@ class TurnConfig:
ttl: int = 86400


VOICE_PACK_MODES = ("mirror", "offline", "disabled")


@dataclass(frozen=True)
class VoicePacksConfig:
"""Voice packs served to robots that cannot reach Roborock (see docs/voice_packs.md).

``mirror`` fetches Roborock's list and packs on first use and keeps copies; ``offline`` serves
only the copies already stored and never contacts Roborock; ``disabled`` turns the routes off.
"""

mode: str = "mirror"


@dataclass(frozen=True)
class AppConfig:
network: NetworkConfig
Expand All @@ -113,6 +127,7 @@ class AppConfig:
admin: AdminConfig
turn: TurnConfig = TurnConfig()
logging: LoggingConfig = LoggingConfig()
voice_packs: VoicePacksConfig = VoicePacksConfig()


@dataclass(frozen=True)
Expand Down Expand Up @@ -259,6 +274,7 @@ def load_config(path: str | Path) -> AppConfig:
logging = _get_section(parsed, "logging")
tls = _get_section(parsed, "tls")
admin = _get_section(parsed, "admin")
voice_packs = _get_section(parsed, "voice_packs")
turn = _get_section(parsed, "turn")
turn_mode = str(turn.get("mode", "external" if _as_bool(turn.get("enabled"), False) else "disabled")).strip().lower()
broker_mode = str(broker.get("mode", "embedded")).strip().lower()
Expand Down Expand Up @@ -368,6 +384,7 @@ def load_config(path: str | Path) -> AppConfig:
realm=str(turn.get("realm", "") or turn.get("host", "")).strip(),
ttl=_as_int(turn.get("ttl"), "turn.ttl", 86400),
),
voice_packs=VoicePacksConfig(mode=str(voice_packs.get("mode", "mirror")).strip().lower()),
)

if len(config.admin.session_secret) < 24:
Expand All @@ -378,6 +395,8 @@ def load_config(path: str | Path) -> AppConfig:
if config.broker.mode == "external":
_require_non_empty(config.broker.host, "broker.host")

if config.voice_packs.mode not in VOICE_PACK_MODES:
raise ValueError("voice_packs.mode must be 'mirror', 'offline', or 'disabled'")
if config.turn.mode not in {"disabled", "provided", "external"}:
raise ValueError("turn.mode must be 'disabled', 'provided', or 'external'")
if config.turn.mode != "disabled":
Expand Down
7 changes: 7 additions & 0 deletions src/roborock_local_server/ha_addon.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
"turn_password": "",
"turn_realm": "",
"turn_ttl": 86400,
"voice_packs_mode": "mirror",
}

_HOST_RE = re.compile(r"^[a-z0-9.-]+$")
Expand Down Expand Up @@ -258,6 +259,9 @@ def _render_config_toml(
acme_eab_kid_file = str(acme_eab_kid_path) if acme_server == "actalis" else ""
acme_eab_hmac_key_file = str(acme_eab_hmac_key_path) if acme_server == "actalis" else ""

voice_packs_mode = str(merged.get("voice_packs_mode") or "mirror").strip().lower()
if voice_packs_mode not in {"mirror", "offline", "disabled"}:
raise ValueError("voice_packs_mode must be mirror, offline, or disabled")
turn_mode = str(merged.get("turn_mode") or "disabled").strip().lower()
if turn_mode not in {"disabled", "provided", "external"}:
raise ValueError("turn_mode must be disabled, provided, or external")
Expand Down Expand Up @@ -373,6 +377,9 @@ def _render_config_toml(
f"realm = {_toml_string(turn_realm)}",
f"ttl = {turn_ttl}",
"",
"[voice_packs]",
f"mode = {_toml_string(voice_packs_mode)}",
"",
]
)
secrets_to_write: dict[Path, str] = {}
Expand Down
60 changes: 59 additions & 1 deletion src/roborock_local_server/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from urllib.parse import parse_qs

from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse, Response
from fastapi.responses import FileResponse, JSONResponse, Response
from python_multipart.exceptions import MultipartParseError
import uvicorn
from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware
Expand All @@ -32,6 +32,7 @@
from .config import AppConfig, AppPaths, load_config, resolve_paths
from .log_retention import configure_jsonl_logging
from .turn_relay import EmbeddedTurnRelay
from .voice_packs import VoicePackError, VoicePackMirror, rewrite_list as rewrite_voice_list
from .standalone_admin import register_standalone_admin_routes
from .backend import (
MqttTlsProxy,
Expand Down Expand Up @@ -348,6 +349,9 @@ def __init__(
self.config = config
self.paths = paths
self.enable_standalone_admin = bool(enable_standalone_admin)
self.voice_packs = VoicePackMirror(paths.data_dir, config.network.region, offline=config.voice_packs.mode == "offline")
self._voice_prefetch_started: set[str] = set()
self._voice_prefetch_tasks: set[asyncio.Task] = set()

self.root_logger = logging.getLogger("roborock_local_server")
self.root_logger.setLevel(logging.INFO)
Expand Down Expand Up @@ -1842,6 +1846,33 @@ async def ui_vacuums(request: Request) -> JSONResponse:
self._require_admin(request)
return JSONResponse(self._ui_vacuums_payload())

# Voice packs, mirrored from Roborock for robots that can't reach it (see voice_packs.py).
# Public like Roborock's own copies: the robot downloads them without credentials.
@app.get("/voice-pkg/{bucket}/info")
async def voice_pack_list(bucket: str) -> Response:
if self.config.voice_packs.mode == "disabled":
return JSONResponse({"error": "Not Found"}, status_code=404)
try:
info = await self.voice_packs.get_list(bucket)
except VoicePackError as exc:
return JSONResponse({"error": str(exc)}, status_code=exc.status)
if not self.voice_packs.offline and bucket not in self._voice_prefetch_started:
# Keep a copy of every pack from the first time the list is asked for.
self._start_voice_prefetch(bucket)
port = self.config.network.advertised_https_port
base_url = f"https://{self.config.network.stack_fqdn}" + ("" if port in (0, 443) else f":{port}")
return JSONResponse(rewrite_voice_list(info, base_url, bucket))

@app.get("/voice-pkg/{bucket}/{kind}/{name}")
async def voice_pack_file(bucket: str, kind: str, name: str) -> Response:
if self.config.voice_packs.mode == "disabled":
return JSONResponse({"error": "Not Found"}, status_code=404)
try:
path = await self.voice_packs.get_file(bucket, kind, name)
except VoicePackError as exc:
return JSONResponse({"error": str(exc)}, status_code=exc.status)
return FileResponse(path)

@app.api_route("/", methods=list(ALL_HTTP_METHODS))
async def root_handler(request: Request) -> Response:
if self._is_standalone_route_path(request.url.path):
Expand Down Expand Up @@ -1997,8 +2028,35 @@ async def start(self) -> None:
if self._uses_local_tls() and self.config.tls.mode == "cloudflare_acme":
self._renew_task = asyncio.create_task(self._renew_loop(), name="tls-renew-loop")

def _start_voice_prefetch(self, bucket: str) -> None:
"""Download every pack of [bucket] in the background; a failed run may be started again later."""
self._voice_prefetch_started.add(bucket)
task = asyncio.create_task(self.voice_packs.prefetch(bucket), name=f"voice-prefetch-{bucket}")
self._voice_prefetch_tasks.add(task)

def done(t: asyncio.Task) -> None:
self._voice_prefetch_tasks.discard(t)
if t.cancelled():
self._voice_prefetch_started.discard(bucket)
return
exc = t.exception()
if exc is not None:
self._voice_prefetch_started.discard(bucket)
self.root_logger.warning("Voice packs: prefetch of %s failed: %s", bucket, exc)
return
result = t.result()
if result.get("failed"):
self._voice_prefetch_started.discard(bucket)
self.root_logger.info(
"Voice packs: %s has %s files stored, %s failed", bucket, result.get("stored"), len(result.get("failed") or {})
)

task.add_done_callback(done)

async def stop(self) -> None:
self._stop_event.set()
for task in list(self._voice_prefetch_tasks):
task.cancel()
self._turn_relay.stop()
self._refresh_turn_health()
if self._renew_task is not None:
Expand Down
Loading