diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md new file mode 100644 index 0000000..809ddb0 --- /dev/null +++ b/.claude/CLAUDE.md @@ -0,0 +1,75 @@ +# HA Controller — guidance for Claude Code + +HA Controller turns the Waveshare ESP32-S3-Touch-AMOLED-1.75 round touch screen into a Home Assistant remote. +It is a custom integration with a sidebar panel, an ESPHome firmware and a GitHub Pages web installer. + +## Rules + +- English only: code, comments, docs and commit messages. +- One version for the whole repository. Change it only with `.github/scripts/.venv/bin/python .github/scripts/versioning.py bump X.Y.Z`; `.github/scripts/.venv/bin/python .github/scripts/versioning.py check [--tag vX.Y.Z]` verifies it (CI job `versions`). +- The protocol is defined in `docs/protocol/README.md` and pinned by `docs/protocol/fixtures/`. +- The repository root holds no files except README.md, LICENSE, hacs.json and .gitignore. Put every new file in the folder that owns it (see the repository map). +- TDD: write the failing test first, then the code. +- Never commit `esphome/secrets.yaml`. +- Specs and plans live in `docs/superpowers/`. + +## Repository map + +| Path | Content | +|---|---| +| `docs/` | User and developer documentation. `docs/protocol/` holds the protocol doc (`README.md`) and its shared fixtures (`fixtures/`), the cross-language contract. `docs/superpowers/` holds this spec and the plans. | +| `custom_components/` | Everything for the Home Assistant integration. HACS allows a single directory here, so development files live inside it, or next to it as plain files. | +| `custom_components/ha_controller/` | The integration (Python). Also holds `emoji.json` (canonical emoji list, also read by the firmware build and the panel), `brand/`, `tests/` (pytest), and `frontend/` (panel source in TypeScript, Lit and Vite, built to `frontend/dist/`, which is git-ignored). | +| `custom_components/pyproject.toml`, `requirements_test.txt`, `__init__.py` | Python test and lint configuration for the integration. The empty `__init__.py` keeps test imports under `custom_components.ha_controller`. | +| `esphome/` | Everything for the firmware: device config, packages, simulator config, external components, C++ host tests, web installer page, `requirements.txt` (ESPHome version) and its venv (`esphome/.venv`, git-ignored) | +| `.github/workflows/` | CI, firmware CI, release | +| `.github/scripts/` | Release and repository-check tooling (versioning, packaging, GitHub Pages site builder, docs and fixture checks), with its own `pyproject.toml`, `requirements.txt` and `tests/` | +| `.claude/` | `CLAUDE.md`, Claude Code skills and agents | +| `3D_models/`, `files/` | Existing enclosure models (unchanged) | + +## Commands + +```bash +python3.14 -m venv .github/scripts/.venv +.github/scripts/.venv/bin/pip install -r .github/scripts/requirements.txt +.github/scripts/.venv/bin/pytest .github/scripts/tests +.github/scripts/.venv/bin/ruff check .github/scripts +.github/scripts/.venv/bin/python .github/scripts/make_brand_icon.py # regenerate brand icons +.github/scripts/.venv/bin/python .github/scripts/versioning.py check # verify the single repository version +.github/scripts/.venv/bin/python .github/scripts/versioning.py check --tag vX.Y.Z # also verify a release tag +.github/scripts/.venv/bin/python .github/scripts/versioning.py bump X.Y.Z # set the version in every source + +# Integration (own venv, run from the repository root) +python3.14 -m venv custom_components/.venv +custom_components/.venv/bin/pip install -r custom_components/requirements_test.txt +custom_components/.venv/bin/pytest custom_components/ha_controller/tests +custom_components/.venv/bin/ruff check custom_components + +# Firmware (own venv, run from the repository root) +python3.13 -m venv esphome/.venv +esphome/.venv/bin/pip install -r esphome/requirements.txt +cmake -S esphome/tests -B esphome/tests/build && cmake --build esphome/tests/build +ctest --test-dir esphome/tests/build --output-on-failure + +# Firmware (needs SDL2 for the simulator: brew install sdl2 / apt install libsdl2-dev) +esphome/.venv/bin/esphome compile esphome/ha-controller.yaml +esphome/.venv/bin/esphome compile esphome/simulator.yaml +esphome/.venv/bin/esphome run esphome/simulator.yaml # desktop simulator, API on port 6053 + +# Panel (Node 24, run from the repository root) +npm --prefix custom_components/ha_controller/frontend ci +npm --prefix custom_components/ha_controller/frontend test +npm --prefix custom_components/ha_controller/frontend run typecheck +npm --prefix custom_components/ha_controller/frontend run build +npm --prefix custom_components/ha_controller/frontend run dev # panel against a mock hass +``` + +## Skills and agents + +- Skill `protocol-change` (`.claude/skills/protocol-change/`): checklist for any change that crosses the Home Assistant ↔ screen boundary. +- Skill `firmware-dev` (`.claude/skills/firmware-dev/`): commands, simulator loop and rules for the ESPHome firmware and LVGL code. +- Skill `add-widget` (`.claude/skills/add-widget/`): end-to-end checklist for a new block widget or custom item kind. +- Skill `release` (`.claude/skills/release/`): cutting a release and changing the release pipeline (versions, workflow, Pages installer, HACS packaging, OTA URLs). +- Agent `firmware-reviewer` (`.claude/agents/firmware-reviewer.md`): reviews changes under `esphome/` for ESPHome/LVGL correctness, memory and hardware safety. +- Agent `protocol-guardian` (`.claude/agents/protocol-guardian.md`): reviews a diff for protocol consistency across docs, fixtures, Python, TypeScript and C++. +- Agent `ha-integration-reviewer` (`.claude/agents/ha-integration-reviewer.md`): reviews integration changes against Home Assistant development rules. diff --git a/.claude/agents/firmware-reviewer.md b/.claude/agents/firmware-reviewer.md new file mode 100644 index 0000000..e5cb94a --- /dev/null +++ b/.claude/agents/firmware-reviewer.md @@ -0,0 +1,17 @@ +--- +name: firmware-reviewer +description: Reviews changes under esphome/ for ESPHome/LVGL correctness, memory and hardware safety. Use before merging firmware changes. +tools: Read, Grep, Glob, Bash +--- + +You review firmware changes. Read the diff (`git diff main...HEAD -- esphome`), then check: + +- No blocking calls in `loop`, except the OTA action. +- LVGL objects are deleted with their views, with animations cancelled first. +- No ESPHome callbacks are registered per view. +- JSON is parsed defensively (missing keys, wrong types, oversized input). +- Pins and I²C addresses match `docs/hardware.md`. +- New pure logic has host tests in `esphome/tests/`. +- Both configs compile: `esphome/.venv/bin/esphome compile esphome/ha-controller.yaml` and `esphome/simulator.yaml`. + +Report each finding as `file:line — issue — fix`. Say so when there is none. diff --git a/.claude/agents/ha-integration-reviewer.md b/.claude/agents/ha-integration-reviewer.md new file mode 100644 index 0000000..566d427 --- /dev/null +++ b/.claude/agents/ha-integration-reviewer.md @@ -0,0 +1,19 @@ +--- +name: ha-integration-reviewer +description: Reviews changes under custom_components/ha_controller and custom_components/ha_controller/tests against Home Assistant development rules. Use before merging integration changes. +tools: Read, Grep, Glob, Bash +--- + +You review changes to the Home Assistant integration. Read the diff (`git diff main...HEAD -- custom_components`), then check: + +- Async only: no blocking I/O (file access, `requests`, `time.sleep`) in the event loop. +- State lives in `entry.runtime_data`; no new `hass.data` globals beyond the panel flags. +- Every listener and timer is removed on unload. +- Event handlers filter by `device_id`. +- Service call errors are caught. +- Constants come from `const.py`, not literals. +- User-facing strings are English and live in `strings.json` and `translations/en.json`. +- Every branch has a test. +- A change that crosses the Home Assistant ↔ screen boundary goes through the `protocol-change` skill. + +Report findings as `file:line — issue — fix`, one per line. Say so when there are none. diff --git a/.claude/agents/protocol-guardian.md b/.claude/agents/protocol-guardian.md new file mode 100644 index 0000000..b51edb3 --- /dev/null +++ b/.claude/agents/protocol-guardian.md @@ -0,0 +1,15 @@ +--- +name: protocol-guardian +description: Reviews a diff for consistency of the HA ↔ screen protocol across docs/protocol/README.md, docs/protocol/fixtures, the integration (Python), the panel model (TypeScript) and the firmware parsers (C++). Use after any protocol-related change and before merging. +tools: Read, Grep, Glob, Bash +--- + +You review protocol changes. Read the diff (`git diff main...HEAD`), then check: + +- Field names, error codes, limits and constants are identical in `docs/protocol/README.md`, the Python integration, the TypeScript model and the C++ parsers. +- Fixtures under `docs/protocol/fixtures/` are updated, and each invalid layout fixture still breaks exactly one rule. +- Golden `rev` values are recomputed (see `docs/protocol/README.md`). +- `PROTOCOL_VERSION` is bumped in `const.py` and `ha_controller.h` on breaking changes. +- `docs/protocol/README.md` describes the new behaviour. + +Output a list of `file:line — inconsistency — fix`, or "Protocol consistent". diff --git a/.claude/skills/add-widget/SKILL.md b/.claude/skills/add-widget/SKILL.md new file mode 100644 index 0000000..e387128 --- /dev/null +++ b/.claude/skills/add-widget/SKILL.md @@ -0,0 +1,23 @@ +--- +name: add-widget +description: Use when adding a new block widget or custom item kind (e.g. switch, cover, fan, media volume) end-to-end. +--- + +# Add a widget + +A widget crosses the Home Assistant ↔ screen boundary, so start with the `protocol-change` skill and keep its checklist open. Then: + +1. Protocol doc and fixtures: `docs/protocol/README.md` and `docs/protocol/fixtures/` (recompute golden `rev` values). +2. `ENTITY_BLOCK_DOMAINS` / `ITEM_KINDS` in `custom_components/ha_controller/const.py`, and the panel model in `custom_components/ha_controller/frontend/`. +3. The state builder and the control mapping in the integration. +4. The panel editor options and the preview. +5. The C++ parser enum and the view under `esphome/components/ha_controller/` (with host tests; see the `firmware-dev` skill). +6. `docs/configuration.md`. +7. Run all suites and both firmware compiles: + - `custom_components/.venv/bin/pytest custom_components/ha_controller/tests` + - `.github/scripts/.venv/bin/pytest .github/scripts/tests` + - `npm --prefix custom_components/ha_controller/frontend test` + - `ctest --test-dir esphome/tests/build --output-on-failure` + - `esphome compile` for `esphome/ha-controller.yaml` and `esphome/simulator.yaml` + +Finish with the `protocol-guardian` and `firmware-reviewer` agents. diff --git a/.claude/skills/firmware-dev/SKILL.md b/.claude/skills/firmware-dev/SKILL.md new file mode 100644 index 0000000..da87b56 --- /dev/null +++ b/.claude/skills/firmware-dev/SKILL.md @@ -0,0 +1,47 @@ +--- +name: firmware-dev +description: Use when building, flashing, simulating or changing the ESPHome firmware (esphome/), including LVGL UI code. +--- + +# Firmware development + +The firmware is ESPHome with LVGL in `esphome/`. Hardware facts are in `docs/hardware.md`; the manual hardware checklist is in `docs/development.md`. + +## Commands + +Run from the repository root: + +```bash +# Host tests (pure C++ logic) +cmake -S esphome/tests -B esphome/tests/build && cmake --build esphome/tests/build +ctest --test-dir esphome/tests/build --output-on-failure + +# Compile both configs (long; run in the background) +esphome/.venv/bin/esphome compile esphome/ha-controller.yaml +esphome/.venv/bin/esphome compile esphome/simulator.yaml + +# Flash over USB-C, or run the SDL simulator +esphome/.venv/bin/esphome run esphome/ha-controller.yaml +esphome/.venv/bin/esphome run esphome/simulator.yaml +``` + +The venv is Python 3.13 with `esphome/requirements.txt`. Never commit `esphome/secrets.yaml`. + +## Simulator loop + +1. Change the code and run the host tests. +2. `esphome run esphome/simulator.yaml` (an SDL window; mouse drags act as finger swipes). +3. Connect it to a development Home Assistant (see `docs/development.md`) and edit the layout in the panel. +4. Before finishing, compile both configs. `install_firmware` exists only in `ha-controller.yaml` (the simulator has no HTTP OTA). + +## Rules + +- Pure logic goes in host-tested headers or modules under `esphome/components/ha_controller/` with a test in `esphome/tests/`. +- LVGL is called on the main loop only. +- Views never register ESPHome callbacks; the component registers them once. +- Call `lv_refr_now` before blocking work (such as OTA), so the message is on the panel. +- LVGL is paused while the screen sleeps. Call `wake()` before showing anything the user must see (`show_message` already does). +- Fonts are declared in `esphome/packages/ui.yaml` and mapped in the `ha_controller:` block. +- A new LVGL widget type needs a hidden instance on `boot_page`, so ESPHome compiles it in. +- Controls stay inside radius 185 of the 466 px circle. +- Keep the `cst9217` external component pinned to its commit SHA. diff --git a/.claude/skills/protocol-change/SKILL.md b/.claude/skills/protocol-change/SKILL.md new file mode 100644 index 0000000..53645df --- /dev/null +++ b/.claude/skills/protocol-change/SKILL.md @@ -0,0 +1,13 @@ +--- +name: protocol-change +description: "Use when changing anything that crosses the Home Assistant ↔ screen boundary: layout fields, validation rules, payload keys, state update fields, events, actions, emoji list or limits." +--- + +# Changing the HA ↔ screen protocol + +1. Classify the change. The C++ parser rejects unknown `widget`/`kind`/`font` values, so any new value is breaking: bump `PROTOCOL_VERSION` in `custom_components/ha_controller/const.py` and in the firmware's `ha_controller.h`. +2. Edit `docs/protocol/README.md` first. +3. Update `docs/protocol/fixtures/`, keeping one rule per invalid fixture and regenerating golden `rev` values with the snippet in `docs/protocol/README.md`. +4. Update the Python code in `custom_components/ha_controller/` (`layout.py`, `compiler.py`, `states.py`, `controls.py`) with its tests in `custom_components/ha_controller/tests`, the TypeScript model (`custom_components/ha_controller/frontend/src/model/`), the C++ parsers (`esphome/components/ha_controller/layout.*`, `states.*`) and the renderers (`widgets.*`, panel editor). +5. Run `pytest custom_components/ha_controller/tests`, `pytest .github/scripts/tests`, `npm --prefix custom_components/ha_controller/frontend test`, the host C++ tests and `esphome compile`. +6. Ask the `protocol-guardian` agent to review. diff --git a/.claude/skills/release/SKILL.md b/.claude/skills/release/SKILL.md new file mode 100644 index 0000000..83ebd7e --- /dev/null +++ b/.claude/skills/release/SKILL.md @@ -0,0 +1,32 @@ +--- +name: release +description: "Use when cutting a release or changing the release pipeline: versions, release workflow, GitHub Pages installer, HACS packaging, firmware OTA URLs." +--- + +# Releasing HA Controller + +- Never edit versions by hand. Use `.github/scripts/.venv/bin/python .github/scripts/versioning.py bump X.Y.Z`. + +## Steps (from `docs/releasing.md`) + +1. `.github/scripts/.venv/bin/python .github/scripts/versioning.py bump X.Y.Z` +2. Commit `chore: release X.Y.Z`. +3. `git tag vX.Y.Z && git push origin main vX.Y.Z` +4. Watch the "Release" workflow. +5. Check that the Pages page shows X.Y.Z and that HACS offers X.Y.Z. + +Dry runs use `workflow_dispatch` (only the `build` job runs). + +## What each job produces + +- `build`: `dist/ha_controller.zip` (integration with the built panel, for HACS) and `dist/ha-controller-X.Y.Z.*` (factory image, OTA image and OTA md5), uploaded as the `dist` artifact. +- `pages`: the installer site, built from `esphome/web`, the firmware of this version (from `dist`) and the firmware of every earlier release (releases without firmware assets are skipped). Tag runs only, after `build`. +- `release`: the GitHub release with every file of `dist`. Tag runs only, after `pages`. + +The order is `build` → `pages` → `release`. Pages is deployed before the release so the OTA URLs exist when HACS offers the new version. + +## Rules + +- The `github-pages` environment must allow tags `v*` (see the one-time setup in `docs/releasing.md`), or the `pages` job fails on tag runs. +- OTA URLs must stay stable (`firmware//ha-controller.ota.bin`), because integrations already installed depend on them. +- After any script change, run `.github/scripts/.venv/bin/pytest .github/scripts/tests`. diff --git a/.github/scripts/build_pages.py b/.github/scripts/build_pages.py new file mode 100644 index 0000000..1b612a4 --- /dev/null +++ b/.github/scripts/build_pages.py @@ -0,0 +1,72 @@ +"""Build the GitHub Pages site: web installer, ESP Web Tools manifest and every OTA image.""" + +import argparse +import json +import shutil +from pathlib import Path + +RELEASE_URL = "https://github.com/pyxel-dev/HA-controller/releases/tag/v{version}" + + +def build_site(web_dir: Path, releases_dir: Path, latest: str, out_dir: Path) -> None: + """Write the site to out_dir from web_dir and releases_dir// asset folders.""" + latest_dir = releases_dir / latest + latest_factory = latest_dir / f"ha-controller-{latest}.factory.bin" + latest_ota = latest_dir / f"ha-controller-{latest}.ota.bin" + for required in (latest_factory, latest_ota): + if not required.is_file(): + raise FileNotFoundError(f"Missing release asset: {required}") + + firmware = out_dir / "firmware" + firmware.mkdir(parents=True, exist_ok=True) + + page = (web_dir / "index.html").read_text(encoding="utf-8") + (out_dir / "index.html").write_text(page.replace("{{VERSION}}", latest), encoding="utf-8") + (out_dir / ".nojekyll").write_text("", encoding="utf-8") + + for folder in sorted(p for p in releases_dir.iterdir() if p.is_dir()): + version = folder.name + ota = folder / f"ha-controller-{version}.ota.bin" + md5 = folder / f"ha-controller-{version}.ota.bin.md5" + if not (ota.is_file() and md5.is_file()): + continue + target = firmware / version + target.mkdir(parents=True, exist_ok=True) + shutil.copyfile(ota, target / "ha-controller.ota.bin") + shutil.copyfile(md5, target / "ha-controller.ota.bin.md5") + + shutil.copyfile(latest_factory, firmware / "ha-controller.factory.bin") + md5_latest = (latest_dir / f"ha-controller-{latest}.ota.bin.md5").read_text().strip() + manifest = { + "name": "HA Controller", + "version": latest, + "home_assistant_domain": "esphome", + "new_install_prompt_erase": True, + "builds": [ + { + "chipFamily": "ESP32-S3", + "parts": [{"path": "ha-controller.factory.bin", "offset": 0}], + "ota": { + "path": f"{latest}/ha-controller.ota.bin", + "md5": md5_latest, + "release_url": RELEASE_URL.format(version=latest), + }, + } + ], + } + (firmware / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--web", type=Path, required=True) + parser.add_argument("--releases", type=Path, required=True) + parser.add_argument("--latest", required=True) + parser.add_argument("--out", type=Path, required=True) + args = parser.parse_args(argv) + build_site(args.web, args.releases, args.latest, args.out) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/.github/scripts/collect_firmware.py b/.github/scripts/collect_firmware.py new file mode 100644 index 0000000..87740bf --- /dev/null +++ b/.github/scripts/collect_firmware.py @@ -0,0 +1,43 @@ +"""Collect the ESPHome factory and OTA images into versioned release assets.""" + +import argparse +import hashlib +import shutil +from pathlib import Path + + +def _only(build_dir: Path, pattern: str) -> Path: + matches = sorted(build_dir.rglob(pattern)) + if len(matches) != 1: + raise ValueError(f"Expected exactly one {pattern} under {build_dir}, found {len(matches)}") + return matches[0] + + +def collect(build_dir: Path, version: str, out_dir: Path) -> list[Path]: + """Copy the images to out_dir as ha-controller-.* and write the OTA md5.""" + factory = _only(build_dir, "*.factory.bin") + ota = _only(build_dir, "*.ota.bin") + out_dir.mkdir(parents=True, exist_ok=True) + + factory_out = out_dir / f"ha-controller-{version}.factory.bin" + ota_out = out_dir / f"ha-controller-{version}.ota.bin" + md5_out = out_dir / f"ha-controller-{version}.ota.bin.md5" + shutil.copyfile(factory, factory_out) + shutil.copyfile(ota, ota_out) + md5_out.write_text(hashlib.md5(ota.read_bytes()).hexdigest(), encoding="ascii") + return [factory_out, ota_out, md5_out] + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--build-dir", type=Path, required=True) + parser.add_argument("--version", required=True) + parser.add_argument("--out", type=Path, required=True) + args = parser.parse_args(argv) + for path in collect(args.build_dir, args.version, args.out): + print(path) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/.github/scripts/make_brand_icon.py b/.github/scripts/make_brand_icon.py new file mode 100644 index 0000000..848dc37 --- /dev/null +++ b/.github/scripts/make_brand_icon.py @@ -0,0 +1,39 @@ +"""Generate the integration brand icons (icon.png and icon@2x.png).""" + +from pathlib import Path + +from PIL import Image, ImageDraw + +DESIGN = 512 +OUT = Path(__file__).parents[2] / "custom_components" / "ha_controller" / "brand" + + +def draw(size: int) -> Image.Image: + """Draw the icon at `size` px, scaled from the 512 design.""" + scale = 4 # supersample for smooth edges + px = size * scale + k = px / DESIGN + c = px / 2 + img = Image.new("RGBA", (px, px), (0, 0, 0, 0)) + d = ImageDraw.Draw(img) + + def box(r: float) -> tuple[float, float, float, float]: + return (c - r * k, c - r * k, c + r * k, c + r * k) + + d.ellipse(box(240), fill="#111827") + # Ring and arc are centred on radius 170, so the outer edge is 170 + width / 2. + outer = 170 + 36 / 2 + d.ellipse(box(outer), outline="#374151", width=round(36 * k)) + d.arc(box(outer), 135, 315, fill="#F59E0B", width=round(36 * k)) + d.ellipse(box(40), fill="#F9FAFB") + return img.resize((size, size), Image.LANCZOS) + + +def main() -> None: + OUT.mkdir(parents=True, exist_ok=True) + draw(256).save(OUT / "icon.png") + draw(512).save(OUT / "icon@2x.png") + + +if __name__ == "__main__": + main() diff --git a/.github/scripts/package_integration.py b/.github/scripts/package_integration.py new file mode 100644 index 0000000..66e28a7 --- /dev/null +++ b/.github/scripts/package_integration.py @@ -0,0 +1,49 @@ +"""Zip the integration for HACS, with the built panel and without development files.""" + +import argparse +import zipfile +from pathlib import Path + +INTEGRATION = Path("custom_components") / "ha_controller" +PANEL = Path("frontend") / "dist" / "ha-controller-panel.js" +BUILD_HINT = ( + "Build the panel first: npm --prefix custom_components/ha_controller/frontend run build" +) + + +def _included(relative: Path) -> bool: + parts = relative.parts + if "__pycache__" in parts or "tests" == parts[0]: + return False + if relative.name.startswith(".") or relative.suffix == ".pyc": + return False + if parts[0] == "frontend": + return relative == PANEL + return True + + +def package(root: Path, out_file: Path) -> Path: + """Write the zip with the integration contents at the zip root.""" + source = root / INTEGRATION + if not (source / PANEL).is_file(): + raise FileNotFoundError(BUILD_HINT) + out_file.parent.mkdir(parents=True, exist_ok=True) + with zipfile.ZipFile(out_file, "w", zipfile.ZIP_DEFLATED) as zf: + for path in sorted(source.rglob("*")): + relative = path.relative_to(source) + if path.is_file() and _included(relative): + zf.write(path, relative.as_posix()) + return out_file + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", type=Path, default=Path.cwd()) + parser.add_argument("--out", type=Path, required=True) + args = parser.parse_args(argv) + print(package(args.root, args.out)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/.github/scripts/pyproject.toml b/.github/scripts/pyproject.toml new file mode 100644 index 0000000..9fe26ce --- /dev/null +++ b/.github/scripts/pyproject.toml @@ -0,0 +1,9 @@ +[tool.pytest.ini_options] +testpaths = ["tests"] + +[tool.ruff] +target-version = "py314" +line-length = 100 + +[tool.ruff.lint] +select = ["E", "F", "I", "UP", "B"] diff --git a/.github/scripts/requirements.txt b/.github/scripts/requirements.txt new file mode 100644 index 0000000..e811611 --- /dev/null +++ b/.github/scripts/requirements.txt @@ -0,0 +1,3 @@ +pytest +ruff +pillow diff --git a/.github/scripts/tests/__init__.py b/.github/scripts/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/.github/scripts/tests/test_docs_links.py b/.github/scripts/tests/test_docs_links.py new file mode 100644 index 0000000..3e7aa12 --- /dev/null +++ b/.github/scripts/tests/test_docs_links.py @@ -0,0 +1,51 @@ +"""Documentation checks: relative links resolve and the docs index is complete.""" + +import re +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[3] +DOC_ROOTS = ["README.md", ".claude/CLAUDE.md", "docs"] # docs/superpowers/** is excluded +EXCLUDED = ROOT / "docs" / "superpowers" +LINK_RE = re.compile(r"\[[^\]]*\]\(([^)\s]+)(?:\s+\"[^\"]*\")?\)") +EXTERNAL_PREFIXES = ("http://", "https://", "mailto:", "#") + + +def _markdown_files() -> list[Path]: + files: list[Path] = [] + for name in DOC_ROOTS: + path = ROOT / name + if path.is_dir(): + files.extend(p for p in path.rglob("*.md") if EXCLUDED not in p.parents) + elif path.exists(): + files.append(path) + return sorted(files) + + +def test_relative_links_resolve(): + broken = [] + for md_file in _markdown_files(): + for target in LINK_RE.findall(md_file.read_text(encoding="utf-8")): + if target.startswith(EXTERNAL_PREFIXES): + continue + relative = target.split("#", 1)[0] + if relative and not (md_file.parent / relative).resolve().exists(): + broken.append(f"{md_file.relative_to(ROOT)} -> {target}") + assert not broken, "Broken relative links:\n" + "\n".join(broken) + + +def test_docs_index_lists_every_doc(): + index = ROOT / "docs" / "README.md" + assert index.exists(), "docs/README.md is missing" + linked = { + (index.parent / t.split("#", 1)[0]).resolve() + for t in LINK_RE.findall(index.read_text(encoding="utf-8")) + if not t.startswith(EXTERNAL_PREFIXES) + } + docs = ROOT / "docs" + candidates = [*docs.glob("*.md"), *docs.glob("*/README.md")] + missing = [ + str(p.relative_to(docs)) + for p in candidates + if p != index and EXCLUDED not in p.parents and p.resolve() not in linked + ] + assert not missing, f"Docs not linked from docs/README.md: {missing}" diff --git a/.github/scripts/tests/test_protocol_fixtures.py b/.github/scripts/tests/test_protocol_fixtures.py new file mode 100644 index 0000000..c85cd13 --- /dev/null +++ b/.github/scripts/tests/test_protocol_fixtures.py @@ -0,0 +1,117 @@ +"""Executable protocol contract: shape and golden values of docs/protocol/fixtures.""" + +import hashlib +import json +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[3] +FIXTURES = ROOT / "docs" / "protocol" / "fixtures" +EMOJI = ROOT / "custom_components" / "ha_controller" / "emoji.json" + +LAYOUT_CODES = { + "invalid_structure", + "too_many_blocks", + "invalid_sleep_timeout", + "invalid_id", + "duplicate_id", + "coordinate_out_of_range", + "duplicate_position", + "invalid_start", + "disconnected", + "invalid_name", + "invalid_background", + "invalid_font_size", + "invalid_type", + "invalid_entity", + "too_many_items", + "invalid_item", + "invalid_text", + "unsupported_emoji", +} # the 18 codes of spec section 6 except payload_too_large + +VALID_LAYOUTS = sorted((FIXTURES / "layouts" / "valid").glob("*.json")) +INVALID_LAYOUTS = sorted((FIXTURES / "layouts" / "invalid").glob("*.json")) +VALID_PAYLOADS = sorted((FIXTURES / "payloads" / "valid").glob("*.json")) +COLORS_FILE = FIXTURES / "colors.json" + + +def _load(path: Path): + return json.loads(path.read_text("utf-8")) + + +def canonical_rev(payload: dict) -> str: + body = {k: v for k, v in payload.items() if k != "rev"} + text = json.dumps(body, sort_keys=True, separators=(",", ":"), ensure_ascii=False) + return hashlib.sha256(text.encode()).hexdigest()[:8] + + +def luminance(color: str) -> float: + channels = [] + for i in (1, 3, 5): + c = int(color[i : i + 2], 16) / 255 + channels.append(c / 12.92 if c <= 0.03928 else ((c + 0.055) / 1.055) ** 2.4) + r, g, b = channels + return 0.2126 * r + 0.7152 * g + 0.0722 * b + + +def test_emoji_list_is_well_formed(): + emoji = _load(EMOJI) + assert len(emoji) == 64 and len(set(emoji)) == 64 + assert all(len(e) == 1 for e in emoji) # one code point each + assert "️" not in "".join(emoji) + assert {"💡", "🔋", "⚡", "☀", "👋"} <= set(emoji) and "🦄" not in emoji + + +def test_all_fixtures_are_utf8_json(): + files = sorted(FIXTURES.rglob("*.json")) + assert files + for path in files: + raw = path.read_bytes() + assert not raw.startswith(b"\xef\xbb\xbf"), f"BOM in {path}" + json.loads(raw.decode("utf-8")) + + +def test_invalid_layout_fixtures_declare_known_codes(): + assert INVALID_LAYOUTS + for path in INVALID_LAYOUTS: + data = _load(path) + code, ref = data["expect"]["code"], data["expect"]["ref"] + assert code in LAYOUT_CODES, path.name + assert ref is None or isinstance(ref, str), path.name + assert path.stem == code or path.stem.startswith(code + "-"), path.name + assert isinstance(data["layout"], dict) + + +def test_every_layout_code_has_an_invalid_fixture(): + covered = {_load(p)["expect"]["code"] for p in INVALID_LAYOUTS} + assert covered == LAYOUT_CODES + + +def test_payload_revisions_match_canonical_hash(): + revs = {p.stem: _load(p)["payload"]["rev"] for p in VALID_PAYLOADS} + assert revs == { + "empty": "c4aad3fa", + "reference": "90538742", + "emoji-variation": "5387d4ea", + } + for path in VALID_PAYLOADS: + payload = _load(path)["payload"] + assert canonical_rev(payload) == payload["rev"], path.name + + +def test_fixtures_reference_existing_layouts(): + names = {p.stem for p in VALID_LAYOUTS} + checked = 0 + for folder in ("payloads/valid", "states", "controls"): + for path in sorted((FIXTURES / folder).glob("*.json")): + assert _load(path)["layout"] in names, path + checked += 1 + assert checked + + +def test_color_fixture_matches_luminance_rule(): + colors = _load(COLORS_FILE) + assert colors + for case in colors: + expected = "#000000" if luminance(case["bg"]) > 0.30 else "#FFFFFF" + assert case["text"] == expected, case diff --git a/.github/scripts/tests/test_release_scripts.py b/.github/scripts/tests/test_release_scripts.py new file mode 100644 index 0000000..6ddfffb --- /dev/null +++ b/.github/scripts/tests/test_release_scripts.py @@ -0,0 +1,183 @@ +"""Release tooling: firmware collection, integration zip and GitHub Pages site.""" + +import hashlib +import json +import zipfile +from pathlib import Path + +import pytest + +from build_pages import build_site +from collect_firmware import collect +from package_integration import package + +REPO_ROOT = Path(__file__).resolve().parents[3] +INTEGRATION = "custom_components/ha_controller" +PANEL = f"{INTEGRATION}/frontend/dist/ha-controller-panel.js" + + +def _write(path: Path, content: bytes | str = b"x") -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + if isinstance(content, str): + path.write_text(content, encoding="utf-8") + else: + path.write_bytes(content) + return path + + +def test_collect_writes_versioned_files_and_md5(tmp_path): + build = tmp_path / "build" / "ha-controller" / "build" + _write(build / "firmware.factory.bin", b"factory") + _write(build / "firmware.ota.bin", b"ota-image") + _write(build / "ha-controller.bin", b"other") + _write(build / "bootloader" / "bootloader.bin", b"boot") + out = tmp_path / "out" + + written = collect(tmp_path / "build", "0.2.0", out) + + assert sorted(p.name for p in written) == [ + "ha-controller-0.2.0.factory.bin", + "ha-controller-0.2.0.ota.bin", + "ha-controller-0.2.0.ota.bin.md5", + ] + assert (out / "ha-controller-0.2.0.factory.bin").read_bytes() == b"factory" + md5 = (out / "ha-controller-0.2.0.ota.bin.md5").read_bytes() + assert md5 == hashlib.md5(b"ota-image").hexdigest().encode() + assert len(md5) == 32 + + +def test_collect_requires_exactly_one_of_each(tmp_path): + build = tmp_path / "build" + build.mkdir() + with pytest.raises(ValueError): + collect(build, "0.2.0", tmp_path / "out") + + _write(build / "a" / "firmware.factory.bin") + _write(build / "b" / "firmware.factory.bin") + _write(build / "a" / "firmware.ota.bin") + with pytest.raises(ValueError): + collect(build, "0.2.0", tmp_path / "out") + + +def _fake_repo(root: Path, with_panel: bool = True) -> None: + _write(root / INTEGRATION / "manifest.json", "{}") + _write(root / INTEGRATION / "__init__.py", "") + _write(root / INTEGRATION / "emoji.json", "[]") + _write(root / INTEGRATION / "brand" / "icon.png") + _write(root / INTEGRATION / "__pycache__" / "x.cpython-314.pyc") + _write(root / INTEGRATION / "tests" / "test_x.py", "") + _write(root / INTEGRATION / "frontend" / "src" / "a.ts", "") + _write(root / INTEGRATION / "frontend" / "package.json", "{}") + _write(root / INTEGRATION / "frontend" / "node_modules" / "m" / "i.js", "") + _write(root / INTEGRATION / "frontend" / "dist" / "other.js", "") + _write(root / INTEGRATION / "frontend" / "dist" / ".gitkeep", "") + if with_panel: + _write(root / PANEL, "panel") + + +def test_package_zips_integration_with_panel(tmp_path): + _fake_repo(tmp_path) + out = package(tmp_path, tmp_path / "dist" / "ha_controller.zip") + + with zipfile.ZipFile(out) as zf: + names = set(zf.namelist()) + assert names == { + "manifest.json", + "__init__.py", + "emoji.json", + "brand/icon.png", + "frontend/dist/ha-controller-panel.js", + } + + +def test_package_requires_built_panel(tmp_path): + _fake_repo(tmp_path, with_panel=False) + with pytest.raises(FileNotFoundError, match="Build the panel first"): + package(tmp_path, tmp_path / "ha_controller.zip") + + +def _release(releases: Path, version: str) -> None: + _write(releases / version / f"ha-controller-{version}.factory.bin", f"f{version}".encode()) + ota = f"o{version}".encode() + _write(releases / version / f"ha-controller-{version}.ota.bin", ota) + _write( + releases / version / f"ha-controller-{version}.ota.bin.md5", + hashlib.md5(ota).hexdigest(), + ) + + +def _web(tmp_path: Path) -> Path: + return _write( + tmp_path / "web" / "index.html", "

Firmware {{VERSION}}

" + ).parent + + +def test_build_site_manifest(tmp_path): + releases = tmp_path / "releases" + _release(releases, "0.2.0") + out = tmp_path / "site" + + build_site(_web(tmp_path), releases, "0.2.0", out) + + manifest = json.loads((out / "firmware" / "manifest.json").read_text()) + assert manifest == { + "name": "HA Controller", + "version": "0.2.0", + "home_assistant_domain": "esphome", + "new_install_prompt_erase": True, + "builds": [ + { + "chipFamily": "ESP32-S3", + "parts": [{"path": "ha-controller.factory.bin", "offset": 0}], + "ota": { + "path": "0.2.0/ha-controller.ota.bin", + "md5": hashlib.md5(b"o0.2.0").hexdigest(), + "release_url": "https://github.com/pyxel-dev/HA-controller/releases/tag/v0.2.0", + }, + } + ], + } + assert (out / "firmware" / "ha-controller.factory.bin").read_bytes() == b"f0.2.0" + + +def test_build_site_keeps_every_release(tmp_path): + releases = tmp_path / "releases" + _release(releases, "0.1.0") + _release(releases, "0.2.0") + out = tmp_path / "site" + + build_site(_web(tmp_path), releases, "0.2.0", out) + + for version in ("0.1.0", "0.2.0"): + folder = out / "firmware" / version + assert (folder / "ha-controller.ota.bin").read_bytes() == f"o{version}".encode() + assert (folder / "ha-controller.ota.bin.md5").read_text() == hashlib.md5( + f"o{version}".encode() + ).hexdigest() + assert (out / "firmware" / "ha-controller.factory.bin").read_bytes() == b"f0.2.0" + + +def test_build_site_renders_version(tmp_path): + releases = tmp_path / "releases" + _release(releases, "0.2.0") + out = tmp_path / "site" + + build_site(_web(tmp_path), releases, "0.2.0", out) + + html = (out / "index.html").read_text() + assert "Firmware 0.2.0" in html + assert "{{VERSION}}" not in html + assert (out / ".nojekyll").exists() + + +def test_build_site_requires_latest_assets(tmp_path): + releases = tmp_path / "releases" + _release(releases, "0.1.0") + with pytest.raises(FileNotFoundError): + build_site(_web(tmp_path), releases, "0.2.0", tmp_path / "site") + + +def test_web_page_template(): + html = (REPO_ROOT / "esphome" / "web" / "index.html").read_text(encoding="utf-8") + assert html.count("{{VERSION}}") >= 2 + assert "esp-web-tools@10.5.2" in html diff --git a/.github/scripts/tests/test_versioning.py b/.github/scripts/tests/test_versioning.py new file mode 100644 index 0000000..63d8c38 --- /dev/null +++ b/.github/scripts/tests/test_versioning.py @@ -0,0 +1,206 @@ +"""Single-version check and bump across manifest, ESPHome, panel and panel lock.""" + +import json +from pathlib import Path + +import pytest + +import versioning +from versioning import bump_version, check_versions, main, read_versions + +REPO_ROOT = Path(__file__).resolve().parents[3] + +MANIFEST = "custom_components/ha_controller/manifest.json" +ESPHOME = "esphome/version.yaml" +FRONTEND = "custom_components/ha_controller/frontend/package.json" +FRONTEND_LOCK = "custom_components/ha_controller/frontend/package-lock.json" + + +def _json(data: dict) -> str: + return json.dumps(data, indent=2) + "\n" + + +def _manifest(version: str) -> str: + # Same shape as the real manifest: inline arrays that json.dumps would reflow. + return ( + "{\n" + ' "domain": "ha_controller",\n' + ' "name": "HA Controller",\n' + ' "after_dependencies": ["esphome"],\n' + ' "codeowners": ["@pyxel-dev"],\n' + ' "config_flow": true,\n' + ' "dependencies": ["frontend", "http", "panel_custom", "websocket_api"],\n' + ' "requirements": [],\n' + f' "version": "{version}"\n' + "}\n" + ) + + +def _yaml(version: str) -> str: + return ( + "substitutions:\n" + ' device_name: "ha-controller"\n' + f' project_version: "{version}"\n' + "esphome:\n" + " name: ha-controller\n" + ) + + +@pytest.fixture +def repo(tmp_path: Path) -> Path: + files = { + MANIFEST: _manifest("0.1.0"), + ESPHOME: _yaml("0.1.0"), + FRONTEND: _json({"name": "ha-controller-panel", "version": "0.1.0", "private": True}), + FRONTEND_LOCK: _json( + { + "name": "ha-controller-panel", + "version": "0.1.0", + "lockfileVersion": 3, + "packages": {"": {"name": "ha-controller-panel", "version": "0.1.0"}}, + } + ), + } + for relative, text in files.items(): + path = tmp_path / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + return tmp_path + + +def test_read_versions(repo): + assert set(read_versions(repo).values()) == {"0.1.0"} + + +def test_check_passes_when_equal(repo): + assert check_versions(repo) == [] + + +def test_check_reports_mismatch(repo): + path = repo / MANIFEST + data = json.loads(path.read_text(encoding="utf-8")) + data["version"] = "0.2.0" + path.write_text(_json(data), encoding="utf-8") + + errors = check_versions(repo) + + assert len(errors) == 1 + assert "manifest" in errors[0] + assert MANIFEST in errors[0] + assert "0.2.0" in errors[0] + assert "0.1.0" in errors[0] + + +def test_check_errors_name_file_path_for_unreadable_source(repo): + (repo / ESPHOME).unlink() + + errors = check_versions(repo) + + assert any("esphome" in error and ESPHOME in error for error in errors) + + +def test_check_tag_must_match(repo): + assert check_versions(repo, "v0.1.0") == [] + assert check_versions(repo, "v0.1.1") + assert check_versions(repo, "0.1.0") + + +def test_check_rejects_non_semver(repo): + (repo / ESPHOME).write_text(_yaml("0.1"), encoding="utf-8") + for relative in (MANIFEST, FRONTEND, FRONTEND_LOCK): + path = repo / relative + text = path.read_text(encoding="utf-8").replace('"0.1.0"', '"0.1"') + path.write_text(text, encoding="utf-8") + + assert check_versions(repo) + + +def test_bump_rewrites_all(repo): + before_yaml = (repo / ESPHOME).read_text(encoding="utf-8") + + bump_version(repo, "1.2.3") + + assert set(read_versions(repo).values()) == {"1.2.3"} + assert check_versions(repo) == [] + + manifest = json.loads((repo / MANIFEST).read_text(encoding="utf-8")) + assert manifest["version"] == "1.2.3" + assert manifest["dependencies"] == ["frontend", "http", "panel_custom", "websocket_api"] + + frontend = json.loads((repo / FRONTEND).read_text(encoding="utf-8")) + assert frontend == {"name": "ha-controller-panel", "version": "1.2.3", "private": True} + + lock = json.loads((repo / FRONTEND_LOCK).read_text(encoding="utf-8")) + assert lock["lockfileVersion"] == 3 + assert lock["packages"][""]["name"] == "ha-controller-panel" + + yaml_after = (repo / ESPHOME).read_text(encoding="utf-8") + assert yaml_after == before_yaml.replace('project_version: "0.1.0"', 'project_version: "1.2.3"') + assert ' device_name: "ha-controller"' in yaml_after + + for relative in (FRONTEND, FRONTEND_LOCK): + assert (repo / relative).read_text(encoding="utf-8").endswith("}\n") + + +def test_bump_changes_only_manifest_version_text(repo): + before = (repo / MANIFEST).read_text(encoding="utf-8") + + bump_version(repo, "1.2.3") + + after = (repo / MANIFEST).read_text(encoding="utf-8") + assert after == before.replace('"version": "0.1.0"', '"version": "1.2.3"') + + +@pytest.mark.parametrize("bad", ["1.2", "v1.2.3", "1.2.3-rc1"]) +def test_bump_rejects_invalid(repo, bad): + with pytest.raises(ValueError): + bump_version(repo, bad) + assert set(read_versions(repo).values()) == {"0.1.0"} + + +def test_repository_versions_are_consistent(): + assert check_versions(REPO_ROOT) == [] + + +def test_main_exit_codes(repo, monkeypatch): + monkeypatch.setattr(versioning, "REPO_ROOT", repo) + + assert main(["check"]) == 0 + assert main(["check", "--tag", "v0.1.0"]) == 0 + assert main(["check", "--tag", "v0.1.1"]) == 1 + assert main(["bump", "0.3.0"]) == 0 + assert set(read_versions(repo).values()) == {"0.3.0"} + assert main(["check"]) == 0 + assert main(["bump", "0.3"]) == 1 + + +@pytest.mark.parametrize( + ("relative", "content"), + [ + (MANIFEST, "{ not json"), + (MANIFEST, "[]"), + (MANIFEST, '{"domain": "ha_controller"}'), + (FRONTEND_LOCK, "[]"), + (FRONTEND_LOCK, '{"version": "0.1.0"}'), + (ESPHOME, "substitutions: {}\n"), + ], +) +@pytest.mark.parametrize("argv", [["check"], ["bump", "1.2.3"]]) +def test_main_reports_malformed_files_without_traceback( + repo, monkeypatch, capsys, relative, content, argv +): + monkeypatch.setattr(versioning, "REPO_ROOT", repo) + (repo / relative).write_text(content, encoding="utf-8") + + assert main(argv) == 1 + + assert capsys.readouterr().err.strip() + + +def test_main_reports_missing_file_without_traceback(repo, monkeypatch, capsys): + monkeypatch.setattr(versioning, "REPO_ROOT", repo) + (repo / FRONTEND).unlink() + + assert main(["check"]) == 1 + assert main(["bump", "1.2.3"]) == 1 + assert FRONTEND in capsys.readouterr().err diff --git a/.github/scripts/versioning.py b/.github/scripts/versioning.py new file mode 100644 index 0000000..8161bc7 --- /dev/null +++ b/.github/scripts/versioning.py @@ -0,0 +1,192 @@ +"""Check and bump the single SemVer version shared by the whole repository. + +The version lives in four files: +- custom_components/ha_controller/manifest.json ("version") +- esphome/version.yaml (substitutions.project_version) +- custom_components/ha_controller/frontend/package.json ("version") +- custom_components/ha_controller/frontend/package-lock.json (root and packages[""] "version") + +Usage: + python .github/scripts/versioning.py check [--tag vX.Y.Z] + python .github/scripts/versioning.py bump X.Y.Z +""" + +import argparse +import json +import re +import sys +from collections import Counter +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parents[2] +VERSION_RE = re.compile(r"^\d+\.\d+\.\d+$") + +MANIFEST = Path("custom_components/ha_controller/manifest.json") +ESPHOME = Path("esphome/version.yaml") +FRONTEND = Path("custom_components/ha_controller/frontend/package.json") +FRONTEND_LOCK = Path("custom_components/ha_controller/frontend/package-lock.json") + +SOURCE_PATHS = { + "manifest": MANIFEST, + "esphome": ESPHOME, + "frontend": FRONTEND, + "frontend-lock": FRONTEND_LOCK, +} + +ESPHOME_LINE_RE = re.compile(r'^(\s*project_version:\s*")([^"]*)(")', re.MULTILINE) +MANIFEST_VERSION_RE = re.compile(r'^(\s*"version"\s*:\s*")([^"]*)(")', re.MULTILINE) + + +def _read_json(path: Path) -> dict: + return json.loads(path.read_text(encoding="utf-8")) + + +def _write_json(path: Path, data: dict) -> None: + path.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") + + +def _read_esphome(root: Path) -> str: + match = ESPHOME_LINE_RE.search((root / ESPHOME).read_text(encoding="utf-8")) + if match is None: + raise ValueError("project_version not found") + return match.group(2) + + +def _read_lock(root: Path) -> str: + lock = _read_json(root / FRONTEND_LOCK) + root_version = lock["version"] + package_version = lock["packages"][""]["version"] + if root_version != package_version: + raise ValueError( + f'version {root_version} differs from packages[""] version {package_version}' + ) + return root_version + + +READERS = { + "manifest": lambda root: _read_json(root / MANIFEST)["version"], + "esphome": _read_esphome, + "frontend": lambda root: _read_json(root / FRONTEND)["version"], + "frontend-lock": _read_lock, +} + + +def _collect(root: Path) -> tuple[dict[str, str], list[str]]: + values: dict[str, str] = {} + errors: list[str] = [] + for key, reader in READERS.items(): + try: + values[key] = reader(root) + except (OSError, ValueError, KeyError, TypeError) as exc: + errors.append(f"{key} ({SOURCE_PATHS[key]}): cannot read version ({exc})") + return values, errors + + +def read_versions(root: Path) -> dict[str, str]: + """Return the version found in each source, keyed by source name.""" + values, errors = _collect(root) + if errors: + raise ValueError("; ".join(errors)) + return values + + +def check_versions(root: Path, tag: str | None = None) -> list[str]: + """Return human-readable errors; an empty list means the repository is consistent.""" + values, errors = _collect(root) + + for key, value in values.items(): + if not VERSION_RE.fullmatch(value): + errors.append(f"{key} ({SOURCE_PATHS[key]}) version {value!r} is not SemVer X.Y.Z") + + if values: + # The first source (manifest) wins a tie, so the reference is stable. + expected, _ = Counter(values.values()).most_common(1)[0] + for key, value in values.items(): + if value != expected: + errors.append(f"{key} ({SOURCE_PATHS[key]}) is {value}, expected {expected}") + + if tag is not None and tag != f"v{expected}": + errors.append(f"tag {tag} does not match version v{expected}") + elif tag is not None: + errors.append(f"tag {tag} cannot be checked without a readable version") + + return errors + + +def _bump_manifest_text(text: str, version: str) -> str: + """Replace only the top-level version value, leaving every other byte unchanged.""" + old = json.loads(text) + if not isinstance(old, dict) or "version" not in old: + raise ValueError(f"{MANIFEST}: top-level version not found") + + match = MANIFEST_VERSION_RE.search(text) + if match is None: + raise ValueError(f"{MANIFEST}: top-level version not found") + new_text = text[: match.start(2)] + version + text[match.end(2) :] + + # Guard against matching a nested "version" key: the only change must be the top-level one. + if json.loads(new_text) != {**old, "version": version}: + raise ValueError(f"{MANIFEST}: could not locate the top-level version safely") + return new_text + + +def bump_version(root: Path, version: str) -> None: + """Write version to every source. Nothing is written unless all sources can be updated.""" + if not VERSION_RE.fullmatch(version): + raise ValueError(f"version {version!r} is not SemVer X.Y.Z") + + manifest_text = (root / MANIFEST).read_text(encoding="utf-8", newline="") + manifest_new = _bump_manifest_text(manifest_text, version) + + frontend = _read_json(root / FRONTEND) + frontend["version"] = version + + lock = _read_json(root / FRONTEND_LOCK) + lock["version"] = version + lock["packages"][""]["version"] = version + + esphome_text = (root / ESPHOME).read_text(encoding="utf-8") + esphome_new, count = ESPHOME_LINE_RE.subn( + lambda match: f"{match.group(1)}{version}{match.group(3)}", esphome_text, count=1 + ) + if count != 1: + raise ValueError(f"{ESPHOME}: project_version not found") + + (root / MANIFEST).write_text(manifest_new, encoding="utf-8", newline="") + _write_json(root / FRONTEND, frontend) + _write_json(root / FRONTEND_LOCK, lock) + (root / ESPHOME).write_text(esphome_new, encoding="utf-8") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(prog="versioning.py", description=__doc__.splitlines()[0]) + commands = parser.add_subparsers(dest="command", required=True) + + check = commands.add_parser("check", help="verify that every source has the same version") + check.add_argument("--tag", help="release tag that must equal v + version") + + bump = commands.add_parser("bump", help="set the version in every source") + bump.add_argument("version", help="new SemVer version X.Y.Z") + + args = parser.parse_args(sys.argv[1:] if argv is None else argv) + + try: + if args.command == "check": + errors = check_versions(REPO_ROOT, args.tag) + if errors: + for error in errors: + print(error, file=sys.stderr) + return 1 + print(f"versions consistent: {next(iter(read_versions(REPO_ROOT).values()))}") + return 0 + + bump_version(REPO_ROOT, args.version) + except (OSError, ValueError, KeyError, TypeError) as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + print(f"version bumped to {args.version}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..5869771 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,54 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +jobs: + repo-checks: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.14" + - run: pip install -r .github/scripts/requirements.txt + - run: ruff check .github/scripts + - run: pytest .github/scripts/tests + + versions: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.14" + - run: python .github/scripts/versioning.py check + + integration: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.14" + - run: pip install -r custom_components/requirements_test.txt + - run: ruff check custom_components + - run: pytest custom_components/ha_controller/tests + + frontend: + runs-on: ubuntu-latest + defaults: + run: + working-directory: custom_components/ha_controller/frontend + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 24 + cache: npm + cache-dependency-path: custom_components/ha_controller/frontend/package-lock.json + - run: npm ci + - run: npm test + - run: npm run build diff --git a/.github/workflows/firmware.yml b/.github/workflows/firmware.yml new file mode 100644 index 0000000..c2e9174 --- /dev/null +++ b/.github/workflows/firmware.yml @@ -0,0 +1,43 @@ +name: Firmware + +on: + push: + branches: [main] + paths: + - "esphome/**" + - "docs/protocol/**" + - "custom_components/ha_controller/emoji.json" + - ".github/workflows/firmware.yml" + pull_request: + paths: + - "esphome/**" + - "docs/protocol/**" + - "custom_components/ha_controller/emoji.json" + - ".github/workflows/firmware.yml" + +jobs: + host-tests: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - run: cmake -S esphome/tests -B esphome/tests/build + - run: cmake --build esphome/tests/build + - run: ctest --test-dir esphome/tests/build --output-on-failure + + compile: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.13" + - uses: actions/cache@v4 + with: + path: | + ~/.platformio + esphome/.esphome + key: esphome-${{ hashFiles('esphome/requirements.txt', 'esphome/**/*.yaml') }} + - run: sudo apt-get install -y libsdl2-dev + - run: pip install -r esphome/requirements.txt + - run: esphome compile esphome/ha-controller.yaml + - run: esphome compile esphome/simulator.yaml diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..ac32a60 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,126 @@ +name: Release + +on: + push: + tags: ["v*"] + workflow_dispatch: + +permissions: + contents: write + pages: write + id-token: write + +concurrency: + group: release + +jobs: + build: + runs-on: ubuntu-latest + outputs: + version: ${{ steps.version.outputs.version }} + steps: + - uses: actions/checkout@v4 + # Both versions are installed. The last one listed (3.14) is the default `python` + # and runs the repository scripts; ESPHome runs in a 3.13 venv. + - uses: actions/setup-python@v5 + with: + python-version: | + 3.13 + 3.14 + - uses: actions/setup-node@v4 + with: + node-version: "24" + cache: npm + cache-dependency-path: custom_components/ha_controller/frontend/package-lock.json + - name: Read the version + id: version + run: | + version=$(python -c "import json; print(json.load(open('custom_components/ha_controller/manifest.json'))['version'])") + echo "version=$version" >> "$GITHUB_OUTPUT" + - name: Check the repository version + run: python .github/scripts/versioning.py check + - name: Check the tag matches the version + if: github.ref_type == 'tag' + run: python .github/scripts/versioning.py check --tag "$GITHUB_REF_NAME" + - name: Build the panel + run: | + npm --prefix custom_components/ha_controller/frontend ci + npm --prefix custom_components/ha_controller/frontend run build + - name: Package the integration + run: python .github/scripts/package_integration.py --out dist/ha_controller.zip + - name: Install ESPHome + run: | + python3.13 -m venv esphome/.venv + esphome/.venv/bin/pip install -r esphome/requirements.txt + - name: Compile the firmware + run: esphome/.venv/bin/esphome compile esphome/ha-controller.yaml + - name: Collect the firmware + run: > + python .github/scripts/collect_firmware.py + --build-dir esphome/.esphome/build/ha-controller/build + --version "${{ steps.version.outputs.version }}" + --out dist + - uses: actions/upload-artifact@v4 + with: + name: dist + path: dist + + pages: + needs: build + if: github.ref_type == 'tag' + runs-on: ubuntu-latest + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.14" + - uses: actions/download-artifact@v4 + with: + name: dist + path: dist + - name: Add the firmware of this version + run: | + mkdir -p "releases/${{ needs.build.outputs.version }}" + cp dist/ha-controller-* "releases/${{ needs.build.outputs.version }}/" + - name: Download the firmware of every earlier release + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + run: | + for tag in $(gh release list --limit 200 --json tagName -q '.[].tagName'); do + if [ "$tag" = "$GITHUB_REF_NAME" ]; then continue; fi + if ! gh release download "$tag" -p 'ha-controller-*' -D "releases/${tag#v}"; then + echo "No firmware downloaded for $tag, skipping it" + rm -rf "releases/${tag#v}" + fi + done + - name: Build the site + run: > + python .github/scripts/build_pages.py --web esphome/web --releases releases + --latest "${{ needs.build.outputs.version }}" --out site + - uses: actions/configure-pages@v5 + - uses: actions/upload-pages-artifact@v3 + with: + path: site + - id: deployment + uses: actions/deploy-pages@v4 + + release: + needs: [build, pages] + if: github.ref_type == 'tag' + runs-on: ubuntu-latest + steps: + - uses: actions/download-artifact@v4 + with: + name: dist + path: dist + - name: Create the GitHub release + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + run: > + gh release create "$GITHUB_REF_NAME" dist/* + --title "$GITHUB_REF_NAME" --generate-notes --verify-tag diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml new file mode 100644 index 0000000..d7714d0 --- /dev/null +++ b/.github/workflows/validate.yml @@ -0,0 +1,22 @@ +name: Validate + +on: + push: + pull_request: + schedule: + - cron: "0 0 * * *" + workflow_dispatch: + +jobs: + hassfest: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: home-assistant/actions/hassfest@master + + hacs: + runs-on: ubuntu-latest + steps: + - uses: hacs/action@main + with: + category: integration diff --git a/.gitignore b/.gitignore index 496ee2c..a95a7d0 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,14 @@ -.DS_Store \ No newline at end of file +.DS_Store +__pycache__/ +.pytest_cache/ +.ruff_cache/ +.venv*/ +node_modules/ +frontend/coverage/ +esphome/.esphome/ +esphome/secrets.yaml +build/ +dist/ +site/ +.superpowers/ +esphome/.gitignore diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..96be66d --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "cmake.sourceDirectory": "/Users/kevin/Projects/HA-controller/esphome/tests" +} \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md index 9999a74..6727480 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,29 @@ # HA Controller -An ESP-32 remote control with a 1.75-inch AMOLED display + +HA Controller turns the Waveshare ESP32-S3-Touch-AMOLED-1.75, a round AMOLED touch screen, into a Home Assistant remote. A custom integration with a sidebar panel lets you design what the screen shows, and an ESPHome firmware renders it. + +- Block map editor in Home Assistant +- Edge-swipe navigation between blocks +- Light and thermostat knobs +- Custom blocks +- Automatic firmware updates + +Status: under active development. + +See the [documentation](docs/README.md). + +## Install + +1. Flash the firmware from the web installer: (Chrome or Edge). +2. In HACS, add the custom repository `https://github.com/pyxel-dev/HA-controller` (type Integration) and install the same version. + +See [Getting started](docs/getting-started.md) for the full steps and the [documentation](docs/README.md). ## 3D models -You can find two 3D models with or without power button, into [3D Models](3D_models) folder. Each models is in STL or 3MF. +You can find two 3D models, with or without power button, in the [3D_models](3D_models) folder. Each model is available as STL or 3MF.

-

\ No newline at end of file +

diff --git a/custom_components/__init__.py b/custom_components/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/custom_components/ha_controller/__init__.py b/custom_components/ha_controller/__init__.py new file mode 100644 index 0000000..f988e92 --- /dev/null +++ b/custom_components/ha_controller/__init__.py @@ -0,0 +1,64 @@ +"""The HA Controller integration.""" + +from homeassistant.config_entries import ConfigEntry +from homeassistant.const import Platform +from homeassistant.core import HomeAssistant +from homeassistant.helpers import config_validation as cv +from homeassistant.helpers.typing import ConfigType +from homeassistant.loader import async_get_integration + +from .const import DOMAIN +from .controller import ScreenController +from .layout import async_load_emoji +from .panel import async_register_panel, async_unregister_panel +from .store import LayoutStore +from .websocket import async_register_websocket + +CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN) + +PLATFORMS = [Platform.UPDATE] + +type HaControllerConfigEntry = ConfigEntry[ScreenController] + + +async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: + """Set up the integration.""" + async_register_websocket(hass) + return True + + +async def async_setup_entry(hass: HomeAssistant, entry: HaControllerConfigEntry) -> bool: + """Set up one screen.""" + integration = await async_get_integration(hass, DOMAIN) + controller = ScreenController( + hass, + entry, + LayoutStore(hass, entry.entry_id), + await async_load_emoji(hass), + str(integration.version), + ) + await controller.async_start() + entry.runtime_data = controller + await async_register_panel(hass, controller.integration_version) + await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) + return True + + +async def async_unload_entry(hass: HomeAssistant, entry: HaControllerConfigEntry) -> bool: + """Unload one screen.""" + if not await hass.config_entries.async_unload_platforms(entry, PLATFORMS): + return False + await entry.runtime_data.async_stop() + others = [ + other + for other in hass.config_entries.async_loaded_entries(DOMAIN) + if other.entry_id != entry.entry_id + ] + if not others: + async_unregister_panel(hass) + return True + + +async def async_remove_entry(hass: HomeAssistant, entry: HaControllerConfigEntry) -> None: + """Delete the stored layout of a removed screen.""" + await LayoutStore(hass, entry.entry_id).async_remove() diff --git a/custom_components/ha_controller/brand/icon.png b/custom_components/ha_controller/brand/icon.png new file mode 100644 index 0000000..b846736 Binary files /dev/null and b/custom_components/ha_controller/brand/icon.png differ diff --git a/custom_components/ha_controller/brand/icon@2x.png b/custom_components/ha_controller/brand/icon@2x.png new file mode 100644 index 0000000..6f63e28 Binary files /dev/null and b/custom_components/ha_controller/brand/icon@2x.png differ diff --git a/custom_components/ha_controller/compiler.py b/custom_components/ha_controller/compiler.py new file mode 100644 index 0000000..3579496 --- /dev/null +++ b/custom_components/ha_controller/compiler.py @@ -0,0 +1,68 @@ +"""Compile a stored layout into the compact payload sent to the screen.""" + +from __future__ import annotations + +import hashlib +import json +from typing import Any + +from .const import PROTOCOL_VERSION +from .layout import normalize_emoji + + +def _compile_item(item: dict[str, Any], block_font: str) -> dict[str, Any]: + kind = item["kind"] + out: dict[str, Any] = { + "id": item["id"], + "kind": kind, + "font": item["font_size"] or block_font, + } + if kind == "text": + out["text"] = item["text"] + elif kind == "emoji": + out["text"] = normalize_emoji(item["emoji"]) + return out + + +def _compile_block(block: dict[str, Any]) -> dict[str, Any]: + out: dict[str, Any] = { + "id": block["id"], + "x": block["x"], + "y": block["y"], + "name": block["name"].strip(), + "bg": block["background"].lstrip("#").upper(), + "font": block["font_size"], + } + if block["type"] == "entity": + out["widget"] = block["entity_id"].split(".", 1)[0] + else: + out["widget"] = "custom" + out["items"] = [_compile_item(i, block["font_size"]) for i in block["items"]] + return out + + +def payload_revision(payload: dict[str, Any]) -> str: + """Return the 8-hex-char revision of a payload, ignoring any `rev` key.""" + body = {k: v for k, v in payload.items() if k != "rev"} + text = json.dumps(body, sort_keys=True, separators=(",", ":"), ensure_ascii=False) + return hashlib.sha256(text.encode("utf-8")).hexdigest()[:8] + + +def compile_layout(layout: dict[str, Any]) -> dict[str, Any]: + """Compile a valid stored layout into a payload including its `rev`.""" + payload: dict[str, Any] = { + "v": PROTOCOL_VERSION, + "start": layout["start"], + "sleep": layout["settings"]["sleep_timeout"], + "blocks": [_compile_block(b) for b in layout["blocks"]], + } + return { + "v": PROTOCOL_VERSION, + "rev": payload_revision(payload), + **{k: v for k, v in payload.items() if k != "v"}, + } + + +def encode_payload(payload: dict[str, Any]) -> str: + """Return the compact JSON transport encoding of a payload.""" + return json.dumps(payload, separators=(",", ":"), ensure_ascii=False) diff --git a/custom_components/ha_controller/config_flow.py b/custom_components/ha_controller/config_flow.py new file mode 100644 index 0000000..3287682 --- /dev/null +++ b/custom_components/ha_controller/config_flow.py @@ -0,0 +1,82 @@ +"""Config flow for HA Controller.""" + +from typing import Any + +import voluptuous as vol +from homeassistant.config_entries import ( + ConfigEntry, + ConfigFlow, + ConfigFlowResult, + OptionsFlow, +) +from homeassistant.core import callback +from homeassistant.helpers import device_registry as dr +from homeassistant.helpers import selector + +from .const import CONF_AUTO_UPDATE, CONF_DEVICE_ID, DOMAIN, MANUFACTURER, MODEL + +STEP_USER_SCHEMA = vol.Schema( + { + vol.Required(CONF_DEVICE_ID): selector.DeviceSelector( + selector.DeviceSelectorConfig( + filter=[ + selector.DeviceFilterSelectorConfig( + integration="esphome", manufacturer=MANUFACTURER, model=MODEL + ) + ] + ) + ) + } +) + + +class HaControllerConfigFlow(ConfigFlow, domain=DOMAIN): + """Link one ESPHome screen device per config entry.""" + + VERSION = 1 + + @staticmethod + @callback + def async_get_options_flow(config_entry: ConfigEntry) -> OptionsFlowHandler: + return OptionsFlowHandler() + + async def async_step_user(self, user_input: dict[str, Any] | None = None) -> ConfigFlowResult: + errors: dict[str, str] = {} + if user_input is not None: + device = dr.async_get(self.hass).async_get(user_input[CONF_DEVICE_ID]) + if device is None or not self._is_screen(device): + errors["base"] = "not_ha_controller" + else: + await self.async_set_unique_id(device.id) + self._abort_if_unique_id_configured() + return self.async_create_entry( + title=device.name_by_user or device.name or "HA Controller", + data={CONF_DEVICE_ID: device.id}, + ) + return self.async_show_form( + step_id="user", + data_schema=self.add_suggested_values_to_schema(STEP_USER_SCHEMA, user_input), + errors=errors, + ) + + def _is_screen(self, device: dr.DeviceEntry) -> bool: + if device.manufacturer != MANUFACTURER or device.model != MODEL: + return False + return any( + (entry := self.hass.config_entries.async_get_entry(entry_id)) is not None + and entry.domain == "esphome" + for entry_id in device.config_entries + ) + + +class OptionsFlowHandler(OptionsFlow): + """Options of one screen.""" + + async def async_step_init(self, user_input: dict[str, Any] | None = None) -> ConfigFlowResult: + if user_input is not None: + return self.async_create_entry(data=user_input) + current = self.config_entry.options.get(CONF_AUTO_UPDATE, True) + return self.async_show_form( + step_id="init", + data_schema=vol.Schema({vol.Required(CONF_AUTO_UPDATE, default=current): bool}), + ) diff --git a/custom_components/ha_controller/const.py b/custom_components/ha_controller/const.py new file mode 100644 index 0000000..832627d --- /dev/null +++ b/custom_components/ha_controller/const.py @@ -0,0 +1,51 @@ +"""Constants for HA Controller. Protocol v1 values are defined here once.""" + +from datetime import timedelta + +DOMAIN = "ha_controller" +MANUFACTURER = "pyxel-dev" +MODEL = "ha-controller" + +CONF_DEVICE_ID = "device_id" +CONF_AUTO_UPDATE = "auto_update" + +PROTOCOL_VERSION = 1 + +EVENT_HELLO = "esphome.ha_controller_hello" +EVENT_CONTROL = "esphome.ha_controller_control" + +ACTION_SET_LAYOUT = "set_layout" +ACTION_SET_STATES = "set_states" +ACTION_INSTALL_FIRMWARE = "install_firmware" + +MAX_BLOCKS = 32 +MAX_ITEMS = 6 +MAX_NAME_LEN = 32 +MAX_TEXT_LEN = 64 +COORD_LIMIT = 32 +MAX_PAYLOAD_BYTES = 24576 +STATE_CHUNK_BYTES = 8192 + +FONT_SIZES = ("s", "m", "l", "xl") +ENTITY_BLOCK_DOMAINS = ("light", "climate") +ITEM_KINDS = ("text", "emoji", "entity", "battery", "brightness") + +# Screen sleep, in seconds. 0 means never. +DEFAULT_SLEEP_TIMEOUT = 20 +MIN_SLEEP_TIMEOUT = 5 +MAX_SLEEP_TIMEOUT = 3600 + +ONLINE_TIMEOUT = timedelta(seconds=150) +PUSH_RETRY = timedelta(seconds=300) +STATE_COALESCE_SECONDS = 0.2 +INSTALL_TIMEOUT = 300 +AUTO_UPDATE_RETRY = timedelta(seconds=3600) + +PANEL_URL_PATH = "ha-controller" +PANEL_COMPONENT = "ha-controller-panel" +PANEL_TITLE = "HA Controller" +PANEL_ICON = "mdi:remote" +STATIC_URL = "/ha_controller_static" + +FIRMWARE_BASE_URL = "https://pyxel-dev.github.io/HA-controller/firmware" +RELEASE_URL = "https://github.com/pyxel-dev/HA-controller/releases/tag/v{version}" diff --git a/custom_components/ha_controller/controller.py b/custom_components/ha_controller/controller.py new file mode 100644 index 0000000..9e9191d --- /dev/null +++ b/custom_components/ha_controller/controller.py @@ -0,0 +1,410 @@ +"""Per-screen controller: owns the layout and keeps the screen in sync.""" + +import asyncio +import logging +from collections.abc import Callable, Collection, Mapping +from dataclasses import dataclass +from datetime import datetime +from typing import Any + +import voluptuous as vol +from homeassistant.config_entries import ConfigEntry +from homeassistant.core import CALLBACK_TYPE, Event, HomeAssistant, callback +from homeassistant.exceptions import HomeAssistantError +from homeassistant.helpers.event import async_call_later, async_track_state_change_event +from homeassistant.util import dt as dt_util + +from .compiler import compile_layout, encode_payload +from .const import ( + ACTION_INSTALL_FIRMWARE, + ACTION_SET_LAYOUT, + ACTION_SET_STATES, + AUTO_UPDATE_RETRY, + CONF_AUTO_UPDATE, + CONF_DEVICE_ID, + EVENT_CONTROL, + EVENT_HELLO, + INSTALL_TIMEOUT, + MAX_PAYLOAD_BYTES, + ONLINE_TIMEOUT, + PROTOCOL_VERSION, + PUSH_RETRY, + STATE_COALESCE_SECONDS, +) +from .controls import resolve_control +from .firmware import firmware_urls, is_release_version +from .layout import LayoutError, bound_entities, empty_layout, validate_layout +from .states import build_updates, chunk_updates +from .store import LayoutStore + +_LOGGER = logging.getLogger(__name__) + +REASON_CONNECTED = "connected" +NO_REVISION = "none" + + +@dataclass +class DeviceStatus: + """What the screen last told us about itself.""" + + node: str | None = None + version: str | None = None + revision: str | None = None + protocol: int | None = None + last_seen: datetime | None = None + + def online(self) -> bool: + """Return True when a hello arrived within the online timeout.""" + return self.last_seen is not None and dt_util.utcnow() - self.last_seen <= ONLINE_TIMEOUT + + +def format_layout_errors(errors: list[LayoutError]) -> str: + """Format errors as `code@ref` (empty ref when None), comma separated.""" + return ", ".join(f"{e.code}@{e.ref or ''}" for e in errors) + + +class InvalidLayout(HomeAssistantError): + """Raised when a layout cannot be saved.""" + + def __init__(self, errors: list[LayoutError]) -> None: + super().__init__(format_layout_errors(errors)) + self.errors = errors + + +def _parse_protocol(value: Any) -> int | None: + try: + return int(value) + except TypeError, ValueError: + return None + + +class ScreenController: + """Owns the stored layout of one screen and pushes it to the device.""" + + def __init__( + self, + hass: HomeAssistant, + entry: ConfigEntry, + store: LayoutStore, + emoji: frozenset[str], + integration_version: str, + ) -> None: + self.hass = hass + self.entry = entry + self._store = store + self._emoji = emoji + self._integration_version = integration_version + self._layout: dict[str, Any] = empty_layout() + self._payload: dict[str, Any] = compile_layout(self._layout) + self._device = DeviceStatus() + self._last_push: tuple[str, datetime] | None = None + self._listeners: list[CALLBACK_TYPE] = [] + self._unsub_hello: CALLBACK_TYPE | None = None + self._unsub_control: CALLBACK_TYPE | None = None + self._unsub_states: CALLBACK_TYPE | None = None + self._cancel_flush: CALLBACK_TYPE | None = None + self._pending: set[str] = set() + self._first_hello_seen = False + self._install_in_progress = False + self._install_target: str | None = None + self._install_waiter: asyncio.Future[None] | None = None + self._auto_attempts: dict[str, datetime] = {} + self._auto_tasks: set[asyncio.Task[None]] = set() + + @property + def device_id(self) -> str: + return self.entry.data[CONF_DEVICE_ID] + + @property + def layout(self) -> dict[str, Any]: + return self._layout + + @property + def revision(self) -> str: + return self._payload["rev"] + + @property + def device(self) -> DeviceStatus: + return self._device + + @property + def integration_version(self) -> str: + return self._integration_version + + @property + def install_in_progress(self) -> bool: + return self._install_in_progress + + async def async_start(self) -> None: + """Load the layout and subscribe to the screen and its entities.""" + stored = await self._store.async_load() + if stored is not None: + errors = validate_layout(stored, self._emoji) + if errors: + _LOGGER.warning( + "Ignoring invalid stored layout for %s: %s", + self.entry.title, + format_layout_errors(errors), + ) + else: + self._set_layout(stored) + self._track_entities() + device_id = self.device_id + + @callback + def _is_ours(event_data: dict[str, Any] | Any) -> bool: + return event_data.get("device_id") == device_id + + self._unsub_hello = self.hass.bus.async_listen( + EVENT_HELLO, self._async_hello_event, event_filter=_is_ours + ) + self._unsub_control = self.hass.bus.async_listen( + EVENT_CONTROL, self._async_control_event, event_filter=_is_ours + ) + + async def async_stop(self) -> None: + """Cancel every subscription and pending timer.""" + if self._unsub_hello is not None: + self._unsub_hello() + self._unsub_hello = None + if self._unsub_control is not None: + self._unsub_control() + self._unsub_control = None + self._untrack_entities() + if self._cancel_flush is not None: + self._cancel_flush() + self._cancel_flush = None + self._pending.clear() + for task in list(self._auto_tasks): + task.cancel() + if self._install_waiter is not None and not self._install_waiter.done(): + self._install_waiter.set_exception(HomeAssistantError("The integration was unloaded.")) + self._listeners.clear() + + @callback + def async_add_listener(self, cb: Callable[[], None]) -> CALLBACK_TYPE: + """Call cb after every hello is recorded.""" + self._listeners.append(cb) + + @callback + def _remove() -> None: + if cb in self._listeners: + self._listeners.remove(cb) + + return _remove + + def _set_layout(self, layout: dict[str, Any]) -> None: + self._layout = layout + self._payload = compile_layout(layout) + self._track_entities() + + def _untrack_entities(self) -> None: + if self._unsub_states is not None: + self._unsub_states() + self._unsub_states = None + + def _track_entities(self) -> None: + self._untrack_entities() + entity_ids = list(bound_entities(self._layout)) + if entity_ids: + self._unsub_states = async_track_state_change_event( + self.hass, entity_ids, self._state_changed + ) + + def _can_push_states(self) -> bool: + return ( + self._device.node is not None + and self._device.protocol == PROTOCOL_VERSION + and self._device.online() + ) + + @callback + def _state_changed(self, event: Event) -> None: + if not self._can_push_states(): + return + self._pending.add(event.data["entity_id"]) + if self._cancel_flush is None: + self._cancel_flush = async_call_later( + self.hass, STATE_COALESCE_SECONDS, self._async_flush + ) + + async def _async_flush(self, _now: datetime) -> None: + self._cancel_flush = None + entity_ids, self._pending = self._pending, set() + if entity_ids and self._can_push_states(): + await self.async_push_states(entity_ids) + + async def async_save_layout(self, layout: dict[str, Any]) -> tuple[str, bool]: + """Validate, store and (when the screen is online) push a layout.""" + errors = validate_layout(layout, self._emoji) + if errors: + raise InvalidLayout(errors) + payload = compile_layout(layout) + if len(encode_payload(payload).encode("utf-8")) > MAX_PAYLOAD_BYTES: + raise InvalidLayout([LayoutError("payload_too_large", None)]) + await self._store.async_save(layout) + self._set_layout(layout) + pushed = False + if self._device.protocol == PROTOCOL_VERSION and self._device.online(): + pushed = await self.async_push_layout() + return self.revision, pushed + + async def async_handle_hello(self, data: dict[str, Any]) -> None: + """Record a hello and resync the screen (spec §7.5).""" + revision = data.get("revision") + self._device = DeviceStatus( + node=data.get("node") or self._device.node, + version=data.get("version"), + revision=None if revision in (None, NO_REVISION) else revision, + protocol=_parse_protocol(data.get("protocol")), + last_seen=dt_util.utcnow(), + ) + version = self._device.version + if ( + self._install_waiter is not None + and not self._install_waiter.done() + and version == self._install_target + ): + self._install_waiter.set_result(None) + self._notify_listeners() + self._maybe_auto_update() + if self._device.protocol != PROTOCOL_VERSION: + return + first_hello = not self._first_hello_seen + self._first_hello_seen = True + connected = data.get("reason") == REASON_CONNECTED or first_hello + if revision != self.revision: + if connected or not self._recently_pushed(): + await self.async_push_layout() + elif connected: + await self.async_push_states() + + def _maybe_auto_update(self) -> None: + """Start an automatic firmware install when the screen runs another version.""" + version = self._integration_version + if ( + not self.entry.options.get(CONF_AUTO_UPDATE, True) + or not is_release_version(version) + or self._device.version is None + or self._device.version == version + or self._install_in_progress + ): + return + now = dt_util.utcnow() + last = self._auto_attempts.get(version) + if last is not None and now - last < AUTO_UPDATE_RETRY: + return + self._auto_attempts[version] = now + task = self.hass.async_create_background_task( + self._async_auto_install(version), f"ha_controller auto update {self.entry.title}" + ) + self._auto_tasks.add(task) + task.add_done_callback(self._auto_tasks.discard) + + async def _async_auto_install(self, version: str) -> None: + try: + await self.async_install_firmware(version) + except HomeAssistantError as err: + _LOGGER.warning("Automatic firmware update of %s failed: %s", self.entry.title, err) + + async def async_install_firmware(self, version: str) -> None: + """Install a firmware version and wait until the screen reports it.""" + if not self._device.online(): + raise HomeAssistantError("The screen is offline.") + if self._install_in_progress: + raise HomeAssistantError("A firmware update is already running.") + self._install_in_progress = True + self._install_target = version + waiter = self.hass.loop.create_future() + self._install_waiter = waiter + self._notify_listeners() + try: + url, md5_url = firmware_urls(version) + if not await self.async_call_device( + ACTION_INSTALL_FIRMWARE, {"url": url, "md5_url": md5_url} + ): + raise HomeAssistantError("The screen did not accept the firmware update.") + try: + async with asyncio.timeout(INSTALL_TIMEOUT): + await waiter + except TimeoutError: + raise HomeAssistantError( + f"Firmware update to {version} did not complete." + ) from None + finally: + self._install_in_progress = False + self._install_target = None + self._install_waiter = None + self._notify_listeners() + + def _notify_listeners(self) -> None: + for cb in list(self._listeners): + cb() + + async def _async_hello_event(self, event: Event) -> None: + await self.async_handle_hello(event.data) + + async def _async_control_event(self, event: Event) -> None: + await self.async_handle_control(event.data) + + async def async_handle_control(self, data: Mapping[str, Any]) -> None: + """Run the service call a control event maps to (spec §7.6).""" + call = resolve_control(self._layout, self.hass, data) + if call is None: + return + try: + await self.hass.services.async_call(call.domain, call.service, call.data, blocking=True) + except (HomeAssistantError, vol.Invalid) as err: + _LOGGER.warning("Calling %s.%s failed: %s", call.domain, call.service, err) + + def _recently_pushed(self) -> bool: + if self._last_push is None: + return False + revision, when = self._last_push + return revision == self.revision and dt_util.utcnow() - when < PUSH_RETRY + + async def async_push_layout(self) -> bool: + """Send the layout, then all states. Return True on success.""" + self._last_push = (self.revision, dt_util.utcnow()) + ok = await self.async_call_device( + ACTION_SET_LAYOUT, {"layout": encode_payload(self._payload)} + ) + return ok and await self.async_push_states() + + async def async_push_states(self, entity_ids: Collection[str] | None = None) -> bool: + """Send the state updates for entity_ids (all when None).""" + updates = build_updates(self.hass, self._layout, entity_ids) + for chunk in chunk_updates(updates): + if not await self.async_call_device(ACTION_SET_STATES, {"states": chunk}): + return False + return True + + async def async_call_device(self, action: str, data: dict[str, Any]) -> bool: + """Call an ESPHome service of the screen. Return False on failure.""" + node = self._device.node + if node is None: + return False + service = f"{node.replace('-', '_')}_{action}" + try: + await self.hass.services.async_call("esphome", service, data, blocking=True) + except (HomeAssistantError, vol.Invalid) as err: + _LOGGER.warning("Calling esphome.%s failed: %s", service, err) + return False + return True + + def status(self) -> dict[str, Any]: + """Return this screen as one ha_controller/screens item.""" + device = self._device + return { + "entry_id": self.entry.entry_id, + "title": self.entry.title, + "device_id": self.device_id, + "online": device.online(), + "firmware_version": device.version, + "integration_version": self._integration_version, + "protocol_ok": None + if device.last_seen is None + else device.protocol == PROTOCOL_VERSION, + "revision": self.revision, + "device_revision": device.revision, + } diff --git a/custom_components/ha_controller/controls.py b/custom_components/ha_controller/controls.py new file mode 100644 index 0000000..4f8920e --- /dev/null +++ b/custom_components/ha_controller/controls.py @@ -0,0 +1,69 @@ +"""Map screen control events to Home Assistant service calls (spec §7.6).""" + +from __future__ import annotations + +import math +from collections.abc import Mapping +from typing import Any, NamedTuple + +from homeassistant.core import HomeAssistant + +DEFAULT_MIN_TEMP = 7 +DEFAULT_MAX_TEMP = 35 + + +class ControlCall(NamedTuple): + """A service call to make for a control event.""" + + domain: str + service: str + data: dict[str, Any] + + +def _parse_value(raw: Any) -> float | None: + try: + value = float(raw) + except TypeError, ValueError: + return None + return value if math.isfinite(value) else None + + +def _bound(hass: HomeAssistant, entity_id: str, attribute: str, default: float) -> float: + state = hass.states.get(entity_id) + value = _parse_value(state.attributes.get(attribute)) if state else None + return default if value is None else value + + +def resolve_control( + layout: dict[str, Any], hass: HomeAssistant, data: Mapping[str, Any] +) -> ControlCall | None: + """Return the service call for a control event, or None to ignore it.""" + block = next((b for b in layout["blocks"] if b["id"] == data.get("block")), None) + if block is None or block["type"] != "entity": + return None + entity_id = block["entity_id"] + domain = entity_id.split(".", 1)[0] + op = data.get("op") + if domain == "light": + if op == "toggle": + return ControlCall("light", "toggle", {"entity_id": entity_id}) + if op == "set": + value = _parse_value(data.get("value")) + if value is None: + return None + if value <= 0: + return ControlCall("light", "turn_off", {"entity_id": entity_id}) + pct = round(min(max(value, 1), 100)) + return ControlCall("light", "turn_on", {"entity_id": entity_id, "brightness_pct": pct}) + elif domain == "climate" and op == "set": + value = _parse_value(data.get("value")) + if value is None: + return None + low = _bound(hass, entity_id, "min_temp", DEFAULT_MIN_TEMP) + high = _bound(hass, entity_id, "max_temp", DEFAULT_MAX_TEMP) + return ControlCall( + "climate", + "set_temperature", + {"entity_id": entity_id, "temperature": min(max(value, low), high)}, + ) + return None diff --git a/custom_components/ha_controller/emoji.json b/custom_components/ha_controller/emoji.json new file mode 100644 index 0000000..8ced6fd --- /dev/null +++ b/custom_components/ha_controller/emoji.json @@ -0,0 +1,66 @@ +[ + "💡", + "🔥", + "❄", + "🌡", + "💧", + "🌬", + "☀", + "🌙", + "⭐", + "☁", + "⛅", + "🌧", + "⚡", + "🔋", + "🔌", + "🏠", + "🛋", + "🛏", + "🛁", + "🚿", + "🍳", + "🍽", + "☕", + "🍷", + "🧺", + "🪴", + "🚪", + "🪟", + "🔒", + "🔓", + "🔑", + "🔔", + "🔕", + "🔊", + "🔇", + "🎵", + "📺", + "🎮", + "💻", + "📱", + "⏰", + "📅", + "🚗", + "🚲", + "🐶", + "🐱", + "👶", + "👋", + "👍", + "❤", + "😀", + "😴", + "🎉", + "🎄", + "✅", + "❌", + "⚠", + "ℹ", + "▶", + "⏸", + "♻", + "🌀", + "🧊", + "🏡" +] diff --git a/custom_components/ha_controller/firmware.py b/custom_components/ha_controller/firmware.py new file mode 100644 index 0000000..0c560b8 --- /dev/null +++ b/custom_components/ha_controller/firmware.py @@ -0,0 +1,18 @@ +"""Firmware locations and version rules.""" + +import re + +from .const import FIRMWARE_BASE_URL + +_RELEASE = re.compile(r"^\d+\.\d+\.\d+$") + + +def firmware_urls(version: str) -> tuple[str, str]: + """Return the OTA image URL and its MD5 URL for a version.""" + url = f"{FIRMWARE_BASE_URL}/{version}/ha-controller.ota.bin" + return url, f"{url}.md5" + + +def is_release_version(version: str) -> bool: + """Return True for a plain release version such as 1.2.3.""" + return _RELEASE.match(version) is not None diff --git a/custom_components/ha_controller/frontend/dev/index.html b/custom_components/ha_controller/frontend/dev/index.html new file mode 100644 index 0000000..457f262 --- /dev/null +++ b/custom_components/ha_controller/frontend/dev/index.html @@ -0,0 +1,25 @@ + + + + + + HA Controller panel (mock) + + + + + + + diff --git a/custom_components/ha_controller/frontend/dev/mock-hass.ts b/custom_components/ha_controller/frontend/dev/mock-hass.ts new file mode 100644 index 0000000..5e1c907 --- /dev/null +++ b/custom_components/ha_controller/frontend/dev/mock-hass.ts @@ -0,0 +1,51 @@ +import type {Hass, HassEntity, Layout, ScreenInfo} from "../src/types"; +import reference from "../../../../docs/protocol/fixtures/layouts/valid/reference.json"; + +const entity = (entity_id: string, state: string, friendly_name: string, extra: Record = {}): HassEntity => ({ + entity_id, + state, + attributes: {friendly_name, ...extra}, +}); + +/** A `hass` with a few entities and one screen whose layout lives in memory. */ +export function createMockHass(screen: Partial = {}): Hass { + let layout = structuredClone(reference) as Layout; + let revision = 1; + const info = (): ScreenInfo => ({ + entry_id: "mock-entry", + title: "Kitchen screen", + device_id: "mock-device", + online: true, + firmware_version: "0.1.0", + integration_version: "0.1.0", + protocol_ok: true, + revision: `r${revision}`, + device_revision: `r${revision}`, + ...screen, + }); + const states = Object.fromEntries( + [ + entity("light.kitchen", "on", "Kitchen"), + entity("light.living_room", "off", "Living room"), + entity("climate.bedroom", "heat", "Bedroom"), + entity("sensor.outdoor_temperature", "21.5", "Outdoor temperature", {unit_of_measurement: "°C"}), + ].map((e) => [e.entity_id, e]), + ); + return { + states, + async callWS(msg: {type: string; [key: string]: unknown}): Promise { + switch (msg.type) { + case "ha_controller/screens": + return {screens: [info()]} as T; + case "ha_controller/layout/get": + return {layout: structuredClone(layout)} as T; + case "ha_controller/layout/save": + layout = structuredClone(msg.layout as Layout); + revision += 1; + return {revision: `r${revision}`, pushed: true} as T; + default: + throw {code: "unknown_command", message: `Unknown command ${msg.type}`}; + } + }, + }; +} diff --git a/custom_components/ha_controller/frontend/package-lock.json b/custom_components/ha_controller/frontend/package-lock.json new file mode 100644 index 0000000..cdbc800 --- /dev/null +++ b/custom_components/ha_controller/frontend/package-lock.json @@ -0,0 +1,1752 @@ +{ + "name": "ha-controller-panel", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "ha-controller-panel", + "version": "0.1.0", + "dependencies": { + "lit": "^3.3.3" + }, + "devDependencies": { + "happy-dom": "^21.0.4", + "typescript": "^7.0.2", + "vite": "^8.3.8", + "vitest": "^5.1.0" + } + }, + "node_modules/@emnapi/core": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.2.tgz", + "integrity": "sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "2.2.0", + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/runtime": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-beta.2.tgz", + "integrity": "sha512-JcrSPzPvZuNZvJqPTF9Fw25LbOJ8avzFVlaf2grmH4Cku0oGP47tRgqPZadcfj3YoZMHkFVnCYFbQM8I+i5QEw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/wasi-threads": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.2.0.tgz", + "integrity": "sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz", + "integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@lit-labs/ssr-dom-shim": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@lit-labs/ssr-dom-shim/-/ssr-dom-shim-1.6.0.tgz", + "integrity": "sha512-VHb0ALPMTlgKjM6yIxxoQNnpKyUKLD04VzeQdsiXkMqkvYlAHxq9glGLmgbb889/1GsohSOAjvQYoiBppXFqrQ==", + "license": "BSD-3-Clause" + }, + "node_modules/@lit/reactive-element": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/@lit/reactive-element/-/reactive-element-2.1.2.tgz", + "integrity": "sha512-pbCDiVMnne1lYUIaYNN5wrwQXDtHaYtg7YEFPeW+hws6U47WeFvISGUWekPGKWOP1ygrs0ef0o1VJMk1exos5A==", + "license": "BSD-3-Clause", + "dependencies": { + "@lit-labs/ssr-dom-shim": "^1.5.0" + } + }, + "node_modules/@napi-rs/wasm-runtime": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.6.tgz", + "integrity": "sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.3" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1 || 2.0.0-beta.2", + "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.156.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.156.0.tgz", + "integrity": "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.19.tgz", + "integrity": "sha512-e+Ebe0WT+9tbXmNKPIiC8YrWAHYwug3m6i4p3rZGGulfZri1jtI4HslT+OZnFf/OIHowWF71DTlHwXBP2SiA7A==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.19.tgz", + "integrity": "sha512-hOombrTJ+szt2ciEzS7oCA78lMPBgF5UMQWCJIyNfnrI7GLl8HYoFqCnpL2gcPOaXMqryGCU5ExdQKyDDcC+yA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.19.tgz", + "integrity": "sha512-XoMA2pwCKGTQzUjPgtRwkedH4WmXhdIPKT6l6oOxd1PUbNodGI6DcBekgN7EC//+x3pfBYX/qL1gNmZAqivw5g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.19.tgz", + "integrity": "sha512-zo8EsSSwMZCY/e+fRnGaX02YGgvJD0yvhNi/9hpGPA2MJ9ZF8dPCw75UGfpI6OpQ/myR/dIYmogRvqiZD0TrXg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.19.tgz", + "integrity": "sha512-O8ISAOfI1nj7AuBPd30FSF47z7f7lzlk5poQVGgiikvQuGEBFYvW8ki+UEnT+YJPnNGjQzn304klt4O9FUE7mA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.19.tgz", + "integrity": "sha512-/lYCba5NO0yq4S0jGMH8QTBtkvQxoXjoQWzF5BcWp9MjB9jxVRD1GQDNofkVjcOj30DWyhLIN/4Oe60JKzaONw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.19.tgz", + "integrity": "sha512-pm/apFMBnSbFb3O6nG5pHO1iqHhZrjGDFEjSm+ot9J17XXPvH9L90y5h+jgfHCE+Qdlsvy8qKEcU4VKxgjD+vA==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.19.tgz", + "integrity": "sha512-K1SmQp3FFichn8oqrNIwvFoZ5wcvjC7goBzpaMNvLf9FZc+QB/QvLmnpJZgAAGHiD980tP8FZZnXk2K94rvlxg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.19.tgz", + "integrity": "sha512-I0xwD57jP/3A7+5UPZin2w8Y7XHEmEM5zqpYZOcQ45MlNW6tUJUziymV3yRr7rL4vwyfEcRsRksC4a7Kc08p5Q==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.19.tgz", + "integrity": "sha512-BrtEHT24SNXj9HiXqy+s/kXiSiQGt6EKCPUlRirAoIioVxKGnbXBUEkbZASAei7iZJB0/Ynm+0JP00Ipx7AnSw==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.19.tgz", + "integrity": "sha512-rm75/9DkHKeU2WnA8w4X94WGYgLlDCFCfkQC+4bguVJmC/jvDRv2B+2wLOYhyE0fVuv7//Ckk39OoOufyCu76Q==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.19.tgz", + "integrity": "sha512-irh/4+iYFM4GAzpluDErgjz89bj6NDtqqMAG/6O1LG38Ed3NpyebzCpcVNkFW8uhy+/3/BocUvnXDR33CXWe9A==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.19.tgz", + "integrity": "sha512-+KWTWNoPt+CfSq94CiceWu3yPE+QzkaG+phPyz9G60tmZLwfQkcA4AeksafzvJAw4pvg1mcd5a1TkUqVv0s4JA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-wasm32-wasi": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.2.19.tgz", + "integrity": "sha512-7EH+skOsl5qpWnK0vzamgJFhOv1cwxQpsxm8tI883K9fur5c27p8q87fzEO6BbBPabA2/+s/zR63/pLc137iOg==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "2.0.0-beta.2", + "@emnapi/runtime": "2.0.0-beta.2", + "@napi-rs/wasm-runtime": "1.2.6" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.19.tgz", + "integrity": "sha512-3Q1Yg1Q7tEvBWoZf5rFvG/GKZQPgwfru+p4wBajDfJFBs0SHCpL++dfTjW9gyAKd1T7ZpIYvdaUax7Pa/IhFVQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.19.tgz", + "integrity": "sha512-y/sqRRc6d7hECzOFc5n3LSeqctmIp9mMjY1Kq4s14uLPd/LZ4z7i1zrW6fMtp2mPeuQIC4e6ULMcwQzMomqQag==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.1.1.tgz", + "integrity": "sha512-glFIJDvLNDtJhT9qrMFWLPbvS+skxgt4L0K8Ei2YtnhPysAJnsI7nyxSJxKj4ADeKX0OLjC4ntRkwpLOoS3rwA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@tybys/wasm-util": { + "version": "0.10.5", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.5.tgz", + "integrity": "sha512-dOGOPxlaNV+G046mZzN+9C0dAcQZeSKcXiVaM0TYy/LM4ttTmgSBDxYfovcYI8Em3+eAbiAYpvWLOv8+ZVRJKA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz", + "integrity": "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "26.6.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz", + "integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~8.9.0" + } + }, + "node_modules/@types/trusted-types": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", + "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==", + "license": "MIT" + }, + "node_modules/@types/whatwg-mimetype": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/whatwg-mimetype/-/whatwg-mimetype-3.0.2.tgz", + "integrity": "sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/ws": { + "version": "8.18.2", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.2.tgz", + "integrity": "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@typescript/typescript-aix-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", + "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz", + "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz", + "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz", + "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz", + "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz", + "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz", + "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-loong64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz", + "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-mips64el": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz", + "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz", + "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-riscv64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz", + "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-s390x": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz", + "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz", + "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz", + "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz", + "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz", + "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz", + "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-sunos-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz", + "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz", + "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz", + "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@vitest/mocker": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.1.0.tgz", + "integrity": "sha512-5umB9/jlWcqVS6fsrFmv5Gdnpu6wAUio/lEOwAmvB7v+lFo/IW2B9FhAD0p19GCULTgMzLCdUmuCDCnAzWgppQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.31", + "@vitest/spy": "5.1.0", + "estree-walker": "^3.0.3", + "magic-string": "^1.4.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9 || ^3.0.0", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/spy": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.1.0.tgz", + "integrity": "sha512-2DPO5OMHWKrBngC+fCmTQqemNF0gidRhp3lxbBmRhW+M1XJrfgPpqNqWVevXtn2f2ufD5ZaR1B6B641aAlcX5A==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/buffer-image-size": { + "version": "0.6.4", + "resolved": "https://registry.npmjs.org/buffer-image-size/-/buffer-image-size-0.6.4.tgz", + "integrity": "sha512-nEh+kZOPY1w+gcCMobZ6ETUp9WfibndnosbpwB1iJk/8Gt5ZF2bhS6+B6bPYz424KtwsR6Rflc3tCz1/ghX2dQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/chai": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz", + "integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/entities": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz", + "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/es-module-lexer": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", + "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", + "dev": true, + "license": "MIT" + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/happy-dom": { + "version": "21.0.4", + "resolved": "https://registry.npmjs.org/happy-dom/-/happy-dom-21.0.4.tgz", + "integrity": "sha512-tFm+GaLBgo6o0awHnvHaNoraVo27qJ+2tZEtZ+cIa08hXbeitrxAJajLI05hsUy/2/YTKcUjQYzHe5mCcraLBw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": ">=20.0.0", + "@types/whatwg-mimetype": "^3.0.2", + "@types/ws": "^8.18.1", + "buffer-image-size": "^0.6.4", + "entities": "^7.0.1", + "whatwg-mimetype": "^3.0.0", + "ws": "^8.21.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lit": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/lit/-/lit-3.3.3.tgz", + "integrity": "sha512-fycuvZg/hkpozL00lm1pEJH5nN/lr9ZXd6mJI2HSN4+Bzc+LDNdEApJ6HFbPkdFNHLvOplIIuJvxkS4XUxqirw==", + "license": "BSD-3-Clause", + "dependencies": { + "@lit/reactive-element": "^2.1.0", + "lit-element": "^4.2.0", + "lit-html": "^3.3.0" + } + }, + "node_modules/lit-element": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/lit-element/-/lit-element-4.2.2.tgz", + "integrity": "sha512-aFKhNToWxoyhkNDmWZwEva2SlQia+jfG0fjIWV//YeTaWrVnOxD89dPKfigCUspXFmjzOEUQpOkejH5Ly6sG0w==", + "license": "BSD-3-Clause", + "dependencies": { + "@lit-labs/ssr-dom-shim": "^1.5.0", + "@lit/reactive-element": "^2.1.0", + "lit-html": "^3.3.0" + } + }, + "node_modules/lit-html": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/lit-html/-/lit-html-3.3.3.tgz", + "integrity": "sha512-el8M6jK2o3RXBnrSHX3ZKrsN8zEV63pSExTO1wYJz7QndGYZ8353e2a5PPX+qHe2aGayfnchQmkAojaWAREOIA==", + "license": "BSD-3-Clause", + "dependencies": { + "@types/trusted-types": "^2.0.2" + } + }, + "node_modules/magic-string": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", + "integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/obug": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/obug/-/obug-3.0.0.tgz", + "integrity": "sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT", + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.33", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz", + "integrity": "sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/rolldown": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.19.tgz", + "integrity": "sha512-QIiV1J9d0pzN4jeeTH4sjPy0AZ6cAy2cG0ExeoE1+U8Rvj+hR3gYkokx0YbeUNGlZqiQJJ2utcETe0oKXwzsuA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.156.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm-eabi": "1.2.19", + "@rolldown/binding-android-arm64": "1.2.19", + "@rolldown/binding-darwin-arm64": "1.2.19", + "@rolldown/binding-darwin-x64": "1.2.19", + "@rolldown/binding-freebsd-x64": "1.2.19", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.19", + "@rolldown/binding-linux-arm64-gnu": "1.2.19", + "@rolldown/binding-linux-arm64-musl": "1.2.19", + "@rolldown/binding-linux-ppc64-gnu": "1.2.19", + "@rolldown/binding-linux-s390x-gnu": "1.2.19", + "@rolldown/binding-linux-x64-gnu": "1.2.19", + "@rolldown/binding-linux-x64-musl": "1.2.19", + "@rolldown/binding-openharmony-arm64": "1.2.19", + "@rolldown/binding-wasm32-wasi": "1.2.19", + "@rolldown/binding-win32-arm64-msvc": "1.2.19", + "@rolldown/binding-win32-x64-msvc": "1.2.19" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/std-env": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz", + "integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinybench": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.3.tgz", + "integrity": "sha512-Al01C2JIBnO2CXCAPbpAl6sUiOZHeThGtHYNTa51JRw9PyWOCdr+9Ong05R4qg/Sk3+H645E8ov1h2c58ityNw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/tinyexec": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz", + "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tslib": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", + "dev": true, + "license": "0BSD", + "optional": true + }, + "node_modules/typescript": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz", + "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc" + }, + "engines": { + "node": ">=16.20.0" + }, + "optionalDependencies": { + "@typescript/typescript-aix-ppc64": "7.0.2", + "@typescript/typescript-darwin-arm64": "7.0.2", + "@typescript/typescript-darwin-x64": "7.0.2", + "@typescript/typescript-freebsd-arm64": "7.0.2", + "@typescript/typescript-freebsd-x64": "7.0.2", + "@typescript/typescript-linux-arm": "7.0.2", + "@typescript/typescript-linux-arm64": "7.0.2", + "@typescript/typescript-linux-loong64": "7.0.2", + "@typescript/typescript-linux-mips64el": "7.0.2", + "@typescript/typescript-linux-ppc64": "7.0.2", + "@typescript/typescript-linux-riscv64": "7.0.2", + "@typescript/typescript-linux-s390x": "7.0.2", + "@typescript/typescript-linux-x64": "7.0.2", + "@typescript/typescript-netbsd-arm64": "7.0.2", + "@typescript/typescript-netbsd-x64": "7.0.2", + "@typescript/typescript-openbsd-arm64": "7.0.2", + "@typescript/typescript-openbsd-x64": "7.0.2", + "@typescript/typescript-sunos-x64": "7.0.2", + "@typescript/typescript-win32-arm64": "7.0.2", + "@typescript/typescript-win32-x64": "7.0.2" + } + }, + "node_modules/undici-types": { + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", + "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==", + "dev": true, + "license": "MIT" + }, + "node_modules/vite": { + "version": "8.3.8", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.8.tgz", + "integrity": "sha512-LzOn3h9rG/0vhLdXrV4yJ4QFA9eEoqCl+Yx+kGJd7aB9w6nfNgVHKSYwLPZUHrz4ZGa+t+kXjV9itvcHDLQouA==", + "dev": true, + "license": "MIT", + "dependencies": { + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.32", + "rolldown": "~1.2.18", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.7.1 || ^0.8.0", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vitest": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.1.0.tgz", + "integrity": "sha512-MzmNFnrwa8v8lF1bLxw3UJ4EREwVOVb75VqJZmUDRjJ6EluK/x9th7qTbaeDk41WxE1GxWqmTXcdsfobfH5sOA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/mocker": "5.1.0", + "chai": "^6.3.0", + "es-module-lexer": "^2.3.2", + "expect-type": "^1.4.0", + "magic-string": "^1.4.3", + "obug": "^3.0.0", + "picomatch": "^4.0.7", + "std-env": "^4.3.0", + "tinybench": "^6.2.2", + "tinyexec": "^1.3.1", + "tinyglobby": "^0.2.17", + "why-is-node-running": "3.2.1" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^22.12.0 || ^24.0.0 || >=26.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "5.1.0", + "@vitest/browser-preview": "5.1.0", + "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", + "@vitest/coverage-istanbul": "5.1.0", + "@vitest/coverage-v8": "5.1.0", + "@vitest/ui": "5.1.0", + "happy-dom": "*", + "jsdom": "*", + "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/coverage-istanbul": { + "optional": true + }, + "@vitest/coverage-v8": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "vite": { + "optional": false + } + } + }, + "node_modules/whatwg-mimetype": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-3.0.0.tgz", + "integrity": "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/why-is-node-running": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-3.2.1.tgz", + "integrity": "sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==", + "dev": true, + "license": "MIT", + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=20.11" + } + }, + "node_modules/ws": { + "version": "8.23.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.23.0.tgz", + "integrity": "sha512-wCkmX8QMOrKjgO8HW2WyDbTSGeqkocxgDzS9iR79rEAexty6/2qzilx3Ag8Tqf9ykop3irLKle0MtVn5qjVnoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + } + } +} diff --git a/custom_components/ha_controller/frontend/package.json b/custom_components/ha_controller/frontend/package.json new file mode 100644 index 0000000..be5858d --- /dev/null +++ b/custom_components/ha_controller/frontend/package.json @@ -0,0 +1,21 @@ +{ + "name": "ha-controller-panel", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "dev": "vite --open dev/index.html", + "build": "tsc --noEmit && vite build", + "test": "vitest run", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "lit": "^3.3.3" + }, + "devDependencies": { + "happy-dom": "^21.0.4", + "typescript": "^7.0.2", + "vite": "^8.3.8", + "vitest": "^5.1.0" + } +} diff --git a/custom_components/ha_controller/frontend/src/api.ts b/custom_components/ha_controller/frontend/src/api.ts new file mode 100644 index 0000000..e86a35b --- /dev/null +++ b/custom_components/ha_controller/frontend/src/api.ts @@ -0,0 +1,19 @@ +import type {Hass, Layout, ScreenInfo} from "./types"; + +export async function listScreens(hass: Hass): Promise { + const result = await hass.callWS<{screens: ScreenInfo[]}>({type: "ha_controller/screens"}); + return result.screens; +} + +export async function getLayout(hass: Hass, entryId: string): Promise { + const result = await hass.callWS<{layout: Layout}>({type: "ha_controller/layout/get", entry_id: entryId}); + return result.layout; +} + +export function saveLayout( + hass: Hass, + entryId: string, + layout: Layout, +): Promise<{revision: string; pushed: boolean}> { + return hass.callWS({type: "ha_controller/layout/save", entry_id: entryId, layout}); +} diff --git a/custom_components/ha_controller/frontend/src/components/hc-block-editor.ts b/custom_components/ha_controller/frontend/src/components/hc-block-editor.ts new file mode 100644 index 0000000..3b34ce6 --- /dev/null +++ b/custom_components/ha_controller/frontend/src/components/hc-block-editor.ts @@ -0,0 +1,260 @@ +import {LitElement, css, html, nothing} from "lit"; +import {property} from "lit/decorators.js"; +import {repeat} from "lit/directives/repeat.js"; +import {defineElement} from "../define"; +import "./hc-entity-input"; +import "./hc-item-editor"; +import "./hc-preview"; +import {FONT_SIZE_LABEL, FONT_SIZE_ORDER, ITEM_KIND_LABEL, UI, deleteReason} from "../messages"; +import {canDelete} from "../model/grid"; +import { + PALETTE, addItem, deleteBlock, moveItem, removeItem, setStart, updateBlock, updateItem, +} from "../model/edit"; +import {MAX_ITEMS} from "../model/limits"; +import type {Block, Hass, Item, ItemKind, Layout} from "../types"; + + +/** Editor for the selected block. Emits `hc-layout-change` with the complete new layout. */ +export class HcBlockEditor extends LitElement { + @property({attribute: false}) hass?: Hass; + @property({attribute: false}) layout!: Layout; + @property() blockId = ""; + + static styles = css` + :host { + display: block; + color: var(--primary-text-color, #212121); + } + .form { + display: grid; + gap: 12px; + } + label, + .label { + display: block; + font-size: 12px; + color: var(--secondary-text-color, #727272); + margin-bottom: 4px; + } + input[type="text"], + select { + box-sizing: border-box; + width: 100%; + font: inherit; + padding: 6px 8px; + color: var(--primary-text-color, #212121); + background: var(--card-background-color, #fff); + border: 1px solid var(--divider-color, rgba(0, 0, 0, 0.12)); + border-radius: 6px; + } + .row { + display: flex; + gap: 6px; + align-items: center; + flex-wrap: wrap; + } + button.swatch { + width: 28px; + height: 28px; + border-radius: 50%; + border: 2px solid transparent; + cursor: pointer; + padding: 0; + } + button.swatch[aria-pressed="true"] { + border-color: var(--primary-text-color, #212121); + } + button.font-size { + min-width: 36px; + padding: 4px 8px; + cursor: pointer; + color: var(--primary-text-color, #212121); + background: var(--card-background-color, #fff); + border: 1px solid var(--divider-color, rgba(0, 0, 0, 0.12)); + border-radius: 6px; + } + button.font-size[aria-pressed="true"] { + border-color: var(--primary-color, #03a9f4); + box-shadow: 0 0 0 1px var(--primary-color, #03a9f4); + } + input[type="color"] { + width: 36px; + height: 28px; + padding: 0; + } + .items { + display: grid; + gap: 8px; + } + .reason { + font-size: 12px; + color: var(--error-color, #db4437); + } + button.delete:not([disabled]) { + color: var(--error-color, #db4437); + } + `; + + private get block(): Block | undefined { + return this.layout?.blocks.find((b) => b.id === this.blockId); + } + + render() { + const block = this.block; + if (!block) return nothing; + const check = canDelete(this.layout, block.id); + const isStart = this.layout.start === block.id; + return html`
+
+ + +
+
+ ${UI.background} +
+ ${PALETTE.map( + (colour) => html``, + )} + + this.change(updateBlock(this.layout, block.id, {background: (e.target as HTMLInputElement).value.toUpperCase()}))} + /> +
+
+
+ ${UI.fontSize} +
+ ${FONT_SIZE_ORDER.map( + (size) => html``, + )} +
+
+
+ + +
+ ${block.type === "entity" ? this.entityFields(block) : this.customFields(block)} +
+ + +
+ ${check.ok ? nothing : html`
${deleteReason[check.reason]}
`} + +
`; + } + + protected updated(): void { + const select = this.renderRoot.querySelector("select[name=type]"); + if (select && this.block) select.value = this.block.type; + } + + private entityFields(block: Block) { + return html`
+ ${UI.entity} + ) => { + e.stopPropagation(); + this.change(updateBlock(this.layout, block.id, {entity_id: e.detail.value})); + }} + > +
`; + } + + private customFields(block: Block) { + const items = block.items ?? []; + return html`
+ ${repeat( + items, + (item) => item.id, + (item, index) => html`}>) => { + e.stopPropagation(); + this.change(updateItem(this.layout, block.id, item.id, e.detail.patch)); + }} + @hc-item-move=${(e: CustomEvent<{delta: -1 | 1}>) => { + e.stopPropagation(); + this.change(moveItem(this.layout, block.id, item.id, e.detail.delta)); + }} + @hc-item-remove=${(e: Event) => { + e.stopPropagation(); + this.change(removeItem(this.layout, block.id, item.id)); + }} + >`, + )} +
+ + +
+
`; + } + + private onName = (e: Event): void => { + const block = this.block; + if (block) this.change(updateBlock(this.layout, block.id, {name: (e.target as HTMLInputElement).value})); + }; + + private onType = (e: Event): void => { + const block = this.block; + if (!block) return; + const type = (e.target as HTMLSelectElement).value as Block["type"]; + if (type === block.type) return; + this.change(updateBlock(this.layout, block.id, type === "custom" ? {type, items: block.items ?? []} : {type})); + }; + + private onAddItem = (e: Event): void => { + const select = e.target as HTMLSelectElement; + const block = this.block; + if (!block || select.value === "") return; + const kind = select.value as ItemKind; + select.value = ""; + this.change(addItem(this.layout, block.id, kind).layout); + }; + + private change(layout: Layout): void { + this.dispatchEvent(new CustomEvent("hc-layout-change", {detail: {layout}, bubbles: true, composed: true})); + } +} + +defineElement("hc-block-editor", HcBlockEditor); + +declare global { + interface HTMLElementTagNameMap { + "hc-block-editor": HcBlockEditor; + } +} diff --git a/custom_components/ha_controller/frontend/src/components/hc-emoji-picker.ts b/custom_components/ha_controller/frontend/src/components/hc-emoji-picker.ts new file mode 100644 index 0000000..c7dc744 --- /dev/null +++ b/custom_components/ha_controller/frontend/src/components/hc-emoji-picker.ts @@ -0,0 +1,62 @@ +import {LitElement, css, html} from "lit"; +import {property} from "lit/decorators.js"; +import {defineElement} from "../define"; +import {UI} from "../messages"; +import {SUPPORTED_EMOJI, normalizeEmoji} from "../model/emoji"; + +/** Grid of the emoji the screen can render. */ +export class HcEmojiPicker extends LitElement { + @property() value = ""; + + static styles = css` + :host { + display: block; + } + .grid { + display: grid; + grid-template-columns: repeat(8, 1fr); + gap: 4px; + } + button { + font-size: 20px; + padding: 4px; + cursor: pointer; + background: var(--card-background-color, #fff); + border: 1px solid var(--divider-color, rgba(0, 0, 0, 0.12)); + border-radius: 6px; + } + button[aria-pressed="true"] { + border-color: var(--primary-color, #03a9f4); + box-shadow: 0 0 0 2px var(--primary-color, #03a9f4); + } + `; + + render() { + const current = normalizeEmoji(this.value ?? ""); + return html`
+ ${SUPPORTED_EMOJI.map( + (e) => html``, + )} +
`; + } + + private emit(value: string): void { + this.dispatchEvent( + new CustomEvent("hc-value-change", {detail: {value: normalizeEmoji(value)}, bubbles: true, composed: true}), + ); + } +} + +defineElement("hc-emoji-picker", HcEmojiPicker); + +declare global { + interface HTMLElementTagNameMap { + "hc-emoji-picker": HcEmojiPicker; + } +} diff --git a/custom_components/ha_controller/frontend/src/components/hc-entity-input.ts b/custom_components/ha_controller/frontend/src/components/hc-entity-input.ts new file mode 100644 index 0000000..6a53f77 --- /dev/null +++ b/custom_components/ha_controller/frontend/src/components/hc-entity-input.ts @@ -0,0 +1,64 @@ +import {LitElement, css, html} from "lit"; +import {property} from "lit/decorators.js"; +import {defineElement} from "../define"; +import {UI} from "../messages"; +import type {Hass} from "../types"; + +let counter = 0; + +/** Entity picker built from `hass.states`: a text input with a datalist of matching ids. */ +export class HcEntityInput extends LitElement { + @property({attribute: false}) hass?: Hass; + @property() value = ""; + @property({attribute: false}) domains?: string[]; + + private readonly listId = `entities-${counter++}`; + + static styles = css` + :host { + display: block; + } + input { + box-sizing: border-box; + width: 100%; + font: inherit; + padding: 6px 8px; + color: var(--primary-text-color, #212121); + background: var(--card-background-color, #fff); + border: 1px solid var(--divider-color, rgba(0, 0, 0, 0.12)); + border-radius: 6px; + } + `; + + render() { + const ids = Object.keys(this.hass?.states ?? {}) + .filter((id) => !this.domains || this.domains.includes(id.split(".")[0])) + .sort(); + return html` this.emit((e.target as HTMLInputElement).value.trim())} + /> + + ${ids.map((id) => { + const name = this.hass?.states[id]?.attributes.friendly_name; + return html``; + })} + `; + } + + private emit(value: string): void { + this.dispatchEvent(new CustomEvent("hc-value-change", {detail: {value}, bubbles: true, composed: true})); + } +} + +defineElement("hc-entity-input", HcEntityInput); + +declare global { + interface HTMLElementTagNameMap { + "hc-entity-input": HcEntityInput; + } +} diff --git a/custom_components/ha_controller/frontend/src/components/hc-grid.ts b/custom_components/ha_controller/frontend/src/components/hc-grid.ts new file mode 100644 index 0000000..ec2fb99 --- /dev/null +++ b/custom_components/ha_controller/frontend/src/components/hc-grid.ts @@ -0,0 +1,136 @@ +import {LitElement, css, html, nothing} from "lit"; +import {property} from "lit/decorators.js"; +import {defineElement} from "../define"; +import {gridBounds, placeholders} from "../model/grid"; +import {UI} from "../messages"; +import {textColorFor} from "../model/color"; +import type {Layout} from "../types"; + +/** Block map: x grows to the right, y grows downwards, like navigation on the screen. */ +export class HcGrid extends LitElement { + @property({attribute: false}) layout: Layout = {version: 1, start: null, settings: {sleep_timeout: 0}, blocks: []}; + @property({attribute: false}) selectedId: string | null = null; + @property({attribute: false}) errorRefs: ReadonlySet = new Set(); + + static styles = css` + :host { + display: block; + overflow: auto; + } + .grid { + display: grid; + grid-auto-columns: 96px; + grid-auto-rows: 96px; + gap: 12px; + padding: 12px; + width: max-content; + } + button { + all: unset; + box-sizing: border-box; + cursor: pointer; + border-radius: 16px; + display: flex; + align-items: center; + justify-content: center; + text-align: center; + position: relative; + font: inherit; + font-weight: 500; + padding: 8px; + overflow: hidden; + overflow-wrap: anywhere; + } + /* Cues are layered box-shadows (start inset, selection, error), so they combine. Focus uses + outline, which no state touches, and sits outside the rings. */ + .block { + --ring-start: 0 0 0 0 transparent; + --ring-select: 0 0 0 0 transparent; + --ring-error: 0 0 0 0 transparent; + box-shadow: var(--ring-select), var(--ring-error), var(--ring-start); + } + .block.start { + --ring-start: inset 0 0 0 3px var(--primary-text-color, #212121); + } + .block.has-error { + --ring-error: 0 0 0 3px var(--error-color, #db4437); + } + .block.selected { + --ring-select: 0 0 0 3px var(--primary-color, #03a9f4); + } + .block.selected.has-error { + --ring-select: 0 0 0 3px var(--primary-color, #03a9f4); + --ring-error: 0 0 0 6px var(--error-color, #db4437); + } + button:focus-visible { + outline: 2px solid var(--primary-text-color, #212121); + outline-offset: 3px; + } + .block.selected:focus-visible, + .block.has-error:focus-visible { + outline-offset: 8px; + } + .start-badge { + position: absolute; + top: 6px; + left: 8px; + font-size: 10px; + text-transform: uppercase; + letter-spacing: 0.05em; + opacity: 0.8; + } + .placeholder { + border: 2px dashed var(--divider-color, rgba(0, 0, 0, 0.12)); + color: var(--secondary-text-color, #727272); + font-size: 28px; + font-weight: 300; + } + .placeholder:hover { + border-color: var(--primary-color, #03a9f4); + color: var(--primary-color, #03a9f4); + } + `; + + render() { + const {blocks, start} = this.layout; + const empty = placeholders(this.layout); + const cells = [...blocks, ...empty]; + if (cells.length === 0) return nothing; + const {minX, minY} = gridBounds(cells); + const place = (x: number, y: number) => `grid-column: ${x - minX + 1}; grid-row: ${y - minY + 1}`; + return html`
+ ${blocks.map( + (b) => html``, + )} + ${empty.map( + (c) => html``, + )} +
`; + } + + private emit(name: string, detail: unknown): void { + this.dispatchEvent(new CustomEvent(name, {detail, bubbles: true, composed: true})); + } +} + +defineElement("hc-grid", HcGrid); + +declare global { + interface HTMLElementTagNameMap { + "hc-grid": HcGrid; + } +} diff --git a/custom_components/ha_controller/frontend/src/components/hc-item-editor.ts b/custom_components/ha_controller/frontend/src/components/hc-item-editor.ts new file mode 100644 index 0000000..a78dfaa --- /dev/null +++ b/custom_components/ha_controller/frontend/src/components/hc-item-editor.ts @@ -0,0 +1,147 @@ +import {LitElement, css, html, nothing} from "lit"; +import {property} from "lit/decorators.js"; +import {defineElement} from "../define"; +import "./hc-entity-input"; +import "./hc-emoji-picker"; +import {FONT_SIZE_LABEL, FONT_SIZE_ORDER, ITEM_KIND_LABEL, UI} from "../messages"; +import type {FontSize, Hass, Item} from "../types"; + +/** Editor for one item of a custom block. */ +export class HcItemEditor extends LitElement { + @property({attribute: false}) hass?: Hass; + @property({attribute: false}) item!: Item; + @property({type: Number}) index = 0; + @property({type: Number}) count = 0; + + static styles = css` + :host { + display: block; + } + .item { + border: 1px solid var(--divider-color, rgba(0, 0, 0, 0.12)); + border-radius: 8px; + padding: 8px; + display: grid; + gap: 8px; + background: var(--card-background-color, #fff); + color: var(--primary-text-color, #212121); + } + .head, + .actions { + display: flex; + gap: 6px; + align-items: center; + } + .head strong { + flex: 1; + } + input[type="text"] { + box-sizing: border-box; + width: 100%; + font: inherit; + padding: 6px 8px; + color: var(--primary-text-color, #212121); + background: var(--card-background-color, #fff); + border: 1px solid var(--divider-color, rgba(0, 0, 0, 0.12)); + border-radius: 6px; + } + label { + font-size: 12px; + color: var(--secondary-text-color, #727272); + } + button.remove { + color: var(--error-color, #db4437); + } + `; + + render() { + const item = this.item; + return html`
+
+ ${ITEM_KIND_LABEL[item.kind]} + + + +
+ ${this.fields(item)} +
+ + +
+
`; + } + + protected updated(): void { + const select = this.renderRoot.querySelector("select[name=font-size]"); + if (select) select.value = this.item.font_size ?? ""; + } + + private fields(item: Item) { + switch (item.kind) { + case "text": + return html` this.patch({text: (e.target as HTMLInputElement).value})} + />`; + case "emoji": + return html`) => { + e.stopPropagation(); + this.patch({emoji: e.detail.value}); + }} + >`; + case "entity": + return html`) => { + e.stopPropagation(); + this.patch({entity_id: e.detail.value}); + }} + > + this.patch({attribute: (e.target as HTMLInputElement).value || null})} + />`; + default: + return nothing; + } + } + + private onFontSize = (e: Event): void => { + const value = (e.target as HTMLSelectElement).value; + this.patch({font_size: value === "" ? null : (value as FontSize)}); + }; + + private patch(patch: Partial): void { + this.emit("hc-item-change", {patch}); + } + + private move(delta: -1 | 1): void { + this.emit("hc-item-move", {delta}); + } + + private emit(name: string, detail?: unknown): void { + this.dispatchEvent(new CustomEvent(name, {detail, bubbles: true, composed: true})); + } +} + +defineElement("hc-item-editor", HcItemEditor); + +declare global { + interface HTMLElementTagNameMap { + "hc-item-editor": HcItemEditor; + } +} diff --git a/custom_components/ha_controller/frontend/src/components/hc-preview.ts b/custom_components/ha_controller/frontend/src/components/hc-preview.ts new file mode 100644 index 0000000..9e9405f --- /dev/null +++ b/custom_components/ha_controller/frontend/src/components/hc-preview.ts @@ -0,0 +1,81 @@ +import {LitElement, css, html} from "lit"; +import {property} from "lit/decorators.js"; +import {defineElement} from "../define"; +import {textColorFor} from "../model/color"; +import {UI} from "../messages"; +import type {Block, Hass, Item} from "../types"; + +const SIZES: Record = {s: "11px", m: "14px", l: "18px", xl: "24px"}; + +/** Round preview of a block, approximating the screen. */ +export class HcPreview extends LitElement { + @property({attribute: false}) block?: Block; + @property({attribute: false}) hass?: Hass; + + static styles = css` + :host { + display: block; + } + .circle { + box-sizing: border-box; + width: 220px; + height: 220px; + border-radius: 50%; + margin: 0 auto; + padding: 32px; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + text-align: center; + overflow: hidden; + overflow-wrap: anywhere; + border: 1px solid var(--divider-color, rgba(0, 0, 0, 0.12)); + } + .name { + font-weight: 600; + } + `; + + private stateOf(entityId: string | undefined, attribute?: string | null): string { + const entity = entityId ? this.hass?.states[entityId] : undefined; + if (!entity) return UI.unavailable; + if (attribute) return String(entity.attributes[attribute] ?? ""); + const unit = entity.attributes.unit_of_measurement; + return typeof unit === "string" ? `${entity.state} ${unit}` : entity.state; + } + + private line(block: Block, item: Item) { + let text = ""; + switch (item.kind) { + case "text": text = item.text ?? ""; break; + case "emoji": text = item.emoji ?? ""; break; + case "entity": text = this.stateOf(item.entity_id, item.attribute); break; + case "battery": text = UI.previewBattery; break; + case "brightness": text = UI.previewBrightness; break; + } + return html`
${text}
`; + } + + render() { + const block = this.block; + if (!block) return html``; + return html`
+
${block.name}
+ ${block.type === "entity" + ? html`
${this.stateOf(block.entity_id)}
` + : (block.items ?? []).map((item) => this.line(block, item))} +
`; + } +} + +defineElement("hc-preview", HcPreview); + +declare global { + interface HTMLElementTagNameMap { + "hc-preview": HcPreview; + } +} diff --git a/custom_components/ha_controller/frontend/src/define.ts b/custom_components/ha_controller/frontend/src/define.ts new file mode 100644 index 0000000..a754845 --- /dev/null +++ b/custom_components/ha_controller/frontend/src/define.ts @@ -0,0 +1,4 @@ +/** Register a custom element once; safe when a module is evaluated twice (HMR, duplicate bundle). */ +export function defineElement(name: string, ctor: CustomElementConstructor): void { + if (customElements.get(name) === undefined) customElements.define(name, ctor); +} diff --git a/custom_components/ha_controller/frontend/src/ha-controller-panel.ts b/custom_components/ha_controller/frontend/src/ha-controller-panel.ts new file mode 100644 index 0000000..56acd08 --- /dev/null +++ b/custom_components/ha_controller/frontend/src/ha-controller-panel.ts @@ -0,0 +1,391 @@ +import {LitElement, css, html, nothing} from "lit"; +import {property, state} from "lit/decorators.js"; +import {defineElement} from "./define"; +import {getLayout, listScreens, saveLayout} from "./api"; +import "./components/hc-grid"; +import "./components/hc-block-editor"; +import {UI, errorMessage} from "./messages"; +import {addBlock, setSleepTimeout} from "./model/edit"; +import {EMOJI_SET} from "./model/emoji"; +import {validateLayout} from "./model/validate"; +import type {Hass, Layout, LayoutError, ScreenInfo} from "./types"; + +const REFRESH_MS = 10_000; + +interface Notice { + kind: "ok" | "error"; + text: string; +} + +/** Root of the sidebar panel: screen picker, status, block map, editor and save. */ +export class HaControllerPanel extends LitElement { + @property({attribute: false}) hass?: Hass; + @property({type: Boolean}) narrow = false; + @property({attribute: false}) panel?: unknown; + @property({attribute: false}) route?: unknown; + + @state() private screens: ScreenInfo[] = []; + @state() private entryId: string | null = null; + @state() private saved: Layout | null = null; + @state() private layout: Layout | null = null; + @state() private selectedId: string | null = null; + @state() private notice: Notice | null = null; + @state() private saving = false; + + private started = false; + private timer?: ReturnType; + private loadToken = 0; + + static styles = css` + :host { + display: block; + min-height: 100%; + box-sizing: border-box; + color: var(--primary-text-color, #212121); + background: var(--primary-background-color, #fafafa); + font-family: var(--paper-font-body1_-_font-family, Roboto, system-ui, sans-serif); + } + header { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px 16px; + padding: 12px 16px; + background: var(--app-header-background-color, var(--card-background-color, #fff)); + color: var(--app-header-text-color, var(--primary-text-color, #212121)); + border-bottom: 1px solid var(--divider-color, rgba(0, 0, 0, 0.12)); + } + h1 { + margin: 0; + font-size: 20px; + font-weight: 500; + } + .status { + font-size: 13px; + color: var(--secondary-text-color, #727272); + } + .actions { + display: flex; + gap: 8px; + margin-left: auto; + } + select, + input[type="number"] { + font: inherit; + padding: 6px 8px; + color: var(--primary-text-color, #212121); + background: var(--card-background-color, #fff); + border: 1px solid var(--divider-color, rgba(0, 0, 0, 0.12)); + border-radius: 6px; + } + button.action { + font: inherit; + padding: 6px 16px; + border-radius: 6px; + cursor: pointer; + color: var(--primary-color, #03a9f4); + background: transparent; + border: 1px solid var(--primary-color, #03a9f4); + } + button.action.save { + color: var(--text-primary-color, #fff); + background: var(--primary-color, #03a9f4); + } + button.action:disabled { + opacity: 0.4; + cursor: default; + } + button.action:focus-visible { + outline: 2px solid var(--primary-text-color, #212121); + outline-offset: 2px; + } + main { + display: grid; + grid-template-columns: minmax(0, 1fr) 340px; + gap: 24px; + padding: 16px; + align-items: start; + } + main.narrow { + grid-template-columns: minmax(0, 1fr); + } + section { + margin-top: 16px; + } + h2 { + margin: 0 0 8px; + font-size: 14px; + font-weight: 500; + } + .help { + margin-top: 4px; + font-size: 12px; + color: var(--secondary-text-color, #727272); + } + .errors { + margin: 12px 0 0; + padding-left: 20px; + color: var(--error-color, #db4437); + } + .notice { + margin: 12px 16px 0; + padding: 8px 12px; + border-radius: 6px; + border: 1px solid var(--divider-color, rgba(0, 0, 0, 0.12)); + background: var(--card-background-color, #fff); + } + .notice.error { + color: var(--error-color, #db4437); + border-color: var(--error-color, #db4437); + } + .empty { + padding: 24px 16px; + color: var(--secondary-text-color, #727272); + } + `; + + connectedCallback(): void { + super.connectedCallback(); + this.timer = setInterval(() => void this.refreshScreens(), REFRESH_MS); + } + + disconnectedCallback(): void { + clearInterval(this.timer); + this.timer = undefined; + super.disconnectedCallback(); + } + + protected updated(changed: Map): void { + if (changed.has("hass") && this.hass && !this.started) { + this.started = true; + void this.init(); + } + } + + private async init(): Promise { + const hass = this.hass as Hass; + try { + this.screens = await listScreens(hass); + } catch (err) { + this.notice = {kind: "error", text: this.describe(err, UI.loadFailed)}; + return; + } + if (this.screens.length > 0) await this.selectScreen(this.screens[0].entry_id); + } + + /** Refresh the screen list only; the working layout is never touched. */ + private async refreshScreens(): Promise { + if (!this.hass) return; + try { + this.screens = await listScreens(this.hass); + } catch { + // A failed refresh keeps the previous status; the next tick tries again. + return; + } + // A failed or empty first load leaves no screen selected: pick one now. + if (this.entryId === null && this.screens.length > 0) await this.selectScreen(this.screens[0].entry_id); + } + + /** Load a screen; resolves true when it is now the loaded one. */ + private async selectScreen(entryId: string): Promise { + const token = ++this.loadToken; + try { + const layout = await getLayout(this.hass as Hass, entryId); + if (token !== this.loadToken) return false; + this.entryId = entryId; + this.saved = layout; + this.layout = layout; + this.selectedId = layout.start ?? layout.blocks[0]?.id ?? null; + this.notice = null; + return true; + } catch (err) { + if (token !== this.loadToken) return false; + this.notice = {kind: "error", text: this.describe(err, UI.loadFailed)}; + return false; + } + } + + private onScreenChange = async (e: Event): Promise => { + const select = e.target as HTMLSelectElement; + if (!(await this.selectScreen(select.value))) select.value = this.entryId ?? ""; + }; + + private describe(err: unknown, fallback: string): string { + const message = (err as {message?: unknown} | null)?.message; + return typeof message === "string" && message !== "" ? message : fallback; + } + + private get errors(): LayoutError[] { + return this.layout ? validateLayout(this.layout, EMOJI_SET) : []; + } + + private get dirty(): boolean { + return JSON.stringify(this.layout) !== JSON.stringify(this.saved); + } + + private errorText(error: LayoutError): string { + const message = errorMessage(error.code); + const block = this.layout?.blocks.find((b) => b.id === error.ref); + return block ? UI.withBlock(message, block.name) : message; + } + + private setLayout(layout: Layout): void { + this.layout = layout; + this.notice = null; + if (!layout.blocks.some((b) => b.id === this.selectedId)) { + this.selectedId = layout.start ?? layout.blocks[0]?.id ?? null; + } + } + + private onAddBlock = (e: CustomEvent<{x: number; y: number}>): void => { + if (!this.layout) return; + const {layout, id} = addBlock(this.layout, e.detail); + this.setLayout(layout); + this.selectedId = id; + }; + + private onSleep = (e: Event): void => { + const input = e.target as HTMLInputElement; + if (!this.layout || input.value === "") return; + this.setLayout(setSleepTimeout(this.layout, Number(input.value))); + }; + + private onRevert = (): void => { + if (!this.saved) return; + this.setLayout(this.saved); + }; + + private onSave = async (): Promise => { + if (!this.hass || !this.entryId || !this.layout || this.saving) return; + const layout = this.layout; + const entryId = this.entryId; + this.saving = true; + try { + const result = await saveLayout(this.hass, entryId, layout); + if (entryId !== this.entryId) return; + this.saved = layout; + this.notice = {kind: "ok", text: result.pushed ? UI.savedPushed : UI.savedOffline}; + void this.refreshScreens(); + } catch (err) { + if (entryId === this.entryId) this.notice = {kind: "error", text: this.saveError(err, layout)}; + } finally { + this.saving = false; + } + }; + + private saveError(err: unknown, layout: Layout): string { + const {code, message} = (err ?? {}) as {code?: string; message?: string}; + if (code === "invalid_layout" && typeof message === "string") { + return message + .split(",") + .map((part) => part.trim()) + .filter((part) => part !== "") + .map((part) => { + const [errorCode, ref = ""] = part.split("@"); + const block = layout.blocks.find((b) => b.id === ref); + return block ? UI.withBlock(errorMessage(errorCode), block.name) : errorMessage(errorCode); + }) + .join(" "); + } + return this.describe(err, UI.saveFailed); + } + + private get screen(): ScreenInfo | undefined { + return this.screens.find((s) => s.entry_id === this.entryId); + } + + private statusText(): string { + const s = this.screen; + if (!s) return ""; + if (!s.online) return UI.statusOffline; + const version = s.firmware_version ?? UI.unknownVersion; + if (s.firmware_version !== s.integration_version) return UI.statusUpdateAvailable(version); + return s.revision === s.device_revision ? UI.statusInSync(version) : UI.statusSyncing(version); + } + + protected render() { + const errors = this.errors; + const locked = this.dirty || this.saving; + const canSave = this.dirty && errors.length === 0 && !this.saving; + return html` +
+ ${this.narrow ? html`` : nothing} +

${UI.title}

+ ${this.screens.length > 1 + ? html`` + : nothing} + ${this.statusText()} +
+ + +
+
+ ${this.notice + ? html`
${this.notice.text}
` + : nothing} + ${this.layout ? this.renderBody(this.layout, errors) : this.renderEmpty()} + `; + } + + private renderEmpty() { + return this.started && this.screens.length === 0 && !this.notice ? html`
${UI.noScreens}
` : nothing; + } + + private renderBody(layout: Layout, errors: LayoutError[]) { + const refs = new Set(errors.map((e) => e.ref).filter((r): r is string => r !== null)); + return html`
+
+ ) => (this.selectedId = e.detail.id)} + @hc-add-block=${this.onAddBlock} + > + ${errors.length > 0 + ? html`
    ${errors.map((e) => html`
  • ${this.errorText(e)}
  • `)}
` + : nothing} +
+

${UI.screenSection}

+ + +
${UI.sleepHelp}
+
+
+ ) => this.setLayout(e.detail.layout)} + > +
`; + } +} + +defineElement("ha-controller-panel", HaControllerPanel); + +declare global { + interface HTMLElementTagNameMap { + "ha-controller-panel": HaControllerPanel; + } +} diff --git a/custom_components/ha_controller/frontend/src/messages.ts b/custom_components/ha_controller/frontend/src/messages.ts new file mode 100644 index 0000000..20af4fe --- /dev/null +++ b/custom_components/ha_controller/frontend/src/messages.ts @@ -0,0 +1,94 @@ +import type {FontSize, ItemKind} from "./types"; + +/** English UI strings for validation error codes and delete refusals. */ +const ERRORS: Record = { + invalid_structure: "The layout is malformed.", + too_many_blocks: "A screen holds at most 32 blocks.", + invalid_id: "Invalid identifier.", + duplicate_id: "Duplicate identifier.", + coordinate_out_of_range: "This block is too far from the centre of the map.", + duplicate_position: "Two blocks share the same cell.", + invalid_start: "Choose a start block.", + disconnected: "This block can't be reached from the start block.", + invalid_name: "Names need 1 to 32 characters.", + invalid_background: "Pick a background colour.", + invalid_font_size: "Pick a font size.", + invalid_type: "Pick a block type.", + invalid_entity: "Pick a valid entity.", + too_many_items: "A custom block holds at most 6 items.", + invalid_item: "Unknown item type.", + invalid_text: "Text needs 1 to 64 characters.", + unsupported_emoji: "This emoji is not available on the screen.", + payload_too_large: "The layout is too large for the screen. Remove blocks or shorten texts.", + invalid_sleep_timeout: "The sleep delay must be 0 (never) or between 5 and 3600 seconds.", +}; + +export function errorMessage(code: string): string { + return ERRORS[code] ?? "Invalid layout."; +} + +export const deleteReason: Record<"start" | "disconnects", string> = { + start: "Choose another start block first.", + disconnects: "Other blocks would become unreachable.", +}; + +/** Item kind labels, in the order offered by the "add item" menu. */ +export const ITEM_KIND_LABEL: Record = { + text: "Text", + emoji: "Emoji", + entity: "Entity state", + battery: "Battery", + brightness: "Screen brightness", +}; + +export const FONT_SIZE_LABEL: Record = {s: "S", m: "M", l: "L", xl: "XL"}; + +export const FONT_SIZE_ORDER: FontSize[] = ["s", "m", "l", "xl"]; + +export const UI = { + name: "Name", + background: "Background", + backgroundColour: (colour: string) => `Background ${colour}`, + customBackground: "Custom background colour", + fontSize: "Font size", + fontSizeInherit: "Inherit", + type: "Type", + typeEntity: "Entity", + typeCustom: "Custom", + entity: "Entity", + entityPlaceholder: "domain.entity", + setStart: "Set as start block", + deleteBlock: "Delete block", + addItemLabel: "Add item", + addItemPlaceholder: "Add item…", + moveUp: "Move up", + moveDown: "Move down", + removeItem: "Remove item", + text: "Text", + attributeOptional: "Attribute (optional)", + emoji: "Emoji", + unavailable: "unavailable", + previewBattery: "Battery", + previewBrightness: "Brightness", + addBlock: "Add block", + title: "HA Controller", + screenSelect: "Screen", + revert: "Revert", + save: "Save", + switchBlocked: "Save or revert your changes first.", + noScreens: "No screens yet. Add the HA Controller integration and connect a screen.", + loadFailed: "Could not load the screens.", + saveFailed: "Could not save the layout.", + mapLabel: "Block map", + screenSection: "Screen", + sleepAfter: "Sleep after (seconds)", + sleepHelp: "0 keeps the screen on.", + statusOffline: "Offline", + statusUpdateAvailable: (version: string) => `Online · firmware ${version} — update available`, + statusInSync: (version: string) => `Online · firmware ${version} · in sync`, + statusSyncing: (version: string) => `Online · firmware ${version} · syncing…`, + unknownVersion: "unknown", + savedPushed: "Saved — sent to the screen.", + savedOffline: "Saved — the screen is offline and will update when it reconnects.", + withBlock: (message: string, blockName: string) => `${message} (${blockName})`, +}; diff --git a/custom_components/ha_controller/frontend/src/model/color.ts b/custom_components/ha_controller/frontend/src/model/color.ts new file mode 100644 index 0000000..3d234eb --- /dev/null +++ b/custom_components/ha_controller/frontend/src/model/color.ts @@ -0,0 +1,15 @@ +const channel = (value: number): number => { + const c = value / 255; + return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; +}; + +/** WCAG relative luminance of a #RRGGBB colour. */ +function luminance(hex: string): number { + const n = parseInt(hex.slice(1), 16); + return 0.2126 * channel((n >> 16) & 255) + 0.7152 * channel((n >> 8) & 255) + 0.0722 * channel(n & 255); +} + +/** Black text on light backgrounds, white on dark ones (spec section 5.5). */ +export function textColorFor(bg: string): "#000000" | "#FFFFFF" { + return luminance(bg) > 0.3 ? "#000000" : "#FFFFFF"; +} diff --git a/custom_components/ha_controller/frontend/src/model/edit.ts b/custom_components/ha_controller/frontend/src/model/edit.ts new file mode 100644 index 0000000..ba0b659 --- /dev/null +++ b/custom_components/ha_controller/frontend/src/model/edit.ts @@ -0,0 +1,95 @@ +import type {Block, Cell, Item, ItemKind, Layout} from "../types"; +import {canDelete} from "./grid"; +import {MAX_BLOCKS} from "./limits"; + +export const PALETTE: readonly string[] = [ + "#C94F3D", "#4F86DD", "#5B9E4D", "#7B2FA0", "#E08A2E", "#2E9E8F", "#D2477A", "#5C6BC0", +]; + +const suffix = (id: string, prefix: string): number => + id.startsWith(prefix) && /^\d+$/.test(id.slice(prefix.length)) ? Number(id.slice(prefix.length)) : 0; + +/** One plus the highest numeric suffix among block and item ids with this prefix. */ +export function nextId(layout: Layout, prefix: "b" | "i"): string { + let max = 0; + for (const block of layout.blocks) { + max = Math.max(max, suffix(block.id, prefix)); + for (const item of block.items ?? []) max = Math.max(max, suffix(item.id, prefix)); + } + return `${prefix}${max + 1}`; +} + +export function addBlock(layout: Layout, cell: Cell): {layout: Layout; id: string} { + if (layout.blocks.length >= MAX_BLOCKS) throw new Error("too_many_blocks"); + const id = nextId(layout, "b"); + const block: Block = { + id, + x: cell.x, + y: cell.y, + name: `Block ${suffix(id, "b")}`, + background: PALETTE[layout.blocks.length % PALETTE.length], + font_size: "m", + type: "custom", + items: [], + }; + return {layout: {...layout, start: layout.start ?? id, blocks: [...layout.blocks, block]}, id}; +} + +export function deleteBlock(layout: Layout, id: string): Layout { + const check = canDelete(layout, id); + if (!check.ok) throw new Error(check.reason); + const blocks = layout.blocks.filter((b) => b.id !== id); + return {...layout, start: blocks.length === 0 ? null : layout.start, blocks}; +} + +export function setStart(layout: Layout, id: string): Layout { + return {...layout, start: id}; +} + +export function updateBlock(layout: Layout, id: string, patch: Partial): Layout { + return {...layout, blocks: layout.blocks.map((b) => (b.id === id ? {...b, ...patch} : b))}; +} + +export function setSleepTimeout(layout: Layout, seconds: number): Layout { + return {...layout, settings: {...layout.settings, sleep_timeout: seconds}}; +} + +function withItems(layout: Layout, blockId: string, change: (items: Item[]) => Item[]): Layout { + return { + ...layout, + blocks: layout.blocks.map((b) => (b.id === blockId ? {...b, items: change(b.items ?? [])} : b)), + }; +} + +const DEFAULT_ITEMS: Record> = { + text: {text: "Text"}, + emoji: {emoji: "💡"}, + entity: {entity_id: "", attribute: null}, + battery: {}, + brightness: {}, +}; + +export function addItem(layout: Layout, blockId: string, kind: ItemKind): {layout: Layout; id: string} { + const id = nextId(layout, "i"); + const item: Item = {id, kind, ...DEFAULT_ITEMS[kind], font_size: null}; + return {layout: withItems(layout, blockId, (items) => [...items, item]), id}; +} + +export function updateItem(layout: Layout, blockId: string, itemId: string, patch: Partial): Layout { + return withItems(layout, blockId, (items) => items.map((i) => (i.id === itemId ? {...i, ...patch} : i))); +} + +export function removeItem(layout: Layout, blockId: string, itemId: string): Layout { + return withItems(layout, blockId, (items) => items.filter((i) => i.id !== itemId)); +} + +export function moveItem(layout: Layout, blockId: string, itemId: string, delta: -1 | 1): Layout { + return withItems(layout, blockId, (items) => { + const from = items.findIndex((i) => i.id === itemId); + const to = from + delta; + if (from < 0 || to < 0 || to >= items.length) return items; + const next = [...items]; + [next[from], next[to]] = [next[to], next[from]]; + return next; + }); +} diff --git a/custom_components/ha_controller/frontend/src/model/emoji.ts b/custom_components/ha_controller/frontend/src/model/emoji.ts new file mode 100644 index 0000000..6bce298 --- /dev/null +++ b/custom_components/ha_controller/frontend/src/model/emoji.ts @@ -0,0 +1,9 @@ +import emoji from "../../../emoji.json"; + +export const SUPPORTED_EMOJI: readonly string[] = emoji; +export const EMOJI_SET: ReadonlySet = new Set(SUPPORTED_EMOJI); + +/** Remove the emoji variation selector U+FE0F. */ +export function normalizeEmoji(text: string): string { + return text.replaceAll("\uFE0F", ""); +} diff --git a/custom_components/ha_controller/frontend/src/model/grid.ts b/custom_components/ha_controller/frontend/src/model/grid.ts new file mode 100644 index 0000000..0baf3e7 --- /dev/null +++ b/custom_components/ha_controller/frontend/src/model/grid.ts @@ -0,0 +1,66 @@ +import type {Block, Cell, Layout} from "../types"; +import {COORD_LIMIT, MAX_BLOCKS} from "./limits"; + +const DIRECTIONS: readonly Cell[] = [ + {x: 1, y: 0}, + {x: -1, y: 0}, + {x: 0, y: 1}, + {x: 0, y: -1}, +]; + +const key = (x: number, y: number): string => `${x},${y}`; + +/** Empty cells next to a block, within the coordinate limit, sorted by y then x. */ +export function placeholders(layout: Layout): Cell[] { + const {blocks} = layout; + if (blocks.length === 0) return [{x: 0, y: 0}]; + if (blocks.length >= MAX_BLOCKS) return []; + const taken = new Set(blocks.map((b) => key(b.x, b.y))); + const found = new Map(); + for (const block of blocks) { + for (const d of DIRECTIONS) { + const x = block.x + d.x; + const y = block.y + d.y; + if (Math.abs(x) > COORD_LIMIT || Math.abs(y) > COORD_LIMIT) continue; + const k = key(x, y); + if (!taken.has(k)) found.set(k, {x, y}); + } + } + return [...found.values()].sort((a, b) => a.y - b.y || a.x - b.x); +} + +/** Ids of the blocks reachable from the start block through adjacent blocks. */ +export function reachable(blocks: Block[], start: string | null): Set { + const first = blocks.find((b) => b.id === start); + if (!first) return new Set(); + const byCell = new Map(blocks.map((b) => [key(b.x, b.y), b])); + const seen = new Set([first.id]); + const queue = [first]; + while (queue.length > 0) { + const current = queue.shift() as Block; + for (const d of DIRECTIONS) { + const next = byCell.get(key(current.x + d.x, current.y + d.y)); + if (next && !seen.has(next.id)) { + seen.add(next.id); + queue.push(next); + } + } + } + return seen; +} + +export type DeleteCheck = {ok: true} | {ok: false; reason: "start" | "disconnects"}; + +export function canDelete(layout: Layout, id: string): DeleteCheck { + if (layout.blocks.length > 1 && layout.start === id) return {ok: false, reason: "start"}; + const rest = layout.blocks.filter((b) => b.id !== id); + if (rest.length === 0) return {ok: true}; + const seen = reachable(rest, layout.start); + return rest.every((b) => seen.has(b.id)) ? {ok: true} : {ok: false, reason: "disconnects"}; +} + +export function gridBounds(cells: Cell[]): {minX: number; maxX: number; minY: number; maxY: number} { + const xs = cells.map((c) => c.x); + const ys = cells.map((c) => c.y); + return {minX: Math.min(...xs), maxX: Math.max(...xs), minY: Math.min(...ys), maxY: Math.max(...ys)}; +} diff --git a/custom_components/ha_controller/frontend/src/model/limits.ts b/custom_components/ha_controller/frontend/src/model/limits.ts new file mode 100644 index 0000000..67074a5 --- /dev/null +++ b/custom_components/ha_controller/frontend/src/model/limits.ts @@ -0,0 +1,4 @@ +/** Layout limits shared with the Python validator (spec section 6). */ +export const MAX_BLOCKS = 32; +export const MAX_ITEMS = 6; +export const COORD_LIMIT = 32; diff --git a/custom_components/ha_controller/frontend/src/model/validate.ts b/custom_components/ha_controller/frontend/src/model/validate.ts new file mode 100644 index 0000000..e1113c6 --- /dev/null +++ b/custom_components/ha_controller/frontend/src/model/validate.ts @@ -0,0 +1,153 @@ +import type {Block, LayoutError} from "../types"; +import {normalizeEmoji} from "./emoji"; +import {reachable} from "./grid"; +import {COORD_LIMIT, MAX_BLOCKS, MAX_ITEMS} from "./limits"; + +const MAX_NAME_LEN = 32; +const MAX_TEXT_LEN = 64; +const MAX_ATTRIBUTE_LEN = 64; +const MIN_SLEEP_TIMEOUT = 5; +const MAX_SLEEP_TIMEOUT = 3600; +const FONT_SIZES = ["s", "m", "l", "xl"]; +const ITEM_KINDS = ["text", "emoji", "entity", "battery", "brightness"]; +const ENTITY_BLOCK_DOMAINS = ["light", "climate"]; + +const ID_RE = /^[a-z][a-z0-9]{0,7}$/; +const COLOR_RE = /^#[0-9A-Fa-f]{6}$/; +const ENTITY_RE = /^[a-z0-9_]+\.[a-z0-9_]+$/; + +type Obj = Record; + +const isObj = (v: unknown): v is Obj => typeof v === "object" && v !== null && !Array.isArray(v); +const isInt = (v: unknown): v is number => typeof v === "number" && Number.isInteger(v); +const isId = (v: unknown): v is string => typeof v === "string" && ID_RE.test(v); +const isEntityId = (v: unknown): v is string => typeof v === "string" && ENTITY_RE.test(v); +const cpLen = (s: string): number => Array.from(s).length; +const refOf = (v: unknown): string | null => (typeof v === "string" ? v : null); + +function checkStructure(layout: unknown): layout is Obj & {settings: Obj; blocks: Obj[]} { + if (!isObj(layout) || layout.version !== 1 || !isObj(layout.settings)) return false; + const blocks = layout.blocks; + if (!Array.isArray(blocks) || !blocks.every(isObj)) return false; + for (const block of blocks as Obj[]) { + if (block.type === "custom") { + const items = block.items; + if (!Array.isArray(items) || !items.every(isObj)) return false; + } + } + return true; +} + +function validEntityItem(item: Obj): boolean { + if (!isEntityId(item.entity_id)) return false; + const attr = item.attribute; + return attr === undefined || attr === null || + (typeof attr === "string" && cpLen(attr) >= 1 && cpLen(attr) <= MAX_ATTRIBUTE_LEN); +} + +function validEntityBlock(block: Obj): boolean { + const id = block.entity_id; + return isEntityId(id) && ENTITY_BLOCK_DOMAINS.includes(id.split(".", 1)[0]); +} + +function checkItem(item: Obj, seen: Set, emoji: ReadonlySet, errors: LayoutError[]): void { + const ref = refOf(item.id); + if (!isId(item.id)) errors.push({code: "invalid_id", ref}); + if (typeof item.id === "string") { + if (seen.has(item.id)) errors.push({code: "duplicate_id", ref: item.id}); + seen.add(item.id); + } + const kind = item.kind; + if (typeof kind !== "string" || !ITEM_KINDS.includes(kind)) errors.push({code: "invalid_item", ref}); + const fontSize = item.font_size; + if (fontSize !== undefined && fontSize !== null && + (typeof fontSize !== "string" || !FONT_SIZES.includes(fontSize))) { + errors.push({code: "invalid_font_size", ref}); + } + if (kind === "text") { + const text = item.text; + if (typeof text !== "string" || cpLen(text) < 1 || cpLen(text) > MAX_TEXT_LEN) { + errors.push({code: "invalid_text", ref}); + } + } else if (kind === "emoji") { + const value = item.emoji; + if (typeof value !== "string" || !emoji.has(normalizeEmoji(value))) { + errors.push({code: "unsupported_emoji", ref}); + } + } else if (kind === "entity" && !validEntityItem(item)) { + errors.push({code: "invalid_entity", ref}); + } +} + +function checkBlock( + block: Obj, seen: Set, positions: Set, emoji: ReadonlySet, errors: LayoutError[], +): void { + const ref = refOf(block.id); + if (!isId(block.id)) errors.push({code: "invalid_id", ref}); + if (typeof block.id === "string") { + if (seen.has(block.id)) errors.push({code: "duplicate_id", ref: block.id}); + seen.add(block.id); + } + + const {x, y} = block; + if (![x, y].every((v) => isInt(v) && Math.abs(v) <= COORD_LIMIT)) { + errors.push({code: "coordinate_out_of_range", ref}); + } else { + const k = `${x},${y}`; + if (positions.has(k)) errors.push({code: "duplicate_position", ref}); + positions.add(k); + } + + const name = block.name; + if (typeof name !== "string" || cpLen(name.trim()) < 1 || cpLen(name.trim()) > MAX_NAME_LEN) { + errors.push({code: "invalid_name", ref}); + } + if (typeof block.background !== "string" || !COLOR_RE.test(block.background)) { + errors.push({code: "invalid_background", ref}); + } + if (typeof block.font_size !== "string" || !FONT_SIZES.includes(block.font_size)) { + errors.push({code: "invalid_font_size", ref}); + } + + if (block.type === "entity") { + if (!validEntityBlock(block)) errors.push({code: "invalid_entity", ref}); + } else if (block.type === "custom") { + const items = block.items as Obj[]; + if (items.length > MAX_ITEMS) errors.push({code: "too_many_items", ref}); + for (const item of items) checkItem(item, seen, emoji, errors); + } else { + errors.push({code: "invalid_type", ref}); + } +} + +function unreachable(layout: Obj & {blocks: Obj[]}): LayoutError[] { + if (layout.blocks.length === 0) return []; + const blocks = layout.blocks as unknown as Block[]; + const seen = reachable(blocks, layout.start as string); + return blocks.filter((b) => !seen.has(b.id)).map((b) => ({code: "disconnected", ref: b.id})); +} + +/** Validate a layout; an empty list means it is valid. Mirrors layout.py. */ +export function validateLayout(layout: unknown, emoji: ReadonlySet): LayoutError[] { + if (!checkStructure(layout)) return [{code: "invalid_structure", ref: null}]; + + const errors: LayoutError[] = []; + const blocks = layout.blocks; + if (blocks.length > MAX_BLOCKS) errors.push({code: "too_many_blocks", ref: null}); + const timeout = layout.settings.sleep_timeout; + if (!isInt(timeout) || !(timeout === 0 || (timeout >= MIN_SLEEP_TIMEOUT && timeout <= MAX_SLEEP_TIMEOUT))) { + errors.push({code: "invalid_sleep_timeout", ref: null}); + } + + const seen = new Set(); + const positions = new Set(); + for (const block of blocks) checkBlock(block, seen, positions, emoji, errors); + + const start = layout.start; + const startOk = start === undefined || start === null + ? blocks.length === 0 + : typeof start === "string" && blocks.some((b) => b.id === start); + if (!startOk) errors.push({code: "invalid_start", ref: null}); + + return errors.length > 0 ? errors : unreachable(layout); +} diff --git a/custom_components/ha_controller/frontend/src/types.ts b/custom_components/ha_controller/frontend/src/types.ts new file mode 100644 index 0000000..d3c4c87 --- /dev/null +++ b/custom_components/ha_controller/frontend/src/types.ts @@ -0,0 +1,65 @@ +export type FontSize = "s" | "m" | "l" | "xl"; +export type ItemKind = "text" | "emoji" | "entity" | "battery" | "brightness"; + +export interface Item { + id: string; + kind: ItemKind; + font_size: FontSize | null; + text?: string; + emoji?: string; + entity_id?: string; + attribute?: string | null; +} + +export interface Block { + id: string; + x: number; + y: number; + name: string; + background: string; + font_size: FontSize; + type: "entity" | "custom"; + entity_id?: string; + items?: Item[]; +} + +export interface Layout { + version: 1; + start: string | null; + settings: {sleep_timeout: number}; + blocks: Block[]; +} + +export interface LayoutError { + code: string; + ref: string | null; +} + +export interface Cell { + x: number; + y: number; +} + +/** One screen as listed by `ha_controller/screens` (spec section 8). */ +export interface ScreenInfo { + entry_id: string; + title: string; + device_id: string; + online: boolean; + firmware_version: string | null; + integration_version: string; + protocol_ok: boolean | null; + revision: string; + device_revision: string | null; +} + +export interface HassEntity { + entity_id: string; + state: string; + attributes: Record; +} + +export interface Hass { + states: Record; + callWS(msg: {type: string; [key: string]: unknown}): Promise; +} diff --git a/custom_components/ha_controller/frontend/test/color.test.ts b/custom_components/ha_controller/frontend/test/color.test.ts new file mode 100644 index 0000000..5b3340c --- /dev/null +++ b/custom_components/ha_controller/frontend/test/color.test.ts @@ -0,0 +1,10 @@ +import {describe, expect, it} from "vitest"; +import {textColorFor} from "../src/model/color"; +import {colors} from "./fixtures"; + +describe("textColorFor", () => { + it("matches the shared vectors", () => { + expect(colors.length).toBeGreaterThan(0); + for (const c of colors) expect(textColorFor(c.bg)).toBe(c.text); + }); +}); diff --git a/custom_components/ha_controller/frontend/test/dom.ts b/custom_components/ha_controller/frontend/test/dom.ts new file mode 100644 index 0000000..91516b3 --- /dev/null +++ b/custom_components/ha_controller/frontend/test/dom.ts @@ -0,0 +1,27 @@ +import {render, type TemplateResult} from "lit"; + +/** Render a Lit template into document.body and wait for the first element to settle. */ +export async function mount(template: TemplateResult): Promise { + const host = document.createElement("div"); + document.body.append(host); + render(template, host); + const el = host.firstElementChild as T & {updateComplete?: Promise}; + await el.updateComplete; + return el; +} + +export function all(el: Element, selector: string): E[] { + return [...(el.shadowRoot as ShadowRoot).querySelectorAll(selector)]; +} + +export function one(el: Element, selector: string): E | null { + return (el.shadowRoot as ShadowRoot).querySelector(selector); +} + +export function nextEvent(el: EventTarget, name: string): Promise> { + return new Promise((resolve) => el.addEventListener(name, (e) => resolve(e as CustomEvent), {once: true})); +} + +export function cleanup(): void { + document.body.innerHTML = ""; +} diff --git a/custom_components/ha_controller/frontend/test/edit.test.ts b/custom_components/ha_controller/frontend/test/edit.test.ts new file mode 100644 index 0000000..e2e9949 --- /dev/null +++ b/custom_components/ha_controller/frontend/test/edit.test.ts @@ -0,0 +1,86 @@ +import {describe, expect, it} from "vitest"; +import { + PALETTE, addBlock, addItem, deleteBlock, moveItem, nextId, removeItem, setSleepTimeout, setStart, + updateBlock, updateItem, +} from "../src/model/edit"; +import type {Layout} from "../src/types"; +import {validLayouts} from "./fixtures"; + +const ref = validLayouts.reference; +const itemIds = (l: Layout, blockId: string): string[] => + (l.blocks.find((b) => b.id === blockId)?.items ?? []).map((i) => i.id); + +describe("edit operations", () => { + it("has an 8 colour palette", () => expect(PALETTE).toHaveLength(8)); + + it("nextId continues the highest suffix", () => { + expect(nextId(ref, "i")).toBe("i6"); + expect(nextId(ref, "b")).toBe("b5"); + expect(nextId(validLayouts.empty, "b")).toBe("b1"); + }); + + it("addBlock", () => { + const r = addBlock(ref, {x: 1, y: 0}); + expect(r.id).toBe("b5"); + expect(r.layout.blocks.at(-1)).toMatchObject({ + x: 1, y: 0, name: "Block 5", background: "#E08A2E", font_size: "m", type: "custom", items: [], + }); + expect(r.layout.start).toBe("b1"); + expect(addBlock(validLayouts.empty, {x: 0, y: 0}).layout).toMatchObject({ + start: "b1", blocks: [{id: "b1", background: "#C94F3D"}], + }); + }); + + it("deleteBlock", () => { + expect(deleteBlock(validLayouts.single, "b1")).toEqual({ + version: 1, start: null, settings: {sleep_timeout: 0}, blocks: [], + }); + expect(deleteBlock(ref, "b4").blocks.map((b) => b.id)).toEqual(["b1", "b2", "b3"]); + expect(() => deleteBlock(ref, "b3")).toThrow(); + expect(() => deleteBlock(ref, "b1")).toThrow(); + }); + + it("setStart, updateBlock, setSleepTimeout", () => { + expect(setStart(ref, "b2").start).toBe("b2"); + expect(updateBlock(ref, "b2", {name: "X"}).blocks[1].name).toBe("X"); + expect(setSleepTimeout(ref, 45).settings).toEqual({sleep_timeout: 45}); + }); + + it("addItem defaults", () => { + const text = addItem(ref, "b3", "text"); + expect(text.id).toBe("i6"); + expect(text.layout.blocks[2].items?.at(-1)).toEqual({id: "i6", kind: "text", text: "Text", font_size: null}); + expect(addItem(ref, "b3", "emoji").layout.blocks[2].items?.at(-1)) + .toEqual({id: "i6", kind: "emoji", emoji: "💡", font_size: null}); + expect(addItem(ref, "b3", "entity").layout.blocks[2].items?.at(-1)) + .toEqual({id: "i6", kind: "entity", entity_id: "", attribute: null, font_size: null}); + expect(addItem(ref, "b3", "battery").layout.blocks[2].items?.at(-1)) + .toEqual({id: "i6", kind: "battery", font_size: null}); + }); + + it("updateItem and removeItem", () => { + expect(updateItem(ref, "b3", "i1", {text: "Hi"}).blocks[2].items?.[0]).toMatchObject({id: "i1", text: "Hi"}); + expect(itemIds(removeItem(ref, "b3", "i2"), "b3")).toEqual(["i1", "i3", "i4", "i5"]); + }); + + it("moveItem", () => { + expect(itemIds(moveItem(ref, "b3", "i1", 1), "b3")).toEqual(["i2", "i1", "i3", "i4", "i5"]); + expect(itemIds(moveItem(ref, "b3", "i1", -1), "b3")).toEqual(["i1", "i2", "i3", "i4", "i5"]); + expect(itemIds(moveItem(ref, "b3", "i5", 1), "b3")).toEqual(["i1", "i2", "i3", "i4", "i5"]); + expect(itemIds(moveItem(ref, "b3", "i3", -1), "b3")).toEqual(["i1", "i3", "i2", "i4", "i5"]); + }); + + it("never mutates its input", () => { + const copy = structuredClone(ref); + addBlock(copy, {x: 1, y: 0}); + deleteBlock(copy, "b4"); + setStart(copy, "b2"); + updateBlock(copy, "b2", {name: "X"}); + setSleepTimeout(copy, 45); + addItem(copy, "b3", "text"); + updateItem(copy, "b3", "i1", {text: "Hi"}); + removeItem(copy, "b3", "i2"); + moveItem(copy, "b3", "i1", 1); + expect(copy).toEqual(ref); + }); +}); diff --git a/custom_components/ha_controller/frontend/test/emoji.test.ts b/custom_components/ha_controller/frontend/test/emoji.test.ts new file mode 100644 index 0000000..a4e9f31 --- /dev/null +++ b/custom_components/ha_controller/frontend/test/emoji.test.ts @@ -0,0 +1,13 @@ +import {describe, expect, it} from "vitest"; +import {EMOJI_SET, SUPPORTED_EMOJI, normalizeEmoji} from "../src/model/emoji"; + +describe("emoji", () => { + it("has 64 supported emoji", () => { + expect(SUPPORTED_EMOJI).toHaveLength(64); + expect(EMOJI_SET.size).toBe(64); + }); + it("strips the variation selector", () => { + expect(normalizeEmoji("❄️")).toBe("❄"); + expect(normalizeEmoji("💡")).toBe("💡"); + }); +}); diff --git a/custom_components/ha_controller/frontend/test/fixtures.ts b/custom_components/ha_controller/frontend/test/fixtures.ts new file mode 100644 index 0000000..c2533c9 --- /dev/null +++ b/custom_components/ha_controller/frontend/test/fixtures.ts @@ -0,0 +1,20 @@ +import type {Layout, LayoutError} from "../src/types"; + +function byName(modules: Record): Record { + return Object.fromEntries( + Object.entries(modules).map(([path, value]) => [path.split("/").pop()!.replace(/\.json$/, ""), value]), + ); +} + +export const validLayouts = byName( + import.meta.glob("../../../../docs/protocol/fixtures/layouts/valid/*.json", {eager: true, import: "default"}), +); + +export const invalidLayouts = byName( + import.meta.glob<{expect: LayoutError; layout: unknown}>( + "../../../../docs/protocol/fixtures/layouts/invalid/*.json", {eager: true, import: "default"}), +); + +export const colors = Object.values( + import.meta.glob<{bg: string; text: string}[]>("../../../../docs/protocol/fixtures/colors.json", {eager: true, import: "default"}), +)[0]; diff --git a/custom_components/ha_controller/frontend/test/grid.test.ts b/custom_components/ha_controller/frontend/test/grid.test.ts new file mode 100644 index 0000000..bb7da4e --- /dev/null +++ b/custom_components/ha_controller/frontend/test/grid.test.ts @@ -0,0 +1,57 @@ +import {describe, expect, it} from "vitest"; +import {canDelete, gridBounds, placeholders} from "../src/model/grid"; +import type {Block, Cell, Layout} from "../src/types"; +import {validLayouts} from "./fixtures"; + +const block = (id: string, x: number, y: number): Block => ({ + id, x, y, name: id, background: "#000000", font_size: "m", type: "custom", items: [], +}); +const layoutOf = (blocks: Block[]): Layout => ({ + version: 1, start: blocks[0]?.id ?? null, settings: {sleep_timeout: 20}, blocks, +}); +const cellsOf = (layout: Layout): Cell[] => layout.blocks.map(({x, y}) => ({x, y})); + +describe("fixtures", () => { + it("are loaded", () => { + expect(Object.keys(validLayouts).length).toBeGreaterThan(0); + }); +}); + +describe("placeholders", () => { + it("offers the origin for an empty layout", () => { + expect(placeholders(validLayouts.empty)).toEqual([{x: 0, y: 0}]); + }); + it("finds the 8 plus cells of the reference screenshot", () => { + expect(placeholders(validLayouts.reference)).toEqual([ + {x: 0, y: -2}, {x: -1, y: -1}, {x: 1, y: -1}, {x: -2, y: 0}, + {x: 1, y: 0}, {x: -2, y: 1}, {x: 0, y: 1}, {x: -1, y: 2}]); + }); + it("offers nothing at 32 blocks", () => { + const row = Array.from({length: 32}, (_, i) => block(`b${i}`, i, 0)); + expect(placeholders(layoutOf(row))).toEqual([]); + }); + it("stays within the coordinate limit", () => { + expect(placeholders(layoutOf([block("b1", 32, 0)]))).not.toContainEqual({x: 33, y: 0}); + }); +}); + +describe("canDelete", () => { + it("refuses the start block", () => { + expect(canDelete(validLayouts.reference, "b1")).toEqual({ok: false, reason: "start"}); + }); + it("refuses a block that disconnects another", () => { + expect(canDelete(validLayouts.reference, "b3")).toEqual({ok: false, reason: "disconnects"}); + }); + it("allows a leaf block", () => { + expect(canDelete(validLayouts.reference, "b2")).toEqual({ok: true}); + }); + it("allows deleting the only block", () => { + expect(canDelete(validLayouts.single, "b1")).toEqual({ok: true}); + }); +}); + +describe("gridBounds", () => { + it("bounds a single cell", () => { + expect(gridBounds(cellsOf(validLayouts.single))).toEqual({minX: 3, maxX: 3, minY: -2, maxY: -2}); + }); +}); diff --git a/custom_components/ha_controller/frontend/test/hass.ts b/custom_components/ha_controller/frontend/test/hass.ts new file mode 100644 index 0000000..9cd5fb6 --- /dev/null +++ b/custom_components/ha_controller/frontend/test/hass.ts @@ -0,0 +1,20 @@ +import type {Hass, HassEntity} from "../src/types"; + +const entity = (entity_id: string, state: string, friendly_name: string, extra: Record = {}): HassEntity => ({ + entity_id, + state, + attributes: {friendly_name, ...extra}, +}); + +/** Minimal fake `hass` for component tests. */ +export function fakeHass(): Hass { + const states = Object.fromEntries( + [ + entity("light.kitchen", "on", "Kitchen"), + entity("light.living_room", "off", "Living room"), + entity("climate.bedroom", "heat", "Bedroom"), + entity("sensor.outdoor_temperature", "21.5", "Outdoor temperature", {unit_of_measurement: "°C"}), + ].map((e) => [e.entity_id, e]), + ); + return {states, callWS: () => Promise.reject(new Error("not available in tests"))}; +} diff --git a/custom_components/ha_controller/frontend/test/hc-block-editor.test.ts b/custom_components/ha_controller/frontend/test/hc-block-editor.test.ts new file mode 100644 index 0000000..3ab01bf --- /dev/null +++ b/custom_components/ha_controller/frontend/test/hc-block-editor.test.ts @@ -0,0 +1,143 @@ +import {html} from "lit"; +import {afterEach, describe, expect, it} from "vitest"; +import "../src/components/hc-block-editor"; +import {all, cleanup, mount, nextEvent, one} from "./dom"; +import {validLayouts} from "./fixtures"; +import {fakeHass} from "./hass"; +import type {Layout} from "../src/types"; + +afterEach(cleanup); + +const hass = fakeHass(); +const editor = (blockId: string, layout: Layout = validLayouts.reference) => + mount(html``); + +function type(input: HTMLInputElement, value: string): void { + input.value = value; + input.dispatchEvent(new Event("input", {bubbles: true})); + input.dispatchEvent(new Event("change", {bubbles: true})); +} + +describe("hc-block-editor", () => { + it("emits the new layout when the name changes, without mutating the property", async () => { + const el = await editor("b1"); + const changed = nextEvent<{layout: Layout}>(el, "hc-layout-change"); + type(one(el, "input[name=name]")!, "Kitchen 2"); + expect((await changed).detail.layout.blocks[0].name).toBe("Kitchen 2"); + expect(validLayouts.reference.blocks[0].name).toBe("Kitchen"); + }); + + it("offers matching entities in the entity input", async () => { + const el = await editor("b1"); + const input = one(el, "hc-entity-input")!; + await (input as unknown as {updateComplete: Promise}).updateComplete; + const values = all(input, "datalist option").map((o) => o.value); + expect(values).toEqual(["climate.bedroom", "light.kitchen", "light.living_room"]); + }); + + it("changes the entity", async () => { + const el = await editor("b1"); + const input = one(el, "hc-entity-input")!; + const changed = nextEvent<{layout: Layout}>(el, "hc-layout-change"); + type(one(input, "input")!, "light.living_room"); + expect((await changed).detail.layout.blocks[0].entity_id).toBe("light.living_room"); + }); + + it("changes the background from a swatch and the font size", async () => { + const el = await editor("b1"); + expect(all(el, "button.swatch")).toHaveLength(8); + let changed = nextEvent<{layout: Layout}>(el, "hc-layout-change"); + all(el, "button.swatch")[1].click(); + expect((await changed).detail.layout.blocks[0].background).toBe("#4F86DD"); + changed = nextEvent(el, "hc-layout-change"); + all(el, "button.font-size").find((b) => b.textContent!.trim() === "XL")!.click(); + expect((await changed).detail.layout.blocks[0].font_size).toBe("xl"); + }); + + it("switches to Custom keeping the entity and adding items", async () => { + const el = await editor("b1"); + const changed = nextEvent<{layout: Layout}>(el, "hc-layout-change"); + const select = one(el, "select[name=type]")!; + select.value = "custom"; + select.dispatchEvent(new Event("change", {bubbles: true})); + const block = (await changed).detail.layout.blocks[0]; + expect(block.type).toBe("custom"); + expect(block.entity_id).toBe("light.kitchen"); + expect(block.items).toEqual([]); + }); + + it("switches back to Entity keeping the items", async () => { + const el = await editor("b3"); + const changed = nextEvent<{layout: Layout}>(el, "hc-layout-change"); + const select = one(el, "select[name=type]")!; + select.value = "entity"; + select.dispatchEvent(new Event("change", {bubbles: true})); + const block = (await changed).detail.layout.blocks[2]; + expect(block.type).toBe("entity"); + expect(block.items).toHaveLength(5); + }); + + it("lists items of a custom block and adds an item", async () => { + const el = await editor("b3"); + expect(all(el, "hc-item-editor")).toHaveLength(5); + const changed = nextEvent<{layout: Layout}>(el, "hc-layout-change"); + const select = one(el, "select[name=add-item]")!; + select.value = "battery"; + select.dispatchEvent(new Event("change", {bubbles: true})); + const items = (await changed).detail.layout.blocks[2].items!; + expect(items).toHaveLength(6); + expect(items[5].kind).toBe("battery"); + }); + + it("applies item events to the layout", async () => { + const el = await editor("b3"); + const editors = all(el, "hc-item-editor"); + let changed = nextEvent<{layout: Layout}>(el, "hc-layout-change"); + editors[0].dispatchEvent(new CustomEvent("hc-item-change", {detail: {patch: {text: "Hi"}}, bubbles: true, composed: true})); + expect((await changed).detail.layout.blocks[2].items![0].text).toBe("Hi"); + changed = nextEvent(el, "hc-layout-change"); + editors[0].dispatchEvent(new CustomEvent("hc-item-move", {detail: {delta: 1}, bubbles: true, composed: true})); + expect((await changed).detail.layout.blocks[2].items![1].id).toBe("i1"); + changed = nextEvent(el, "hc-layout-change"); + editors[1].dispatchEvent(new CustomEvent("hc-item-remove", {bubbles: true, composed: true})); + expect((await changed).detail.layout.blocks[2].items).toHaveLength(4); + }); + + it("disables start and delete for the start block and explains why", async () => { + const el = await editor("b1"); + expect(one(el, "button.start")!.hasAttribute("disabled")).toBe(true); + expect(one(el, "button.delete")!.hasAttribute("disabled")).toBe(true); + expect(el.shadowRoot!.textContent).toContain("Choose another start block first."); + }); + + it("explains a delete that would disconnect blocks", async () => { + const layout: Layout = { + ...validLayouts.reference, + blocks: [ + {id: "b1", x: 0, y: 0, name: "A", background: "#C94F3D", font_size: "m", type: "custom", items: []}, + {id: "b2", x: 1, y: 0, name: "B", background: "#4F86DD", font_size: "m", type: "custom", items: []}, + {id: "b3", x: 2, y: 0, name: "C", background: "#5B9E4D", font_size: "m", type: "custom", items: []}, + ], + }; + const el = await editor("b2", layout); + expect(one(el, "button.delete")!.hasAttribute("disabled")).toBe(true); + expect(el.shadowRoot!.textContent).toContain("Other blocks would become unreachable."); + }); + + it("sets the start block and deletes a leaf block", async () => { + let el = await editor("b2"); + expect(one(el, "button.start")!.hasAttribute("disabled")).toBe(false); + let changed = nextEvent<{layout: Layout}>(el, "hc-layout-change"); + one(el, "button.start")!.click(); + expect((await changed).detail.layout.start).toBe("b2"); + el = await editor("b2"); + changed = nextEvent(el, "hc-layout-change"); + one(el, "button.delete")!.click(); + expect((await changed).detail.layout.blocks.map((b) => b.id)).toEqual(["b1", "b3", "b4"]); + }); + + it("renders a preview", async () => { + const el = await editor("b1"); + expect(one(el, "hc-preview")).not.toBeNull(); + }); +}); diff --git a/custom_components/ha_controller/frontend/test/hc-grid.test.ts b/custom_components/ha_controller/frontend/test/hc-grid.test.ts new file mode 100644 index 0000000..db8d454 --- /dev/null +++ b/custom_components/ha_controller/frontend/test/hc-grid.test.ts @@ -0,0 +1,86 @@ +import {html} from "lit"; +import {afterEach, describe, expect, it} from "vitest"; +import "../src/components/hc-grid"; +import {all, cleanup, mount, nextEvent, one} from "./dom"; +import {defineElement} from "../src/define"; +import {validLayouts} from "./fixtures"; + +afterEach(cleanup); + +const reference = () => + mount(html``); + +describe("hc-grid", () => { + it("renders blocks, placeholders, start badge and error state", async () => { + const el = await reference(); + expect(all(el, ".block")).toHaveLength(4); + expect(all(el, ".placeholder")).toHaveLength(8); + expect(one(el, '.block[data-id="b1"] .start-badge')?.textContent).toBe("start"); + expect(all(el, ".start-badge")).toHaveLength(1); + expect(one(el, '.block[data-id="b1"]')!.classList.contains("start")).toBe(true); + expect(one(el, '.block[data-id="b1"] .start-badge')).not.toBeNull(); + expect(all(el, ".block.start")).toHaveLength(1); + expect(one(el, '.block[data-id="b4"]')!.classList.contains("has-error")).toBe(true); + expect(one(el, '.block[data-id="b1"]')!.classList.contains("has-error")).toBe(false); + }); + + it("places cells on the grid with x right and y down", async () => { + const el = await reference(); + expect(one(el, '.block[data-id="b3"]')!.style.gridColumn).toBe("2"); + expect(one(el, '.block[data-id="b3"]')!.style.gridRow).toBe("3"); + }); + + it("marks the selected block and colours its text", async () => { + const layout = validLayouts.reference; + const el = await mount(html`()}>`); + expect(one(el, '.block[data-id="b2"]')!.classList.contains("selected")).toBe(true); + expect(all(el, ".block.selected")).toHaveLength(1); + const block = layout.blocks[0]; + const node = one(el, `.block[data-id="${block.id}"]`)!; + expect(node.style.background).not.toBe(""); + expect(["#000000", "#ffffff", "rgb(0, 0, 0)", "rgb(255, 255, 255)"]).toContain(node.style.color.toLowerCase()); + }); + + it("emits hc-add-block from a placeholder", async () => { + const el = await reference(); + const added = nextEvent<{x: number; y: number}>(el, "hc-add-block"); + one(el, '.placeholder[data-x="1"][data-y="0"]')!.click(); + const event = await added; + expect(event.detail).toEqual({x: 1, y: 0}); + expect(event.bubbles && event.composed).toBe(true); + }); + + it("emits hc-select-block from a block", async () => { + const el = await reference(); + const selected = nextEvent<{id: string}>(el, "hc-select-block"); + one(el, '.block[data-id="b3"]')!.click(); + const event = await selected; + expect(event.detail).toEqual({id: "b3"}); + expect(event.bubbles && event.composed).toBe(true); + }); + + it("can show selected and has-error on the same block", async () => { + const el = await mount(html``); + const node = one(el, '.block[data-id="b4"]')!; + expect(node.classList.contains("selected") && node.classList.contains("has-error")).toBe(true); + }); + + it("renders a single origin placeholder for an empty layout", async () => { + const empty = {version: 1 as const, start: null, settings: {sleep_timeout: 0}, blocks: []}; + const el = await mount(html``); + const ph = all(el, ".placeholder"); + expect(ph).toHaveLength(1); + expect(ph[0].dataset.x).toBe("0"); + expect(ph[0].dataset.y).toBe("0"); + }); +}); + +describe("defineElement", () => { + it("does not throw when the same name is defined twice", () => { + class Dummy extends HTMLElement {} + expect(() => { + defineElement("hc-define-test", Dummy); + defineElement("hc-define-test", Dummy); + }).not.toThrow(); + }); +}); diff --git a/custom_components/ha_controller/frontend/test/hc-item-editor.test.ts b/custom_components/ha_controller/frontend/test/hc-item-editor.test.ts new file mode 100644 index 0000000..f592683 --- /dev/null +++ b/custom_components/ha_controller/frontend/test/hc-item-editor.test.ts @@ -0,0 +1,96 @@ +import {html} from "lit"; +import {afterEach, describe, expect, it} from "vitest"; +import "../src/components/hc-item-editor"; +import "../src/components/hc-emoji-picker"; +import "../src/components/hc-preview"; +import {all, cleanup, mount, nextEvent, one} from "./dom"; +import {fakeHass} from "./hass"; +import {validLayouts} from "./fixtures"; +import type {Item} from "../src/types"; + +afterEach(cleanup); + +const hass = fakeHass(); +const items = validLayouts.reference.blocks[2].items as Item[]; +const item = (i: number) => + mount(html``); + +describe("hc-item-editor", () => { + it("emits a text patch", async () => { + const el = await item(0); + const input = one(el, "input[name=text]")!; + const changed = nextEvent<{patch: Partial}>(el, "hc-item-change"); + input.value = "Hi"; + input.dispatchEvent(new Event("input", {bubbles: true})); + expect((await changed).detail.patch).toEqual({text: "Hi"}); + }); + + it("emits font size patches, null for inherit", async () => { + const el = await item(1); + const select = one(el, "select[name=font-size]")!; + expect(select.value).toBe("xl"); + const changed = nextEvent<{patch: Partial}>(el, "hc-item-change"); + select.value = ""; + select.dispatchEvent(new Event("change", {bubbles: true})); + expect((await changed).detail.patch).toEqual({font_size: null}); + }); + + it("emits move and remove, disabling impossible moves", async () => { + const el = await item(0); + expect(one(el, "button.up")!.hasAttribute("disabled")).toBe(true); + expect(one(el, "button.down")!.hasAttribute("disabled")).toBe(false); + const moved = nextEvent<{delta: number}>(el, "hc-item-move"); + one(el, "button.down")!.click(); + expect((await moved).detail.delta).toBe(1); + const removed = nextEvent(el, "hc-item-remove"); + one(el, "button.remove")!.click(); + await removed; + }); + + it("edits an entity item with attribute", async () => { + const el = await item(2); + expect(one(el, "hc-entity-input")).not.toBeNull(); + const input = one(el, "input[name=attribute]")!; + const changed = nextEvent<{patch: Partial}>(el, "hc-item-change"); + input.value = "unit"; + input.dispatchEvent(new Event("input", {bubbles: true})); + expect((await changed).detail.patch).toEqual({attribute: "unit"}); + }); + + it("maps the emoji picker to an emoji patch", async () => { + const el = await item(1); + const changed = nextEvent<{patch: Partial}>(el, "hc-item-change"); + one(el, "hc-emoji-picker")!.dispatchEvent(new CustomEvent("hc-value-change", {detail: {value: "💡"}, bubbles: true, composed: true})); + expect((await changed).detail.patch).toEqual({emoji: "💡"}); + }); + + it("has no extra fields for battery items", async () => { + const el = await item(3); + expect(one(el, "input")).toBeNull(); + }); +}); + +describe("hc-emoji-picker", () => { + it("renders 64 buttons and emits the normalised value", async () => { + const picker = await mount(html``); + const buttons = all(picker, "button.emoji"); + expect(buttons).toHaveLength(64); + const changed = nextEvent<{value: string}>(picker, "hc-value-change"); + buttons[3].click(); + expect((await changed).detail.value).toBe(buttons[3].textContent!.trim().replaceAll("️", "")); + }); +}); + +describe("hc-preview", () => { + it("shows the entity state for entity blocks", async () => { + const el = await mount(html``); + expect(el.shadowRoot!.textContent).toContain("Kitchen"); + expect(el.shadowRoot!.textContent).toContain("on"); + }); + + it("shows one line per item for custom blocks", async () => { + const el = await mount(html``); + expect(all(el, ".line")).toHaveLength(5); + expect(el.shadowRoot!.textContent).toContain("21.5"); + }); +}); diff --git a/custom_components/ha_controller/frontend/test/panel.test.ts b/custom_components/ha_controller/frontend/test/panel.test.ts new file mode 100644 index 0000000..9e6d52d --- /dev/null +++ b/custom_components/ha_controller/frontend/test/panel.test.ts @@ -0,0 +1,291 @@ +import {html} from "lit"; +import {afterEach, beforeEach, describe, expect, it, vi} from "vitest"; +import "../src/ha-controller-panel"; +import type {HaControllerPanel} from "../src/ha-controller-panel"; +import {createMockHass} from "../dev/mock-hass"; +import type {Hass, Layout, ScreenInfo} from "../src/types"; +import {all, cleanup, mount, one} from "./dom"; + +afterEach(() => { + cleanup(); + vi.useRealTimers(); +}); + +function spied(screen: Partial = {}) { + const hass = createMockHass(screen); + const real = hass.callWS.bind(hass); + const callWS = vi.fn(real); + hass.callWS = callWS as unknown as Hass["callWS"]; + return {hass, callWS, real}; +} + +function saveCall(callWS: {mock: {calls: unknown[][]}}): {entry_id: string; layout: Layout} { + const msgs = callWS.mock.calls.map((c) => c[0] as {type: string; entry_id: string; layout: Layout}); + return msgs.find((m) => m.type === "ha_controller/layout/save")!; +} + +async function settle(el: HaControllerPanel): Promise { + for (let i = 0; i < 5; i++) { + await Promise.resolve(); + await el.updateComplete; + } +} + +async function open(hass: Hass): Promise { + const el = await mount(html``); + await settle(el); + return el; +} + +const blocks = (el: HaControllerPanel) => all(one(el, "hc-grid")!, ".block"); +const saveButton = (el: HaControllerPanel) => one(el, "button.save")!; +const click = async (el: HaControllerPanel, node: Element) => { + (node as HTMLElement).click(); + await settle(el); +}; +const addBlockRight = async (el: HaControllerPanel) => { + await click(el, one(one(el, "hc-grid")!, '.placeholder[data-x="1"][data-y="0"]')!); +}; + +describe("ha-controller-panel", () => { + it("loads the first screen and renders its map", async () => { + const {hass} = spied(); + const el = await open(hass); + expect(blocks(el)).toHaveLength(4); + }); + + it("save is disabled until something changes", async () => { + const {hass} = spied(); + const el = await open(hass); + expect(saveButton(el).disabled).toBe(true); + await addBlockRight(el); + expect(saveButton(el).disabled).toBe(false); + await click(el, one(el, "button.revert")!); + expect(blocks(el)).toHaveLength(4); + expect(saveButton(el).disabled).toBe(true); + }); + + it("adding a block and saving sends the new layout", async () => { + const {hass, callWS} = spied(); + const el = await open(hass); + await addBlockRight(el); + await click(el, saveButton(el)); + const call = saveCall(callWS); + expect(call.entry_id).toBe("mock-entry"); + expect(call.layout.blocks).toHaveLength(5); + expect(one(el, ".notice")!.textContent).toContain("Saved — sent to the screen."); + expect(saveButton(el).disabled).toBe(true); + }); + + it("save error keeps changes", async () => { + const {hass, callWS, real} = spied(); + const el = await open(hass); + await addBlockRight(el); + callWS.mockImplementation((msg: {type: string}) => + msg.type === "ha_controller/layout/save" + ? Promise.reject({code: "invalid_layout", message: "invalid_name@b2"}) + : real(msg), + ); + await click(el, saveButton(el)); + expect(one(el, ".notice")!.textContent).toContain("Names need 1 to 32 characters."); + expect(blocks(el)).toHaveLength(5); + expect(saveButton(el).disabled).toBe(false); + }); + + it("shows the message of other save errors", async () => { + const {hass, callWS, real} = spied(); + const el = await open(hass); + await addBlockRight(el); + callWS.mockImplementation((msg: {type: string}) => + msg.type === "ha_controller/layout/save" ? Promise.reject({code: "not_found", message: "Screen not found"}) : real(msg), + ); + await click(el, saveButton(el)); + expect(one(el, ".notice")!.textContent).toContain("Screen not found"); + }); + + describe("with fake timers", () => { + beforeEach(() => vi.useFakeTimers()); + + it("refresh does not reset working copy", async () => { + const {hass, callWS} = spied(); + const el = await open(hass); + await addBlockRight(el); + callWS.mockClear(); + await vi.advanceTimersByTimeAsync(10_000); + await settle(el); + expect(callWS.mock.calls.map((c) => c[0].type)).toEqual(["ha_controller/screens"]); + el.hass = {...hass}; + await settle(el); + expect(blocks(el)).toHaveLength(5); + expect(callWS.mock.calls.map((c) => c[0].type)).toEqual(["ha_controller/screens"]); + }); + + it("stops refreshing when removed", async () => { + const {hass, callWS} = spied(); + const el = await open(hass); + el.remove(); + callWS.mockClear(); + await vi.advanceTimersByTimeAsync(30_000); + expect(callWS).not.toHaveBeenCalled(); + }); + }); + + it("changing the sleep delay enables Save and sends it", async () => { + const {hass, callWS} = spied(); + const el = await open(hass); + const input = one(el, 'input[name="sleep_timeout"]')!; + expect(input.value).toBe("20"); + input.value = "45"; + input.dispatchEvent(new Event("input")); + await settle(el); + expect(saveButton(el).disabled).toBe(false); + await click(el, saveButton(el)); + const call = saveCall(callWS); + expect(call.layout.settings.sleep_timeout).toBe(45); + }); + + it("disables Save and lists local errors for an invalid sleep delay", async () => { + const {hass} = spied(); + const el = await open(hass); + const input = one(el, 'input[name="sleep_timeout"]')!; + input.value = "2"; + input.dispatchEvent(new Event("input")); + await settle(el); + expect(saveButton(el).disabled).toBe(true); + expect(one(el, ".errors")!.textContent).toContain("The sleep delay must be 0"); + }); + + describe("status line", () => { + it("reports update available", async () => { + const el = await open(spied({firmware_version: "0.0.9"}).hass); + expect(one(el, ".status")!.textContent).toContain("Online · firmware 0.0.9 — update available"); + }); + it("reports in sync", async () => { + const el = await open(spied().hass); + expect(one(el, ".status")!.textContent).toContain("Online · firmware 0.1.0 · in sync"); + }); + it("reports syncing", async () => { + const el = await open(spied({device_revision: "old"}).hass); + expect(one(el, ".status")!.textContent).toContain("Online · firmware 0.1.0 · syncing…"); + }); + it("reports offline", async () => { + const el = await open(spied({online: false}).hass); + expect(one(el, ".status")!.textContent?.trim()).toBe("Offline"); + }); + }); + + it("shows the menu button only when narrow", async () => { + const {hass} = spied(); + const el = await open(hass); + expect(one(el, "ha-menu-button")).toBeNull(); + el.narrow = true; + await settle(el); + expect(one(el, "ha-menu-button")).not.toBeNull(); + }); + + describe("screen state", () => { + const twoScreens = () => { + const {hass, callWS, real} = spied(); + const info = (id: string, title: string) => ({ + entry_id: id, + title, + device_id: `d-${id}`, + online: true, + firmware_version: "0.1.0", + integration_version: "0.1.0", + protocol_ok: true, + revision: "r1", + device_revision: "r1", + }); + return {hass, callWS, real, info}; + }; + + it("drops a save result when the screen changed meanwhile", async () => { + const {hass, callWS, real, info} = twoScreens(); + let resolveSave: (v: unknown) => void = () => undefined; + callWS.mockImplementation((msg: {type: string; entry_id?: string}) => { + if (msg.type === "ha_controller/screens") return Promise.resolve({screens: [info("a", "A"), info("b", "B")]}); + if (msg.type === "ha_controller/layout/save") return new Promise((r) => (resolveSave = r)); + return real({...msg, type: msg.type}); + }); + const el = await open(hass); + await addBlockRight(el); + void (el as unknown as {onSave: () => Promise}).onSave(); + await settle(el); + await (el as unknown as {selectScreen: (id: string) => Promise}).selectScreen("b"); + await settle(el); + resolveSave({revision: "r2", pushed: true}); + await settle(el); + expect(saveButton(el).disabled).toBe(true); + expect(one(el, ".notice")).toBeNull(); + await click(el, one(el, "button.revert")!); + expect(blocks(el)).toHaveLength(4); + }); + + it("loads the layout on a later refresh when the first load failed", async () => { + vi.useFakeTimers(); + const {hass, callWS, real} = spied(); + let first = true; + callWS.mockImplementation((msg: {type: string}) => { + if (msg.type === "ha_controller/layout/get" && first) { + first = false; + return Promise.reject({code: "boom", message: "boom"}); + } + return real(msg); + }); + const el = await open(hass); + expect(one(el, "hc-grid")).toBeNull(); + await vi.advanceTimersByTimeAsync(10_000); + await settle(el); + expect(blocks(el)).toHaveLength(4); + }); + + it("selects a screen that appears after an empty first load", async () => { + vi.useFakeTimers(); + const {hass, callWS, real} = spied(); + let empty = true; + callWS.mockImplementation((msg: {type: string}) => + msg.type === "ha_controller/screens" && empty ? Promise.resolve({screens: []}) : real(msg), + ); + const el = await open(hass); + expect(one(el, ".empty")).not.toBeNull(); + empty = false; + await vi.advanceTimersByTimeAsync(10_000); + await settle(el); + expect(blocks(el)).toHaveLength(4); + }); + + it("disables the screen select while dirty", async () => { + const {hass, callWS, real, info} = twoScreens(); + callWS.mockImplementation((msg: {type: string}) => + msg.type === "ha_controller/screens" ? Promise.resolve({screens: [info("a", "A"), info("b", "B")]}) : real(msg), + ); + const el = await open(hass); + const select = () => one(el, "select")!; + expect(select().disabled).toBe(false); + await addBlockRight(el); + expect(select().disabled).toBe(true); + expect(select().title).toBe("Save or revert your changes first."); + await click(el, one(el, "button.revert")!); + expect(select().disabled).toBe(false); + }); + + it("puts the select back on the loaded screen when a switch fails", async () => { + const {hass, callWS, real, info} = twoScreens(); + callWS.mockImplementation((msg: {type: string; entry_id?: string}) => { + if (msg.type === "ha_controller/screens") return Promise.resolve({screens: [info("a", "A"), info("b", "B")]}); + if (msg.type === "ha_controller/layout/get" && msg.entry_id === "b") return Promise.reject({message: "nope"}); + return real(msg); + }); + const el = await open(hass); + const select = one(el, "select")!; + expect(select.value).toBe("a"); + select.value = "b"; + select.dispatchEvent(new Event("change")); + await settle(el); + expect(select.value).toBe("a"); + expect(one(el, ".notice")!.textContent).toContain("nope"); + expect(blocks(el)).toHaveLength(4); + }); + }); +}); diff --git a/custom_components/ha_controller/frontend/test/validate.test.ts b/custom_components/ha_controller/frontend/test/validate.test.ts new file mode 100644 index 0000000..977605d --- /dev/null +++ b/custom_components/ha_controller/frontend/test/validate.test.ts @@ -0,0 +1,22 @@ +import {describe, expect, it} from "vitest"; +import {EMOJI_SET} from "../src/model/emoji"; +import {validateLayout} from "../src/model/validate"; +import {colors, invalidLayouts, validLayouts} from "./fixtures"; + +describe("validateLayout", () => { + it("has fixtures", () => { + expect(Object.keys(validLayouts).length).toBeGreaterThan(0); + expect(Object.keys(invalidLayouts).length).toBeGreaterThan(0); + expect(colors.length).toBeGreaterThan(0); + }); + for (const [name, layout] of Object.entries(validLayouts)) { + it(`accepts valid/${name}`, () => { + expect(validateLayout(layout, EMOJI_SET)).toEqual([]); + }); + } + for (const [name, c] of Object.entries(invalidLayouts)) { + it(`rejects invalid/${name}`, () => { + expect(validateLayout(c.layout, EMOJI_SET)).toEqual([c.expect]); + }); + } +}); diff --git a/custom_components/ha_controller/frontend/tsconfig.json b/custom_components/ha_controller/frontend/tsconfig.json new file mode 100644 index 0000000..9b685a7 --- /dev/null +++ b/custom_components/ha_controller/frontend/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "strict": true, + "target": "ES2022", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "module": "ESNext", + "moduleResolution": "Bundler", + "experimentalDecorators": true, + "useDefineForClassFields": false, + "resolveJsonModule": true, + "noEmit": true, + "types": ["vite/client"] + }, + "include": ["src", "test", "vite.config.ts"] +} diff --git a/custom_components/ha_controller/frontend/vite.config.ts b/custom_components/ha_controller/frontend/vite.config.ts new file mode 100644 index 0000000..b94db59 --- /dev/null +++ b/custom_components/ha_controller/frontend/vite.config.ts @@ -0,0 +1,16 @@ +import {defineConfig} from "vitest/config"; + +export default defineConfig({ + build: { + lib: { + entry: "src/ha-controller-panel.ts", + formats: ["es"], + fileName: () => "ha-controller-panel.js", + }, + outDir: "dist", + emptyOutDir: true, + target: "es2022", + }, + server: {fs: {allow: ["../../.."]}}, + test: {environment: "happy-dom"}, +}); diff --git a/custom_components/ha_controller/layout.py b/custom_components/ha_controller/layout.py new file mode 100644 index 0000000..f7811c2 --- /dev/null +++ b/custom_components/ha_controller/layout.py @@ -0,0 +1,257 @@ +"""Layout model helpers and validation (protocol v1, spec section 6).""" + +from __future__ import annotations + +import json +import re +from collections import deque +from pathlib import Path +from typing import Any, NamedTuple + +from homeassistant.core import HomeAssistant + +from .const import ( + COORD_LIMIT, + DEFAULT_SLEEP_TIMEOUT, + ENTITY_BLOCK_DOMAINS, + FONT_SIZES, + ITEM_KINDS, + MAX_BLOCKS, + MAX_ITEMS, + MAX_NAME_LEN, + MAX_SLEEP_TIMEOUT, + MAX_TEXT_LEN, + MIN_SLEEP_TIMEOUT, +) + +EMOJI_FILE = Path(__file__).parent / "emoji.json" + +_ID_RE = re.compile(r"[a-z][a-z0-9]{0,7}") +_COLOR_RE = re.compile(r"#[0-9A-Fa-f]{6}") +_ENTITY_RE = re.compile(r"[a-z0-9_]+\.[a-z0-9_]+") +_MAX_ATTRIBUTE_LEN = 64 + + +class LayoutError(NamedTuple): + """A validation error; ref is the offending block or item id, or None.""" + + code: str + ref: str | None + + +def empty_layout() -> dict[str, Any]: + """Return the layout of a screen that has no blocks yet.""" + return { + "version": 1, + "start": None, + "settings": {"sleep_timeout": DEFAULT_SLEEP_TIMEOUT}, + "blocks": [], + } + + +def normalize_emoji(text: str) -> str: + """Remove the emoji variation selector U+FE0F.""" + return text.replace("️", "") + + +def load_emoji_file(path: Path) -> frozenset[str]: + """Read the supported emoji list (blocking).""" + return frozenset(json.loads(path.read_text(encoding="utf-8"))) + + +async def async_load_emoji(hass: HomeAssistant) -> frozenset[str]: + """Read the supported emoji list without blocking the event loop.""" + return await hass.async_add_executor_job(load_emoji_file, EMOJI_FILE) + + +def bound_entities(layout: dict[str, Any]) -> dict[str, list[str]]: + """Map entity_id to the ids of the blocks and items bound to it.""" + bound: dict[str, list[str]] = {} + for block in layout["blocks"]: + if block["type"] == "entity": + bound.setdefault(block["entity_id"], []).append(block["id"]) + elif block["type"] == "custom": + for item in block["items"]: + if item["kind"] == "entity": + bound.setdefault(item["entity_id"], []).append(item["id"]) + return bound + + +def _is_int(value: Any) -> bool: + return isinstance(value, int) and not isinstance(value, bool) + + +def _is_id(value: Any) -> bool: + return isinstance(value, str) and _ID_RE.fullmatch(value) is not None + + +def _check_structure(layout: Any) -> bool: + if not isinstance(layout, dict): + return False + version = layout.get("version") + if not _is_int(version) or version != 1: + return False + if not isinstance(layout.get("settings"), dict): + return False + blocks = layout.get("blocks") + if not isinstance(blocks, list) or not all(isinstance(b, dict) for b in blocks): + return False + for block in blocks: + if block.get("type") == "custom": + items = block.get("items") + if not isinstance(items, list) or not all(isinstance(i, dict) for i in items): + return False + return True + + +def _is_entity_id(value: Any) -> bool: + return isinstance(value, str) and _ENTITY_RE.fullmatch(value) is not None + + +def _valid_entity_item(item: dict[str, Any]) -> bool: + entity_id = item.get("entity_id") + if not _is_entity_id(entity_id): + return False + attribute = item.get("attribute") + return attribute is None or ( + isinstance(attribute, str) and 1 <= len(attribute) <= _MAX_ATTRIBUTE_LEN + ) + + +def _valid_entity_block(block: dict[str, Any]) -> bool: + entity_id = block.get("entity_id") + if not _is_entity_id(entity_id): + return False + return entity_id.split(".", 1)[0] in ENTITY_BLOCK_DOMAINS + + +def _check_item( + item: dict[str, Any], + seen_ids: set[str], + emoji: frozenset[str], + errors: list[LayoutError], +) -> None: + item_id = item.get("id") + ref = item_id if isinstance(item_id, str) else None + if not _is_id(item_id): + errors.append(LayoutError("invalid_id", ref)) + if isinstance(item_id, str): + if item_id in seen_ids: + errors.append(LayoutError("duplicate_id", item_id)) + seen_ids.add(item_id) + kind = item.get("kind") + if kind not in ITEM_KINDS: + errors.append(LayoutError("invalid_item", ref)) + font_size = item.get("font_size") + if font_size is not None and font_size not in FONT_SIZES: + errors.append(LayoutError("invalid_font_size", ref)) + if kind == "text": + text = item.get("text") + if not isinstance(text, str) or not 1 <= len(text) <= MAX_TEXT_LEN: + errors.append(LayoutError("invalid_text", ref)) + elif kind == "emoji": + value = item.get("emoji") + if not isinstance(value, str) or normalize_emoji(value) not in emoji: + errors.append(LayoutError("unsupported_emoji", ref)) + elif kind == "entity" and not _valid_entity_item(item): + errors.append(LayoutError("invalid_entity", ref)) + + +def _check_block( + block: dict[str, Any], + seen_ids: set[str], + positions: set[tuple[int, int]], + emoji: frozenset[str], + errors: list[LayoutError], +) -> None: + block_id = block.get("id") + ref = block_id if isinstance(block_id, str) else None + if not _is_id(block_id): + errors.append(LayoutError("invalid_id", ref)) + if isinstance(block_id, str): + if block_id in seen_ids: + errors.append(LayoutError("duplicate_id", block_id)) + seen_ids.add(block_id) + + x, y = block.get("x"), block.get("y") + if not all(_is_int(v) and -COORD_LIMIT <= v <= COORD_LIMIT for v in (x, y)): + errors.append(LayoutError("coordinate_out_of_range", ref)) + else: + if (x, y) in positions: + errors.append(LayoutError("duplicate_position", ref)) + positions.add((x, y)) + + name = block.get("name") + if not isinstance(name, str) or not 1 <= len(name.strip()) <= MAX_NAME_LEN: + errors.append(LayoutError("invalid_name", ref)) + background = block.get("background") + if not isinstance(background, str) or _COLOR_RE.fullmatch(background) is None: + errors.append(LayoutError("invalid_background", ref)) + if block.get("font_size") not in FONT_SIZES: + errors.append(LayoutError("invalid_font_size", ref)) + + block_type = block.get("type") + if block_type == "entity": + if not _valid_entity_block(block): + errors.append(LayoutError("invalid_entity", ref)) + elif block_type == "custom": + items = block["items"] + if len(items) > MAX_ITEMS: + errors.append(LayoutError("too_many_items", ref)) + for item in items: + _check_item(item, seen_ids, emoji, errors) + else: + errors.append(LayoutError("invalid_type", ref)) + + +def _unreachable(layout: dict[str, Any]) -> list[LayoutError]: + if not layout["blocks"]: + return [] + cells = {(b["x"], b["y"]): b["id"] for b in layout["blocks"]} + start = next(b for b in layout["blocks"] if b["id"] == layout["start"]) + reached = {(start["x"], start["y"])} + queue = deque(reached) + while queue: + x, y = queue.popleft() + for cell in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)): + if cell in cells and cell not in reached: + reached.add(cell) + queue.append(cell) + return [ + LayoutError("disconnected", b["id"]) + for b in layout["blocks"] + if (b["x"], b["y"]) not in reached + ] + + +def validate_layout(layout: Any, emoji: frozenset[str]) -> list[LayoutError]: + """Validate a layout; an empty list means it is valid.""" + if not _check_structure(layout): + return [LayoutError("invalid_structure", None)] + + errors: list[LayoutError] = [] + blocks = layout["blocks"] + if len(blocks) > MAX_BLOCKS: + errors.append(LayoutError("too_many_blocks", None)) + timeout = layout["settings"].get("sleep_timeout") + if not _is_int(timeout) or not ( + timeout == 0 or MIN_SLEEP_TIMEOUT <= timeout <= MAX_SLEEP_TIMEOUT + ): + errors.append(LayoutError("invalid_sleep_timeout", None)) + + seen_ids: set[str] = set() + positions: set[tuple[int, int]] = set() + for block in blocks: + _check_block(block, seen_ids, positions, emoji, errors) + + start = layout.get("start") + if start is None: + start_ok = not blocks + else: + start_ok = isinstance(start, str) and any(b.get("id") == start for b in blocks) + if not start_ok: + errors.append(LayoutError("invalid_start", None)) + + if errors: + return errors + return _unreachable(layout) diff --git a/custom_components/ha_controller/manifest.json b/custom_components/ha_controller/manifest.json new file mode 100644 index 0000000..0772eeb --- /dev/null +++ b/custom_components/ha_controller/manifest.json @@ -0,0 +1,14 @@ +{ + "domain": "ha_controller", + "name": "HA Controller", + "after_dependencies": ["esphome"], + "codeowners": ["@pyxel-dev"], + "config_flow": true, + "dependencies": ["frontend", "http", "panel_custom", "websocket_api"], + "documentation": "https://github.com/pyxel-dev/HA-controller/tree/main/docs", + "integration_type": "device", + "iot_class": "local_push", + "issue_tracker": "https://github.com/pyxel-dev/HA-controller/issues", + "requirements": [], + "version": "0.1.0" +} diff --git a/custom_components/ha_controller/panel.py b/custom_components/ha_controller/panel.py new file mode 100644 index 0000000..e291df5 --- /dev/null +++ b/custom_components/ha_controller/panel.py @@ -0,0 +1,45 @@ +"""Sidebar panel registration.""" + +import logging +from pathlib import Path + +from homeassistant.components import frontend, panel_custom +from homeassistant.components.http import StaticPathConfig +from homeassistant.core import HomeAssistant, callback + +from .const import DOMAIN, PANEL_COMPONENT, PANEL_ICON, PANEL_TITLE, PANEL_URL_PATH, STATIC_URL + +_LOGGER = logging.getLogger(__name__) + +BUNDLE = Path(__file__).parent / "frontend" / "dist" / "ha-controller-panel.js" +STATIC_REGISTERED = f"{DOMAIN}_static_registered" + + +async def async_register_panel(hass: HomeAssistant, version: str) -> None: + """Serve the panel bundle and add the sidebar panel.""" + if not hass.data.get(STATIC_REGISTERED): + hass.data[STATIC_REGISTERED] = True + await hass.http.async_register_static_paths( + [StaticPathConfig(f"{STATIC_URL}/ha-controller-panel.js", str(BUNDLE), True)] + ) + if not await hass.async_add_executor_job(BUNDLE.is_file): + _LOGGER.warning("The panel bundle %s is missing; build it with npm", BUNDLE) + + if PANEL_URL_PATH in hass.data.get(frontend.DATA_PANELS, {}): + return + await panel_custom.async_register_panel( + hass, + frontend_url_path=PANEL_URL_PATH, + webcomponent_name=PANEL_COMPONENT, + sidebar_title=PANEL_TITLE, + sidebar_icon=PANEL_ICON, + module_url=f"{STATIC_URL}/ha-controller-panel.js?v={version}", + require_admin=True, + config={}, + ) + + +@callback +def async_unregister_panel(hass: HomeAssistant) -> None: + """Remove the sidebar panel.""" + frontend.async_remove_panel(hass, PANEL_URL_PATH, warn_if_unknown=False) diff --git a/custom_components/ha_controller/services.yaml b/custom_components/ha_controller/services.yaml new file mode 100644 index 0000000..a0e86ff --- /dev/null +++ b/custom_components/ha_controller/services.yaml @@ -0,0 +1,2 @@ +# This integration registers no services of its own. +{} diff --git a/custom_components/ha_controller/states.py b/custom_components/ha_controller/states.py new file mode 100644 index 0000000..fc825bf --- /dev/null +++ b/custom_components/ha_controller/states.py @@ -0,0 +1,127 @@ +"""Build the display-ready state updates the screen receives.""" + +import json +from collections.abc import Collection +from typing import Any + +from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN +from homeassistant.core import HomeAssistant +from homeassistant.helpers import entity_registry as er + +from .const import MAX_TEXT_LEN, STATE_CHUNK_BYTES + +MISSING_TEXT = "—" +_UNUSABLE = (STATE_UNAVAILABLE, STATE_UNKNOWN) + + +def _precision(hass: HomeAssistant, entity_id: str) -> int | None: + entry = er.async_get(hass).async_get(entity_id) + if entry is None: + return None + options = entry.options.get("sensor") or {} + precision = options.get("display_precision") + if precision is None: + precision = options.get("suggested_display_precision") + return precision + + +def format_entity_text(hass: HomeAssistant, entity_id: str, attribute: str | None) -> str: + """Return the display text of an entity item.""" + state = hass.states.get(entity_id) + if state is None or state.state in _UNUSABLE: + return MISSING_TEXT + if attribute: + if attribute not in state.attributes: + return MISSING_TEXT + return str(state.attributes[attribute])[:MAX_TEXT_LEN] + text = state.state + precision = _precision(hass, entity_id) + if precision is not None: + try: + text = f"{float(text):.{int(precision)}f}" + except ValueError: + pass + unit = state.attributes.get("unit_of_measurement") + if unit: + text = f"{text} {unit}" + return text[:MAX_TEXT_LEN] + + +def _light_update(block_id: str, state: Any) -> dict[str, Any]: + modes = state.attributes.get("supported_color_modes") or [] + dimmable = any(mode != "onoff" for mode in modes) + is_on = state.state == "on" + brightness = None + if dimmable: + brightness = round((state.attributes.get("brightness") or 255) * 100 / 255) if is_on else 0 + return {"id": block_id, "available": True, "on": is_on, "brightness": brightness} + + +def _climate_update(hass: HomeAssistant, block_id: str, state: Any) -> dict[str, Any]: + attrs = state.attributes + unit = hass.config.units.temperature_unit + current = attrs.get("current_temperature") + action = attrs.get("hvac_action") or state.state + action = str(action).replace("_", " ") + return { + "id": block_id, + "available": True, + "target": attrs.get("temperature"), + "min": attrs.get("min_temp", 7), + "max": attrs.get("max_temp", 35), + "step": attrs.get("target_temp_step") or (0.5 if unit == "°C" else 1), + "unit": unit, + "current": MISSING_TEXT if current is None else f"{current} {unit}", + "action": action[:1].upper() + action[1:], + } + + +def build_updates( + hass: HomeAssistant, layout: dict[str, Any], entity_ids: Collection[str] | None = None +) -> list[dict[str, Any]]: + """Build the updates for the bound entities, in layout order.""" + wanted = None if entity_ids is None else set(entity_ids) + updates: list[dict[str, Any]] = [] + for block in layout["blocks"]: + if block["type"] == "entity": + entity_id = block["entity_id"] + if wanted is not None and entity_id not in wanted: + continue + state = hass.states.get(entity_id) + if state is None or state.state in _UNUSABLE: + updates.append({"id": block["id"], "available": False}) + elif entity_id.startswith("light."): + updates.append(_light_update(block["id"], state)) + elif entity_id.startswith("climate."): + updates.append(_climate_update(hass, block["id"], state)) + else: + updates.append({"id": block["id"], "available": True}) + elif block["type"] == "custom": + for item in block["items"]: + if item["kind"] != "entity": + continue + if wanted is not None and item["entity_id"] not in wanted: + continue + text = format_entity_text(hass, item["entity_id"], item.get("attribute")) + updates.append({"id": item["id"], "text": text}) + return updates + + +def chunk_updates(updates: list[dict[str, Any]], max_bytes: int = STATE_CHUNK_BYTES) -> list[str]: + """Split updates into JSON arrays of at most max_bytes bytes each.""" + + def encode(items: list[dict[str, Any]]) -> str: + return json.dumps(items, separators=(",", ":"), ensure_ascii=False) + + chunks: list[str] = [] + current: list[dict[str, Any]] = [] + for update in updates: + candidate = [*current, update] + if current and len(encode(candidate).encode("utf-8")) > max_bytes: + chunks.append(encode(current)) + current = [update] + else: + current = candidate + if current: + chunks.append(encode(current)) + return chunks diff --git a/custom_components/ha_controller/store.py b/custom_components/ha_controller/store.py new file mode 100644 index 0000000..47211b4 --- /dev/null +++ b/custom_components/ha_controller/store.py @@ -0,0 +1,31 @@ +"""Persistent storage of one screen's layout.""" + +from typing import Any + +from homeassistant.core import HomeAssistant +from homeassistant.helpers.storage import Store + +from .const import DOMAIN + +STORAGE_VERSION = 1 + + +class LayoutStore: + """Wrap the Home Assistant store that keeps a screen's layout.""" + + def __init__(self, hass: HomeAssistant, entry_id: str) -> None: + self._store: Store[dict[str, Any]] = Store( + hass, STORAGE_VERSION, f"{DOMAIN}.layout.{entry_id}" + ) + + async def async_load(self) -> dict[str, Any] | None: + """Return the stored layout, or None when nothing was saved yet.""" + return await self._store.async_load() + + async def async_save(self, layout: dict[str, Any]) -> None: + """Persist the layout.""" + await self._store.async_save(layout) + + async def async_remove(self) -> None: + """Delete the stored layout.""" + await self._store.async_remove() diff --git a/custom_components/ha_controller/strings.json b/custom_components/ha_controller/strings.json new file mode 100644 index 0000000..ce4e2a8 --- /dev/null +++ b/custom_components/ha_controller/strings.json @@ -0,0 +1,37 @@ +{ + "config": { + "step": { + "user": { + "title": "Add an HA Controller screen", + "description": "Pick the screen. It must already be added to Home Assistant with the ESPHome integration.", + "data": { + "device_id": "Screen" + } + } + }, + "error": { + "not_ha_controller": "This device is not an HA Controller screen." + }, + "abort": { + "already_configured": "This screen is already set up." + } + }, + "entity": { + "update": { + "firmware": { + "name": "HA Controller firmware" + } + } + }, + "options": { + "step": { + "init": { + "title": "HA Controller options", + "description": "Installs the firmware that matches this integration's version whenever the screen reports a different one.", + "data": { + "auto_update": "Update the screen firmware automatically" + } + } + } + } +} diff --git a/custom_components/ha_controller/tests/__init__.py b/custom_components/ha_controller/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/custom_components/ha_controller/tests/conftest.py b/custom_components/ha_controller/tests/conftest.py new file mode 100644 index 0000000..e1e1bb1 --- /dev/null +++ b/custom_components/ha_controller/tests/conftest.py @@ -0,0 +1,8 @@ +"""Shared fixtures for the HA Controller tests.""" + +import pytest + + +@pytest.fixture(autouse=True) +def auto_enable_custom_integrations(enable_custom_integrations): + """Let Home Assistant load the integration from custom_components.""" diff --git a/custom_components/ha_controller/tests/helpers.py b/custom_components/ha_controller/tests/helpers.py new file mode 100644 index 0000000..c8b487a --- /dev/null +++ b/custom_components/ha_controller/tests/helpers.py @@ -0,0 +1,63 @@ +"""Helpers shared by the HA Controller tests.""" + +import json +from pathlib import Path +from typing import Any + +from homeassistant.core import HomeAssistant +from homeassistant.helpers import device_registry as dr +from pytest_homeassistant_custom_component.common import MockConfigEntry + +from custom_components.ha_controller.const import CONF_DEVICE_ID, DOMAIN, MANUFACTURER, MODEL + +NODE = "ha-controller-aabbcc" +FIXTURES = Path(__file__).parents[3] / "docs" / "protocol" / "fixtures" +VERSION = json.loads((Path(__file__).resolve().parents[1] / "manifest.json").read_text())["version"] + + +async def register_screen( + hass: HomeAssistant, + *, + name: str = "HA Controller", + manufacturer: str = MANUFACTURER, + model: str = MODEL, + mac: str = "aa:bb:cc:dd:ee:ff", +) -> dr.DeviceEntry: + """Add an ESPHome config entry and a screen device that belongs to it.""" + esphome_entry = MockConfigEntry(domain="esphome", title=name) + esphome_entry.add_to_hass(hass) + return dr.async_get(hass).async_get_or_create( + config_entry_id=esphome_entry.entry_id, + connections={(dr.CONNECTION_NETWORK_MAC, mac)}, + name=name, + manufacturer=manufacturer, + model=model, + ) + + +async def setup_screen(hass: HomeAssistant, device: dr.DeviceEntry) -> MockConfigEntry: + """Add and set up the ha_controller entry for a screen device.""" + entry = MockConfigEntry(domain=DOMAIN, data={CONF_DEVICE_ID: device.id}, unique_id=device.id) + entry.add_to_hass(hass) + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + return entry + + +def hello(device: dr.DeviceEntry, **overrides: Any) -> dict[str, Any]: + """Return a default hello event payload for the screen.""" + data: dict[str, Any] = { + "device_id": device.id, + "node": NODE, + "version": VERSION, + "protocol": "1", + "revision": "none", + "reason": "connected", + } + data.update(overrides) + return data + + +def load_fixture(*parts: str) -> Any: + """Read a shared protocol fixture from docs/protocol/fixtures.""" + return json.loads(FIXTURES.joinpath(*parts).read_text(encoding="utf-8")) diff --git a/custom_components/ha_controller/tests/test_compiler.py b/custom_components/ha_controller/tests/test_compiler.py new file mode 100644 index 0000000..2d19d14 --- /dev/null +++ b/custom_components/ha_controller/tests/test_compiler.py @@ -0,0 +1,70 @@ +"""Tests for the layout compiler against the shared protocol fixtures.""" + +from typing import Any + +import pytest + +from custom_components.ha_controller.compiler import ( + compile_layout, + encode_payload, + payload_revision, +) +from custom_components.ha_controller.const import MAX_PAYLOAD_BYTES + +from .helpers import FIXTURES, load_fixture + +VALID_PAYLOADS = sorted((FIXTURES / "payloads" / "valid").glob("*.json")) + + +def load_layout(stem: str) -> dict[str, Any]: + return load_fixture("layouts", "valid", f"{stem}.json") + + +@pytest.mark.parametrize("path", VALID_PAYLOADS, ids=lambda p: p.stem) +def test_golden_payloads(path): + case = load_fixture("payloads", "valid", path.name) + assert compile_layout(load_layout(case["layout"])) == case["payload"] + + +def test_revision_ignores_rev_key(): + payload = {"v": 1, "rev": "zzz", "start": None, "sleep": 20, "blocks": []} + assert payload_revision(payload) == "c4aad3fa" + + +def test_names_are_trimmed(): + layout = load_layout("single") + layout["blocks"][0]["name"] = f" {layout['blocks'][0]['name']}\t" + assert ( + compile_layout(layout)["blocks"][0]["name"] + == compile_layout(load_layout("single"))["blocks"][0]["name"].strip() + ) + + +def test_encode_payload_is_compact_utf8(): + text = encode_payload(compile_layout(load_layout("reference"))) + assert ", " not in text and ": " not in text and "👋" in text + + +def test_huge_layout_exceeds_payload_limit(): + huge = { + "version": 1, + "start": "b0", + "settings": {"sleep_timeout": 20}, + "blocks": [ + { + "id": f"b{n}", + "x": n, + "y": 0, + "name": "é" * 32, + "background": "#112233", + "font_size": "m", + "type": "custom", + "items": [ + {"id": f"i{n}_{k}", "kind": "text", "text": "é" * 64, "font_size": None} + for k in range(6) + ], + } + for n in range(32) + ], + } + assert len(encode_payload(compile_layout(huge)).encode()) > MAX_PAYLOAD_BYTES diff --git a/custom_components/ha_controller/tests/test_config_flow.py b/custom_components/ha_controller/tests/test_config_flow.py new file mode 100644 index 0000000..ad4a82f --- /dev/null +++ b/custom_components/ha_controller/tests/test_config_flow.py @@ -0,0 +1,63 @@ +"""Tests for the HA Controller config flow.""" + +import json +from pathlib import Path + +from homeassistant.config_entries import ConfigEntryState +from homeassistant.data_entry_flow import FlowResultType + +from custom_components.ha_controller.const import DOMAIN + +from .helpers import register_screen, setup_screen + +COMPONENT = Path(__file__).parents[1] + + +async def start_flow_and_submit(hass, user_input): + result = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"}) + return await hass.config_entries.flow.async_configure(result["flow_id"], user_input) + + +async def test_user_step_shows_device_selector(hass): + result = await hass.config_entries.flow.async_init(DOMAIN, context={"source": "user"}) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "user" + assert result["errors"] == {} + + +async def test_user_step_creates_entry(hass): + device = await register_screen(hass) + result = await start_flow_and_submit(hass, {"device_id": device.id}) + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["title"] == "HA Controller" and result["data"] == {"device_id": device.id} + assert result["result"].unique_id == device.id + + +async def test_user_step_rejects_other_device(hass): + device = await register_screen(hass, model="other") + result = await start_flow_and_submit(hass, {"device_id": device.id}) + assert result["type"] is FlowResultType.FORM + assert result["errors"] == {"base": "not_ha_controller"} + + +async def test_user_step_aborts_when_already_configured(hass): + device = await register_screen(hass) + await setup_screen(hass, device) + result = await start_flow_and_submit(hass, {"device_id": device.id}) + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_configured" + + +async def test_setup_and_unload_entry(hass): + device = await register_screen(hass) + entry = await setup_screen(hass, device) + assert entry.state is ConfigEntryState.LOADED + await hass.config_entries.async_unload(entry.entry_id) + await hass.async_block_till_done() + assert entry.state is ConfigEntryState.NOT_LOADED + + +def test_strings_match_english_translation(): + strings = json.loads((COMPONENT / "strings.json").read_text(encoding="utf-8")) + english = json.loads((COMPONENT / "translations" / "en.json").read_text(encoding="utf-8")) + assert strings == english diff --git a/custom_components/ha_controller/tests/test_controller.py b/custom_components/ha_controller/tests/test_controller.py new file mode 100644 index 0000000..07f0cea --- /dev/null +++ b/custom_components/ha_controller/tests/test_controller.py @@ -0,0 +1,346 @@ +"""Tests for the layout store and the screen sync engine.""" + +import json +from datetime import timedelta + +import voluptuous as vol +from homeassistant.exceptions import HomeAssistantError +from pytest_homeassistant_custom_component.common import ( + MockConfigEntry, + async_fire_time_changed, + async_mock_service, +) + +from custom_components.ha_controller.const import DOMAIN +from custom_components.ha_controller.controller import InvalidLayout +from custom_components.ha_controller.layout import LayoutError + +from .helpers import NODE, VERSION, hello, register_screen, setup_screen +from .test_compiler import load_layout + +REFERENCE_REV = "90538742" + + +def mock_screen(hass): + layouts = async_mock_service(hass, "esphome", "ha_controller_aabbcc_set_layout") + states = async_mock_service(hass, "esphome", "ha_controller_aabbcc_set_states") + return layouts, states + + +async def start(hass, *, saved=True): + """Set up a screen, optionally with the reference layout saved (offline).""" + device = await register_screen(hass) + entry = await setup_screen(hass, device) + if saved: + await entry.runtime_data.async_save_layout(load_layout("reference")) + return device, entry, entry.runtime_data + + +async def send_hello(hass, device, **overrides): + hass.bus.async_fire("esphome.ha_controller_hello", hello(device, **overrides)) + await hass.async_block_till_done() + + +async def test_hello_with_unknown_revision_pushes_layout_and_states(hass): + layouts, states = mock_screen(hass) + device, _, _ = await start(hass) + await send_hello(hass, device, revision="none", reason="heartbeat") + assert len(layouts) == 1 + assert json.loads(layouts[0].data["layout"])["rev"] == REFERENCE_REV + assert len(states) >= 1 + + +async def test_hello_connected_with_current_revision_pushes_states_only(hass): + layouts, states = mock_screen(hass) + device, _, _ = await start(hass) + await send_hello(hass, device, revision=REFERENCE_REV, reason="connected") + assert layouts == [] + assert len(states) >= 1 + + +async def test_heartbeat_with_current_revision_pushes_nothing(hass): + layouts, states = mock_screen(hass) + device, _, _ = await start(hass) + await send_hello(hass, device, revision=REFERENCE_REV, reason="heartbeat") # first hello + states.clear() + await send_hello(hass, device, revision=REFERENCE_REV, reason="heartbeat") + assert layouts == [] + assert states == [] + + +async def test_first_hello_after_start_pushes_states(hass): + layouts, states = mock_screen(hass) + device, _, _ = await start(hass) + await send_hello(hass, device, revision=REFERENCE_REV, reason="heartbeat") + assert layouts == [] + assert len(states) == 1 + await send_hello(hass, device, revision=REFERENCE_REV, reason="heartbeat") + assert layouts == [] + assert len(states) == 1 + + +async def test_stale_revision_is_retried_at_most_every_300s(hass, freezer): + layouts, _ = mock_screen(hass) + device, _, _ = await start(hass) + await send_hello(hass, device, reason="heartbeat") + freezer.tick(timedelta(seconds=299)) + await send_hello(hass, device, reason="heartbeat") + assert len(layouts) == 1 + freezer.tick(timedelta(seconds=2)) + await send_hello(hass, device, reason="heartbeat") + assert len(layouts) == 2 + await send_hello(hass, device, reason="connected") + assert len(layouts) == 3 + + +async def test_hello_with_other_protocol_pushes_nothing(hass): + layouts, states = mock_screen(hass) + device, entry, controller = await start(hass) + await send_hello(hass, device, protocol="2", reason="connected") + assert layouts == [] + assert states == [] + assert controller.status()["protocol_ok"] is False + + +async def test_hello_from_other_device_is_ignored(hass): + layouts, _ = mock_screen(hass) + device, _, controller = await start(hass) + other = await register_screen(hass, name="Other", mac="11:22:33:44:55:66") + await send_hello(hass, other) + assert layouts == [] + assert controller.device.last_seen is None + assert controller.status()["protocol_ok"] is None + + +async def test_state_changes_are_coalesced(hass, freezer): + _, states = mock_screen(hass) + device, _, _ = await start(hass) + await send_hello(hass, device, revision=REFERENCE_REV, reason="heartbeat") + states.clear() + hass.states.async_set("light.kitchen", "on", {"brightness": 255}) + freezer.tick(timedelta(milliseconds=100)) + hass.states.async_set("light.living_room", "on", {"brightness": 255}) + await hass.async_block_till_done() + assert states == [] + freezer.tick(timedelta(milliseconds=300)) + async_fire_time_changed(hass) + await hass.async_block_till_done() + assert len(states) == 1 + ids = {u["id"] for u in json.loads(states[0].data["states"])} + assert ids == {"b1", "b2"} + + +async def test_state_change_not_pushed_when_offline(hass, freezer): + _, states = mock_screen(hass) + device, _, _ = await start(hass) + await send_hello(hass, device, revision=REFERENCE_REV, reason="heartbeat") + states.clear() + freezer.tick(timedelta(seconds=151)) + hass.states.async_set("light.kitchen", "on", {"brightness": 255}) + freezer.tick(timedelta(seconds=1)) + async_fire_time_changed(hass) + await hass.async_block_till_done() + assert states == [] + + +async def test_save_layout_pushes_when_online(hass): + layouts, states = mock_screen(hass) + device, entry, controller = await start(hass, saved=False) + await send_hello(hass, device, revision="none", reason="heartbeat") + assert (await controller.async_save_layout(load_layout("reference"))) == ( + REFERENCE_REV, + True, + ) + assert json.loads(layouts[-1].data["layout"])["rev"] == REFERENCE_REV + assert len(states) >= 1 + + +async def test_save_layout_offline_returns_not_pushed(hass, hass_storage): + layouts, _ = mock_screen(hass) + _, entry, controller = await start(hass, saved=False) + result = await controller.async_save_layout(load_layout("reference")) + assert result == (REFERENCE_REV, False) + assert layouts == [] + key = f"{DOMAIN}.layout.{entry.entry_id}" + assert hass_storage[key]["data"] == load_layout("reference") + + +async def test_save_invalid_layout_raises(hass): + _, _, controller = await start(hass, saved=False) + layout = load_layout("reference") + layout["blocks"][1]["name"] = "" + try: + await controller.async_save_layout(layout) + except InvalidLayout as err: + assert err.errors == [LayoutError("invalid_name", "b2")] + else: + raise AssertionError("InvalidLayout not raised") + assert controller.revision != REFERENCE_REV + + +async def test_save_too_large_layout_raises_payload_too_large(hass): + _, _, controller = await start(hass, saved=False) + text = "漢" * 64 + layout = { + "version": 1, + "start": "b0", + "settings": {"sleep_timeout": 20}, + "blocks": [ + { + "id": f"b{n}", + "x": n, + "y": 0, + "name": "Big", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [ + {"id": f"i{n}x{k}", "kind": "text", "text": text, "font_size": None} + for k in range(6) + ], + } + for n in range(32) + ], + } + try: + await controller.async_save_layout(layout) + except InvalidLayout as err: + assert err.errors == [LayoutError("payload_too_large", None)] + else: + raise AssertionError("InvalidLayout not raised") + + +async def test_push_failure_is_logged_not_raised(hass, caplog): + async def fail(call): + raise HomeAssistantError("boom") + + hass.services.async_register("esphome", "ha_controller_aabbcc_set_layout", fail) + device, _, controller = await start(hass) + await send_hello(hass, device, reason="heartbeat") + assert await controller.async_push_layout() is False + assert "ha_controller_aabbcc_set_layout" in caplog.text + assert "boom" in caplog.text + + +async def test_call_device_without_hello_returns_false(hass): + layouts, _ = mock_screen(hass) + _, _, controller = await start(hass) + assert await controller.async_call_device("set_layout", {"layout": "{}"}) is False + assert layouts == [] + + +async def test_invalid_stored_layout_falls_back_to_empty(hass, hass_storage, caplog): + device = await register_screen(hass) + entry = MockConfigEntry(domain=DOMAIN, data={"device_id": device.id}, unique_id=device.id) + entry.add_to_hass(hass) + key = f"{DOMAIN}.layout.{entry.entry_id}" + stored = {"version": 1, "start": "zz", "settings": {"sleep_timeout": 20}, "blocks": "bad"} + hass_storage[key] = {"version": 1, "minor_version": 1, "key": key, "data": stored} + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + controller = entry.runtime_data + assert controller.layout["blocks"] == [] + assert "Ignoring invalid stored layout" in caplog.text + assert hass_storage[key]["data"] == stored + + +async def test_layout_survives_reload(hass): + _, entry, _ = await start(hass) + assert await hass.config_entries.async_reload(entry.entry_id) + await hass.async_block_till_done() + assert entry.runtime_data.layout == load_layout("reference") + assert entry.runtime_data.revision == REFERENCE_REV + + +async def test_remove_entry_deletes_storage(hass, hass_storage): + _, entry, _ = await start(hass) + key = f"{DOMAIN}.layout.{entry.entry_id}" + assert key in hass_storage + await hass.config_entries.async_remove(entry.entry_id) + await hass.async_block_till_done() + assert key not in hass_storage + + +async def test_listeners_are_notified_on_hello(hass): + mock_screen(hass) + device, _, controller = await start(hass) + calls = [] + remove = controller.async_add_listener(lambda: calls.append(1)) + await send_hello(hass, device, reason="heartbeat") + assert calls == [1] + remove() + await send_hello(hass, device, reason="heartbeat") + assert calls == [1] + + +async def test_status_reports_device(hass): + mock_screen(hass) + device, entry, controller = await start(hass) + await send_hello(hass, device, revision=REFERENCE_REV, reason="heartbeat") + assert controller.status() == { + "entry_id": entry.entry_id, + "title": entry.title, + "device_id": device.id, + "online": True, + "firmware_version": VERSION, + "integration_version": VERSION, + "protocol_ok": True, + "revision": REFERENCE_REV, + "device_revision": REFERENCE_REV, + } + assert controller.device.node == NODE + + +async def test_service_schema_error_is_logged_not_raised(hass, caplog): + hass.services.async_register( + "esphome", + "ha_controller_aabbcc_set_layout", + lambda call: None, + schema=vol.Schema({vol.Required("other"): str}), + ) + device, _, controller = await start(hass, saved=False) + await send_hello(hass, device, revision="none", reason="heartbeat") + result = await controller.async_save_layout(load_layout("reference")) + assert result == (REFERENCE_REV, False) + assert "ha_controller_aabbcc_set_layout" in caplog.text + + +def test_invalid_layout_message_format(): + assert str(InvalidLayout([LayoutError("payload_too_large", None)])) == "payload_too_large@" + errors = [LayoutError("invalid_name", "b2"), LayoutError("disconnected", "b4")] + assert str(InvalidLayout(errors)) == "invalid_name@b2, disconnected@b4" + + +async def test_new_revision_is_pushed_despite_recent_push(hass, freezer): + layouts, _ = mock_screen(hass) + device, _, controller = await start(hass, saved=False) + layout_a = load_layout("reference") + await controller.async_save_layout(layout_a) + await send_hello(hass, device, revision="none", reason="heartbeat") + assert len(layouts) == 1 + freezer.tick(timedelta(seconds=151)) + layout_b = json.loads(json.dumps(layout_a)) + layout_b["blocks"] = layout_b["blocks"][:-1] + _, pushed = await controller.async_save_layout(layout_b) + assert pushed is False + assert controller.revision != REFERENCE_REV + assert len(layouts) == 1 + freezer.tick(timedelta(seconds=1)) + await send_hello(hass, device, revision=REFERENCE_REV, reason="heartbeat") + assert len(layouts) == 2 + assert json.loads(layouts[1].data["layout"])["rev"] == controller.revision + + +async def test_stop_cancels_pending_flush(hass, freezer): + _, states = mock_screen(hass) + device, entry, _ = await start(hass) + await send_hello(hass, device, revision=REFERENCE_REV, reason="heartbeat") + states.clear() + hass.states.async_set("light.kitchen", "on", {"brightness": 255}) + await hass.async_block_till_done() + await hass.config_entries.async_unload(entry.entry_id) + await hass.async_block_till_done() + freezer.tick(timedelta(seconds=1)) + async_fire_time_changed(hass) + await hass.async_block_till_done() + assert states == [] diff --git a/custom_components/ha_controller/tests/test_controls.py b/custom_components/ha_controller/tests/test_controls.py new file mode 100644 index 0000000..e827f8f --- /dev/null +++ b/custom_components/ha_controller/tests/test_controls.py @@ -0,0 +1,82 @@ +"""Tests for the control event mapping.""" + +import logging + +import pytest +from homeassistant.exceptions import HomeAssistantError +from pytest_homeassistant_custom_component.common import async_mock_service + +from custom_components.ha_controller.const import EVENT_CONTROL +from custom_components.ha_controller.controls import resolve_control + +from .helpers import FIXTURES, load_fixture, register_screen, setup_screen +from .test_compiler import load_layout + +CONTROL_FIXTURES = sorted((FIXTURES / "controls").glob("*.json")) + + +@pytest.mark.parametrize("path", CONTROL_FIXTURES, ids=lambda p: p.stem) +async def test_control_fixtures(hass, path): + case = load_fixture("controls", path.name) + for entity_id, s in case["hass_states"].items(): + hass.states.async_set(entity_id, s["state"], s["attributes"]) + call = resolve_control(load_layout(case["layout"]), hass, case["event"]) + assert (call and call._asdict()) == case["expect_call"] + + +async def test_climate_defaults_without_state(hass): + event = {"block": "b4", "item": "", "op": "set", "value": "50"} + call = resolve_control(load_layout("reference"), hass, event) + assert call.data["temperature"] == 35 + event["value"] = "1" + assert resolve_control(load_layout("reference"), hass, event).data["temperature"] == 7 + + +async def test_non_finite_value_is_ignored(hass): + event = {"block": "b2", "item": "", "op": "set", "value": "nan"} + assert resolve_control(load_layout("reference"), hass, event) is None + event["value"] = "inf" + assert resolve_control(load_layout("reference"), hass, event) is None + + +async def start(hass): + device = await register_screen(hass) + entry = await setup_screen(hass, device) + await entry.runtime_data.async_save_layout(load_layout("reference")) + return device + + +def control(device_id, **overrides): + data = {"device_id": device_id, "block": "b1", "item": "", "op": "toggle", "value": "0"} + data.update(overrides) + return data + + +async def test_control_event_calls_service(hass): + calls = async_mock_service(hass, "light", "toggle") + device = await start(hass) + hass.bus.async_fire(EVENT_CONTROL, control(device.id)) + await hass.async_block_till_done() + assert len(calls) == 1 + assert calls[0].data == {"entity_id": "light.kitchen"} + + +async def test_control_from_other_device_is_ignored(hass): + calls = async_mock_service(hass, "light", "toggle") + await start(hass) + hass.bus.async_fire(EVENT_CONTROL, control("other-device")) + await hass.async_block_till_done() + assert calls == [] + + +async def test_service_error_is_swallowed(hass, caplog): + def fail(call): + raise HomeAssistantError("boom") + + hass.services.async_register("light", "turn_on", fail) + device = await start(hass) + with caplog.at_level(logging.WARNING): + hass.bus.async_fire(EVENT_CONTROL, control(device.id, block="b2", op="set", value="50")) + await hass.async_block_till_done() + assert "light.turn_on" in caplog.text + assert "boom" in caplog.text diff --git a/custom_components/ha_controller/tests/test_layout.py b/custom_components/ha_controller/tests/test_layout.py new file mode 100644 index 0000000..2ece638 --- /dev/null +++ b/custom_components/ha_controller/tests/test_layout.py @@ -0,0 +1,138 @@ +"""Tests for layout validation against the shared protocol fixtures.""" + +import copy +import json +from pathlib import Path +from typing import Any + +import pytest + +from custom_components.ha_controller.const import DEFAULT_SLEEP_TIMEOUT +from custom_components.ha_controller.layout import ( + LayoutError, + async_load_emoji, + bound_entities, + empty_layout, + load_emoji_file, + normalize_emoji, + validate_layout, +) + +from .helpers import FIXTURES, load_fixture + +EMOJI_FILE = Path(__file__).parents[1] / "emoji.json" +EMOJI = load_emoji_file(EMOJI_FILE) +VALID_LAYOUTS = sorted((FIXTURES / "layouts" / "valid").glob("*.json")) +INVALID_LAYOUTS = sorted((FIXTURES / "layouts" / "invalid").glob("*.json")) + + +def reference() -> dict[str, Any]: + return copy.deepcopy(load_fixture("layouts", "valid", "reference.json")) + + +SPEC_ERROR_CODES = frozenset( + { + "invalid_structure", + "too_many_blocks", + "invalid_sleep_timeout", + "invalid_id", + "duplicate_id", + "coordinate_out_of_range", + "duplicate_position", + "invalid_start", + "disconnected", + "invalid_name", + "invalid_background", + "invalid_font_size", + "invalid_type", + "invalid_entity", + "too_many_items", + "invalid_item", + "invalid_text", + "unsupported_emoji", + } +) + + +def test_fixture_sets_are_complete() -> None: + assert VALID_LAYOUTS + assert INVALID_LAYOUTS + covered = { + json.loads(path.read_text(encoding="utf-8"))["expect"]["code"] for path in INVALID_LAYOUTS + } + missing = sorted(SPEC_ERROR_CODES - covered) + assert not missing, f"no invalid fixture for error codes: {missing}" + + +@pytest.mark.parametrize("path", VALID_LAYOUTS, ids=lambda p: p.stem) +def test_valid_fixtures(path: Path) -> None: + assert validate_layout(json.loads(path.read_text(encoding="utf-8")), EMOJI) == [] + + +@pytest.mark.parametrize("path", INVALID_LAYOUTS, ids=lambda p: p.stem) +def test_invalid_fixtures(path: Path) -> None: + case = json.loads(path.read_text(encoding="utf-8")) + expect = case["expect"] + assert validate_layout(case["layout"], EMOJI) == [LayoutError(expect["code"], expect["ref"])] + + +def test_connectivity_is_skipped_when_fields_are_invalid() -> None: + layout = reference() + layout["blocks"][0]["name"] = "" + layout["blocks"][1]["y"] = -5 # would be disconnected + assert validate_layout(layout, EMOJI) == [LayoutError("invalid_name", "b1")] + + +def test_normalize_emoji_strips_variation_selector() -> None: + assert normalize_emoji("❄️") == "❄" + + +def test_bound_entities_reference() -> None: + assert bound_entities(reference()) == { + "light.kitchen": ["b1"], + "light.living_room": ["b2"], + "sensor.outdoor_temperature": ["i3"], + "climate.bedroom": ["b4"], + } + + +def test_bool_is_not_a_coordinate() -> None: + layout = reference() + layout["blocks"][0]["x"] = True + assert LayoutError("coordinate_out_of_range", "b1") in validate_layout(layout, EMOJI) + + +@pytest.mark.parametrize( + ("value", "ok"), + [(0, True), (5, True), (3600, True), (4, False), (3601, False), (True, False), ("20", False)], +) +def test_sleep_timeout_bounds(value: Any, ok: bool) -> None: + layout = reference() + layout["settings"]["sleep_timeout"] = value + expected = [] if ok else [LayoutError("invalid_sleep_timeout", None)] + assert validate_layout(layout, EMOJI) == expected + + +def test_non_dict_layout_is_invalid_structure() -> None: + assert validate_layout([], EMOJI) == [LayoutError("invalid_structure", None)] + + +def test_empty_layout_is_valid() -> None: + layout = empty_layout() + assert layout == { + "version": 1, + "start": None, + "settings": {"sleep_timeout": DEFAULT_SLEEP_TIMEOUT}, + "blocks": [], + } + assert validate_layout(layout, EMOJI) == [] + + +def test_load_emoji_file() -> None: + with EMOJI_FILE.open(encoding="utf-8") as handle: + assert EMOJI == frozenset(json.load(handle)) + assert "💡" in EMOJI + + +async def test_async_load_emoji(hass) -> None: + assert await async_load_emoji(hass) == EMOJI diff --git a/custom_components/ha_controller/tests/test_panel.py b/custom_components/ha_controller/tests/test_panel.py new file mode 100644 index 0000000..1379b8a --- /dev/null +++ b/custom_components/ha_controller/tests/test_panel.py @@ -0,0 +1,73 @@ +"""Tests for the sidebar panel registration.""" + +from pathlib import Path +from unittest.mock import AsyncMock, patch + +from homeassistant.components import frontend +from homeassistant.core import HomeAssistant +from homeassistant.setup import async_setup_component + +from custom_components.ha_controller.const import PANEL_URL_PATH + +from .helpers import register_screen, setup_screen + + +async def test_panel_registered_on_setup(hass: HomeAssistant) -> None: + """The panel is registered for admins with the first entry.""" + await setup_screen(hass, await register_screen(hass)) + + panel = hass.data[frontend.DATA_PANELS][PANEL_URL_PATH] + assert panel.require_admin is True + assert panel.sidebar_title == "HA Controller" + assert panel.sidebar_icon == "mdi:remote" + + +async def test_panel_kept_while_another_entry_is_loaded(hass: HomeAssistant) -> None: + """Unloading one of two entries keeps the panel.""" + first = await setup_screen(hass, await register_screen(hass, mac="aa:bb:cc:dd:ee:01")) + await setup_screen(hass, await register_screen(hass, mac="aa:bb:cc:dd:ee:02")) + + assert await hass.config_entries.async_unload(first.entry_id) + await hass.async_block_till_done() + + assert PANEL_URL_PATH in hass.data[frontend.DATA_PANELS] + + +async def test_panel_removed_when_last_entry_unloaded(hass: HomeAssistant) -> None: + """Unloading the last entry removes the panel.""" + entry = await setup_screen(hass, await register_screen(hass)) + + assert await hass.config_entries.async_unload(entry.entry_id) + await hass.async_block_till_done() + + assert PANEL_URL_PATH not in hass.data[frontend.DATA_PANELS] + + +async def test_static_path_registered_once(hass: HomeAssistant) -> None: + """The bundle route is registered once for several entries.""" + assert await async_setup_component(hass, "http", {}) + with patch.object(hass.http, "async_register_static_paths", AsyncMock()) as register: + await setup_screen(hass, await register_screen(hass, mac="aa:bb:cc:dd:ee:01")) + await setup_screen(hass, await register_screen(hass, mac="aa:bb:cc:dd:ee:02")) + + ours = [ + config + for call in register.await_args_list + for config in call.args[0] + if config.url_path.startswith("/ha_controller_static") + ] + assert len(ours) == 1 + assert ours[0].url_path == "/ha_controller_static/ha-controller-panel.js" + assert ours[0].path.endswith("frontend/dist/ha-controller-panel.js") + assert ours[0].cache_headers is True + + +async def test_missing_bundle_warns(hass: HomeAssistant, caplog) -> None: + """A missing bundle only logs a warning.""" + with patch( + "custom_components.ha_controller.panel.BUNDLE", Path("/nonexistent/ha-controller-panel.js") + ): + entry = await setup_screen(hass, await register_screen(hass)) + + assert entry.state.name == "LOADED" + assert "bundle" in caplog.text diff --git a/custom_components/ha_controller/tests/test_states.py b/custom_components/ha_controller/tests/test_states.py new file mode 100644 index 0000000..17d6a92 --- /dev/null +++ b/custom_components/ha_controller/tests/test_states.py @@ -0,0 +1,101 @@ +"""Tests for the screen state builders.""" + +import json + +import pytest +from homeassistant.helpers import entity_registry as er +from homeassistant.util.unit_system import METRIC_SYSTEM, US_CUSTOMARY_SYSTEM + +from custom_components.ha_controller.const import STATE_CHUNK_BYTES +from custom_components.ha_controller.states import ( + build_updates, + chunk_updates, + format_entity_text, +) + +from .helpers import FIXTURES, load_fixture +from .test_compiler import load_layout + +STATE_FIXTURES = sorted((FIXTURES / "states").glob("*.json")) + + +@pytest.mark.parametrize("path", STATE_FIXTURES, ids=lambda p: p.stem) +async def test_state_fixtures(hass, path): + case = load_fixture("states", path.name) + hass.config.units = METRIC_SYSTEM + registry = er.async_get(hass) + for entity_id, options in case.get("registry_options", {}).items(): + domain, object_id = entity_id.split(".", 1) + entry = registry.async_get_or_create( + domain, "test", object_id, suggested_object_id=object_id + ) + assert entry.entity_id == entity_id + for option_domain, value in options.items(): + registry.async_update_entity_options(entity_id, option_domain, value) + # Set states after registering: the registry avoids ids that already have a state. + for entity_id, s in case["hass_states"].items(): + hass.states.async_set(entity_id, s["state"], s["attributes"]) + updates = build_updates(hass, load_layout(case["layout"]), case["entity_ids"]) + assert updates == case["updates"] + + +async def test_entity_text_truncated_to_64(hass): + hass.states.async_set("sensor.long", "x" * 100) + assert len(format_entity_text(hass, "sensor.long", None)) == 64 + + +async def test_entity_text_uses_attribute(hass): + hass.states.async_set("sensor.phone", "ok", {"battery": 80, "unit_of_measurement": "%"}) + assert format_entity_text(hass, "sensor.phone", "battery") == "80" + assert format_entity_text(hass, "sensor.phone", "missing") == "—" + + +def test_chunk_updates_splits_by_size(): + updates = [{"id": f"i{n}", "text": "x" * 40} for n in range(300)] + chunks = chunk_updates(updates, STATE_CHUNK_BYTES) + assert len(chunks) > 1 + assert all(len(c.encode("utf-8")) <= STATE_CHUNK_BYTES for c in chunks) + assert [u for c in chunks for u in json.loads(c)] == updates + + +def test_chunk_updates_keeps_oversize_update_alone(): + big = {"id": "i1", "text": "x" * 200} + small = {"id": "i2", "text": "y"} + chunks = chunk_updates([small, big, small], 100) + assert [json.loads(c) for c in chunks] == [[small], [big], [small]] + + +async def test_climate_fahrenheit_defaults(hass): + hass.config.units = US_CUSTOMARY_SYSTEM + hass.states.async_set( + "climate.bedroom", + "heat", + {"temperature": 70, "current_temperature": 68, "min_temp": 45, "max_temp": 95}, + ) + updates = build_updates(hass, load_layout("reference"), ["climate.bedroom"]) + assert updates == [ + { + "id": "b4", + "available": True, + "target": 70, + "min": 45, + "max": 95, + "step": 1, + "unit": "°F", + "current": "68 °F", + "action": "Heat", + } + ] + + +async def test_entity_text_uses_suggested_precision(hass): + registry = er.async_get(hass) + registry.async_get_or_create( + "sensor", "test", "outdoor_temperature", suggested_object_id="outdoor_temperature" + ) + registry.async_update_entity_options( + "sensor.outdoor_temperature", "sensor", {"suggested_display_precision": 2} + ) + hass.states.async_set("sensor.outdoor_temperature", "3.14159", {"unit_of_measurement": "kW"}) + updates = build_updates(hass, load_layout("reference"), ["sensor.outdoor_temperature"]) + assert [u for u in updates if u["id"] == "i3"] == [{"id": "i3", "text": "3.14 kW"}] diff --git a/custom_components/ha_controller/tests/test_update.py b/custom_components/ha_controller/tests/test_update.py new file mode 100644 index 0000000..76bba05 --- /dev/null +++ b/custom_components/ha_controller/tests/test_update.py @@ -0,0 +1,193 @@ +"""Tests for the firmware update entity, automatic updates and the options flow.""" + +import asyncio +from datetime import timedelta + +import pytest +from homeassistant.data_entry_flow import FlowResultType +from homeassistant.exceptions import HomeAssistantError +from pytest_homeassistant_custom_component.common import ( + async_fire_time_changed, + async_mock_service, +) + +from custom_components.ha_controller.const import CONF_AUTO_UPDATE +from custom_components.ha_controller.firmware import firmware_urls, is_release_version + +from .helpers import VERSION, hello, register_screen, setup_screen + +ENTITY = "update.mock_title_ha_controller_firmware" +URL = f"https://pyxel-dev.github.io/HA-controller/firmware/{VERSION}/ha-controller.ota.bin" + + +def test_firmware_urls(): + assert firmware_urls(VERSION) == (URL, URL + ".md5") + + +def test_is_release_version(): + assert is_release_version("1.2.3") + assert not is_release_version("0.2.0.dev0") + assert not is_release_version("0.2.0-rc1") + + +async def start(hass, *, auto_update=False): + installs = async_mock_service(hass, "esphome", "ha_controller_aabbcc_install_firmware") + async_mock_service(hass, "esphome", "ha_controller_aabbcc_set_layout") + async_mock_service(hass, "esphome", "ha_controller_aabbcc_set_states") + device = await register_screen(hass) + entry = await setup_screen(hass, device) + hass.config_entries.async_update_entry(entry, options={CONF_AUTO_UPDATE: auto_update}) + await hass.async_block_till_done() + return device, entry, installs + + +async def send_hello(hass, device, **overrides): + hass.bus.async_fire("esphome.ha_controller_hello", hello(device, **overrides)) + await hass.async_block_till_done() + + +async def start_install(hass): + """Start the install service call and let it reach its wait for the hello.""" + task = hass.async_create_background_task( + hass.services.async_call("update", "install", {"entity_id": ENTITY}, blocking=True), + "test install", + ) + for _ in range(20): + await asyncio.sleep(0) + return task + + +async def test_unknown_before_first_hello(hass): + await start(hass) + assert hass.states.get(ENTITY).state == "unknown" + + +async def test_update_entity_reports_versions(hass): + device, _, _ = await start(hass) + await send_hello(hass, device, version="0.0.9") + state = hass.states.get(ENTITY) + assert state.state == "on" + assert state.attributes["installed_version"] == "0.0.9" + assert state.attributes["latest_version"] == VERSION + assert state.attributes["release_url"].endswith(f"/tag/v{VERSION}") + + +async def test_update_entity_off_when_versions_match(hass): + device, _, _ = await start(hass) + await send_hello(hass, device, version=VERSION) + assert hass.states.get(ENTITY).state == "off" + + +async def test_newer_firmware_is_offered_as_update(hass): + device, _, _ = await start(hass) + await send_hello(hass, device, version="999.0.0") + assert hass.states.get(ENTITY).state == "on" + + +async def test_install_calls_device_and_completes_on_hello(hass): + device, _, installs = await start(hass) + await send_hello(hass, device, version="0.0.9") + task = await start_install(hass) + assert len(installs) == 1 + assert installs[0].data == {"url": URL, "md5_url": URL + ".md5"} + assert hass.states.get(ENTITY).attributes["in_progress"] is True + await send_hello(hass, device, version=VERSION) + await task + state = hass.states.get(ENTITY) + assert state.state == "off" + assert state.attributes["in_progress"] is False + + +async def test_install_times_out(hass, freezer): + device, entry, _ = await start(hass) + await send_hello(hass, device, version="0.0.9") + task = await start_install(hass) + assert entry.runtime_data.install_in_progress + freezer.tick(timedelta(seconds=301)) + async_fire_time_changed(hass) + await hass.async_block_till_done() + with pytest.raises(HomeAssistantError, match="did not complete"): + await task + assert not entry.runtime_data.install_in_progress + assert hass.states.get(ENTITY).attributes["in_progress"] is False + + +async def test_install_when_offline_raises(hass): + _, entry, installs = await start(hass) + with pytest.raises(HomeAssistantError, match="offline"): + await entry.runtime_data.async_install_firmware(VERSION) + assert installs == [] + + +async def test_install_while_in_progress_raises(hass): + device, entry, installs = await start(hass) + await send_hello(hass, device, version="0.0.9") + task = await start_install(hass) + with pytest.raises(HomeAssistantError, match="already running"): + await entry.runtime_data.async_install_firmware(VERSION) + assert len(installs) == 1 + await send_hello(hass, device, version=VERSION) + await task + + +async def test_auto_update_installs_at_most_once_per_hour(hass, freezer): + device, entry, installs = await start(hass, auto_update=True) + await send_hello(hass, device, version="0.0.9") + assert len(installs) == 1 + freezer.tick(timedelta(seconds=301)) + async_fire_time_changed(hass) # the first install gives up waiting + await hass.async_block_till_done() + assert not entry.runtime_data.install_in_progress + freezer.tick(timedelta(seconds=1)) + await send_hello(hass, device, version="0.0.9") # inside the one hour window + assert len(installs) == 1 + freezer.tick(timedelta(seconds=3601 - 302)) + await send_hello(hass, device, version="0.0.9") # 3601 s after the first attempt + assert len(installs) == 2 + await send_hello(hass, device, version=VERSION) + + +async def test_auto_update_ignores_protocol_mismatch(hass): + device, _, installs = await start(hass, auto_update=True) + await send_hello(hass, device, version="0.0.9", protocol="2") + assert len(installs) == 1 + await send_hello(hass, device, version=VERSION, protocol="2") + + +async def test_unload_ends_pending_install(hass): + device, entry, installs = await start(hass) + await send_hello(hass, device, version="0.0.9") + task = await start_install(hass) + controller = entry.runtime_data + assert controller.install_in_progress + assert await hass.config_entries.async_unload(entry.entry_id) + await hass.async_block_till_done() + assert task.done() # ended without waiting for the 300 s timeout + with pytest.raises(HomeAssistantError, match="unloaded"): + await task + assert not controller.install_in_progress + assert controller._install_waiter is None + + +async def test_auto_update_disabled_by_option(hass): + device, _, installs = await start(hass, auto_update=False) + await send_hello(hass, device, version="0.0.9") + assert installs == [] + + +async def test_auto_update_skipped_for_dev_versions(hass): + device, entry, installs = await start(hass, auto_update=True) + entry.runtime_data._integration_version = "0.2.0.dev0" + await send_hello(hass, device, version="0.0.9") + assert installs == [] + + +async def test_options_flow_toggles_auto_update(hass): + _, entry, _ = await start(hass, auto_update=True) + result = await hass.config_entries.options.async_init(entry.entry_id) + assert result["type"] is FlowResultType.FORM and result["step_id"] == "init" + result = await hass.config_entries.options.async_configure( + result["flow_id"], {CONF_AUTO_UPDATE: False} + ) + assert result["type"] is FlowResultType.CREATE_ENTRY + assert entry.options[CONF_AUTO_UPDATE] is False diff --git a/custom_components/ha_controller/tests/test_websocket.py b/custom_components/ha_controller/tests/test_websocket.py new file mode 100644 index 0000000..210577d --- /dev/null +++ b/custom_components/ha_controller/tests/test_websocket.py @@ -0,0 +1,145 @@ +"""Tests for the websocket API used by the panel.""" + +from homeassistant.config_entries import ConfigEntryState +from homeassistant.setup import async_setup_component +from pytest_homeassistant_custom_component.common import MockConfigEntry + +from custom_components.ha_controller.const import DOMAIN + +from .helpers import register_screen, setup_screen +from .test_compiler import load_layout + +REFERENCE_REV = "90538742" + + +async def start(hass, *, name="HA Controller", mac="aa:bb:cc:dd:ee:ff", saved=True): + device = await register_screen(hass, name=name, mac=mac) + entry = await setup_screen(hass, device) + hass.config_entries.async_update_entry(entry, title=name) + if saved: + await entry.runtime_data.async_save_layout(load_layout("reference")) + return entry + + +async def test_screens_lists_entries(hass, hass_ws_client): + second = await start(hass, name="Bedroom", mac="aa:bb:cc:dd:ee:01", saved=False) + first = await start(hass, name="Attic", mac="aa:bb:cc:dd:ee:02", saved=False) + client = await hass_ws_client(hass) + await client.send_json_auto_id({"type": "ha_controller/screens"}) + msg = await client.receive_json() + assert msg["success"] + assert msg["result"] == {"screens": [first.runtime_data.status(), second.runtime_data.status()]} + + +async def test_screens_skips_unloaded_entries(hass, hass_ws_client): + entry = await start(hass, saved=False) + await hass.config_entries.async_unload(entry.entry_id) + assert entry.state is ConfigEntryState.NOT_LOADED + client = await hass_ws_client(hass) + await client.send_json_auto_id({"type": "ha_controller/screens"}) + msg = await client.receive_json() + assert msg["result"] == {"screens": []} + + +async def test_layout_get_returns_stored_layout(hass, hass_ws_client): + entry = await start(hass) + client = await hass_ws_client(hass) + await client.send_json_auto_id({"type": "ha_controller/layout/get", "entry_id": entry.entry_id}) + msg = await client.receive_json() + assert msg["success"] + assert msg["result"] == {"layout": load_layout("reference")} + + +async def test_layout_get_unknown_entry_returns_not_found(hass, hass_ws_client): + assert await async_setup_component(hass, DOMAIN, {}) + client = await hass_ws_client(hass) + await client.send_json_auto_id({"type": "ha_controller/layout/get", "entry_id": "missing"}) + msg = await client.receive_json() + assert not msg["success"] + assert msg["error"]["code"] == "not_found" + + +async def test_layout_get_foreign_entry_returns_not_found(hass, hass_ws_client): + assert await async_setup_component(hass, DOMAIN, {}) + other = MockConfigEntry(domain="other") + other.add_to_hass(hass) + client = await hass_ws_client(hass) + await client.send_json_auto_id({"type": "ha_controller/layout/get", "entry_id": other.entry_id}) + msg = await client.receive_json() + assert msg["error"]["code"] == "not_found" + + +async def test_layout_get_unloaded_entry_returns_not_found(hass, hass_ws_client): + entry = await start(hass, saved=False) + await hass.config_entries.async_unload(entry.entry_id) + client = await hass_ws_client(hass) + await client.send_json_auto_id({"type": "ha_controller/layout/get", "entry_id": entry.entry_id}) + msg = await client.receive_json() + assert msg["error"]["code"] == "not_found" + + +async def test_layout_save_valid(hass, hass_ws_client): + entry = await start(hass, saved=False) + client = await hass_ws_client(hass) + await client.send_json_auto_id( + { + "type": "ha_controller/layout/save", + "entry_id": entry.entry_id, + "layout": load_layout("reference"), + } + ) + msg = await client.receive_json() + assert msg["success"] + assert msg["result"] == {"revision": REFERENCE_REV, "pushed": False} + assert entry.runtime_data.layout == load_layout("reference") + + +async def test_layout_save_invalid(hass, hass_ws_client): + entry = await start(hass, saved=False) + layout = load_layout("reference") + layout["blocks"][1]["name"] = "" + client = await hass_ws_client(hass) + await client.send_json_auto_id( + { + "type": "ha_controller/layout/save", + "entry_id": entry.entry_id, + "layout": layout, + } + ) + msg = await client.receive_json() + assert not msg["success"] + assert msg["error"] == {"code": "invalid_layout", "message": "invalid_name@b2"} + + +async def test_layout_save_unknown_entry_returns_not_found(hass, hass_ws_client): + assert await async_setup_component(hass, DOMAIN, {}) + client = await hass_ws_client(hass) + await client.send_json_auto_id( + { + "type": "ha_controller/layout/save", + "entry_id": "missing", + "layout": load_layout("reference"), + } + ) + msg = await client.receive_json() + assert msg["error"]["code"] == "not_found" + + +async def test_commands_require_admin(hass, hass_ws_client, hass_admin_user): + entry = await start(hass) + hass_admin_user.groups = [] + client = await hass_ws_client(hass) + commands = [ + {"type": "ha_controller/screens"}, + {"type": "ha_controller/layout/get", "entry_id": entry.entry_id}, + { + "type": "ha_controller/layout/save", + "entry_id": entry.entry_id, + "layout": load_layout("reference"), + }, + ] + for command in commands: + await client.send_json_auto_id(command) + msg = await client.receive_json() + assert not msg["success"] + assert msg["error"]["code"] == "unauthorized" diff --git a/custom_components/ha_controller/translations/en.json b/custom_components/ha_controller/translations/en.json new file mode 100644 index 0000000..ce4e2a8 --- /dev/null +++ b/custom_components/ha_controller/translations/en.json @@ -0,0 +1,37 @@ +{ + "config": { + "step": { + "user": { + "title": "Add an HA Controller screen", + "description": "Pick the screen. It must already be added to Home Assistant with the ESPHome integration.", + "data": { + "device_id": "Screen" + } + } + }, + "error": { + "not_ha_controller": "This device is not an HA Controller screen." + }, + "abort": { + "already_configured": "This screen is already set up." + } + }, + "entity": { + "update": { + "firmware": { + "name": "HA Controller firmware" + } + } + }, + "options": { + "step": { + "init": { + "title": "HA Controller options", + "description": "Installs the firmware that matches this integration's version whenever the screen reports a different one.", + "data": { + "auto_update": "Update the screen firmware automatically" + } + } + } + } +} diff --git a/custom_components/ha_controller/update.py b/custom_components/ha_controller/update.py new file mode 100644 index 0000000..eef1a2c --- /dev/null +++ b/custom_components/ha_controller/update.py @@ -0,0 +1,69 @@ +"""Firmware update entity of a screen.""" + +from homeassistant.components.update import UpdateEntity, UpdateEntityFeature +from homeassistant.core import HomeAssistant, callback +from homeassistant.helpers import device_registry as dr +from homeassistant.helpers.device_registry import DeviceInfo +from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback + +from . import HaControllerConfigEntry +from .const import RELEASE_URL +from .controller import ScreenController + + +async def async_setup_entry( + hass: HomeAssistant, + entry: HaControllerConfigEntry, + async_add_entities: AddConfigEntryEntitiesCallback, +) -> None: + """Add the firmware update entity of a screen.""" + controller = entry.runtime_data + device = dr.async_get(hass).async_get(controller.device_id) + if device is None: + return + async_add_entities([FirmwareUpdateEntity(controller, device.connections)]) + + +class FirmwareUpdateEntity(UpdateEntity): + """Keeps the screen firmware on the integration version.""" + + _attr_has_entity_name = True + _attr_translation_key = "firmware" + _attr_title = "HA Controller" + _attr_supported_features = UpdateEntityFeature.INSTALL | UpdateEntityFeature.PROGRESS + _attr_should_poll = False + + def __init__(self, controller: ScreenController, connections: set[tuple[str, str]]) -> None: + self._controller = controller + self._attr_unique_id = f"{controller.device_id}-firmware" + self._attr_device_info = DeviceInfo(connections=connections) + + @property + def installed_version(self) -> str | None: + return self._controller.device.version + + @property + def latest_version(self) -> str: + return self._controller.integration_version + + @property + def release_url(self) -> str: + return RELEASE_URL.format(version=self.latest_version) + + @property + def in_progress(self) -> bool: + return self._controller.install_in_progress + + def version_is_newer(self, latest_version: str, installed_version: str) -> bool: + """Offer any different version, so a downgrade is shown as an update.""" + return latest_version != installed_version + + async def async_install(self, version: str | None, backup: bool, **kwargs: object) -> None: + await self._controller.async_install_firmware(self.latest_version) + + async def async_added_to_hass(self) -> None: + self.async_on_remove(self._controller.async_add_listener(self._handle_update)) + + @callback + def _handle_update(self) -> None: + self.async_write_ha_state() diff --git a/custom_components/ha_controller/websocket.py b/custom_components/ha_controller/websocket.py new file mode 100644 index 0000000..4f4f8e5 --- /dev/null +++ b/custom_components/ha_controller/websocket.py @@ -0,0 +1,86 @@ +"""Websocket API used by the HA Controller panel.""" + +from typing import Any + +import voluptuous as vol +from homeassistant.components import websocket_api +from homeassistant.config_entries import ConfigEntryState +from homeassistant.core import HomeAssistant, callback + +from .const import DOMAIN +from .controller import InvalidLayout, ScreenController, format_layout_errors + + +@callback +def async_register_websocket(hass: HomeAssistant) -> None: + """Register the panel commands.""" + websocket_api.async_register_command(hass, ws_screens) + websocket_api.async_register_command(hass, ws_layout_get) + websocket_api.async_register_command(hass, ws_layout_save) + + +def _get_controller( + hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any] +) -> ScreenController | None: + """Return the controller of a loaded entry, or send not_found.""" + entry = hass.config_entries.async_get_entry(msg["entry_id"]) + if entry is None or entry.domain != DOMAIN or entry.state is not ConfigEntryState.LOADED: + connection.send_error(msg["id"], websocket_api.ERR_NOT_FOUND, "Screen not found") + return None + return entry.runtime_data + + +@websocket_api.websocket_command({vol.Required("type"): "ha_controller/screens"}) +@websocket_api.require_admin +@callback +def ws_screens( + hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any] +) -> None: + """List the loaded screens.""" + entries = sorted( + ( + entry + for entry in hass.config_entries.async_entries(DOMAIN) + if entry.state is ConfigEntryState.LOADED + ), + key=lambda entry: entry.title, + ) + connection.send_result( + msg["id"], {"screens": [entry.runtime_data.status() for entry in entries]} + ) + + +@websocket_api.websocket_command( + {vol.Required("type"): "ha_controller/layout/get", vol.Required("entry_id"): str} +) +@websocket_api.require_admin +@callback +def ws_layout_get( + hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any] +) -> None: + """Return the stored layout of a screen.""" + if (controller := _get_controller(hass, connection, msg)) is not None: + connection.send_result(msg["id"], {"layout": controller.layout}) + + +@websocket_api.websocket_command( + { + vol.Required("type"): "ha_controller/layout/save", + vol.Required("entry_id"): str, + vol.Required("layout"): dict, + } +) +@websocket_api.require_admin +@websocket_api.async_response +async def ws_layout_save( + hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any] +) -> None: + """Validate, store and push a layout.""" + if (controller := _get_controller(hass, connection, msg)) is None: + return + try: + revision, pushed = await controller.async_save_layout(msg["layout"]) + except InvalidLayout as err: + connection.send_error(msg["id"], "invalid_layout", format_layout_errors(err.errors)) + return + connection.send_result(msg["id"], {"revision": revision, "pushed": pushed}) diff --git a/custom_components/pyproject.toml b/custom_components/pyproject.toml new file mode 100644 index 0000000..0825ec9 --- /dev/null +++ b/custom_components/pyproject.toml @@ -0,0 +1,12 @@ +[tool.pytest.ini_options] +testpaths = ["ha_controller/tests"] +pythonpath = [".."] +asyncio_mode = "auto" +asyncio_default_fixture_loop_scope = "function" + +[tool.ruff] +target-version = "py314" +line-length = 100 + +[tool.ruff.lint] +select = ["E", "F", "I", "UP", "B"] diff --git a/custom_components/requirements_test.txt b/custom_components/requirements_test.txt new file mode 100644 index 0000000..3b7da4b --- /dev/null +++ b/custom_components/requirements_test.txt @@ -0,0 +1,3 @@ +pytest-homeassistant-custom-component==0.13.375 +home-assistant-frontend==20260930.5 +ruff diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..cb6af5d --- /dev/null +++ b/docs/README.md @@ -0,0 +1,11 @@ +# HA Controller documentation + +- [Architecture](architecture.md): subsystems, data flow and repository layout. +- [Design specification](superpowers/specs/2026-11-16-ha-controller-design.md): the approved design for version 1, with the plans in `superpowers/plans/`. +- [Device protocol v1](protocol/README.md): the normative layout model and device protocol, pinned by `docs/protocol/fixtures/`. +- [Development](development.md): environments, tests and running a development Home Assistant. +- [Configuration](configuration.md): how to edit the screens in the HA Controller panel. +- [Hardware](hardware.md): the board, pins, power, performance settings and enclosures. +- [Getting started](getting-started.md): installing the firmware and the integration. +- [Updates](updates.md): how the integration and the firmware are updated. +- [Releasing](releasing.md): cutting a release. diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..840f552 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,60 @@ +# Architecture + +HA Controller has three parts: a Home Assistant custom integration with a sidebar panel, an ESPHome firmware for the screen, and a GitHub Pages web installer. This page is the contributor overview. + +## Overview + +```text + Home Assistant Screen (ESPHome firmware) +┌──────────────────────────────────────────┐ ┌──────────────────────────────────────┐ +│ custom integration `ha_controller` │ ESPHome │ external component `ha_controller` │ +│ config entry per screen │ actions │ layout + state parsers (pure C++) │ +│ layout store + validation │ ─────────▶ │ pager: edge swipes, slide animation │ +│ compiler → device payload (+ revision) │ set_layout │ block views: knobs, custom items │ +│ sync engine (hello, states, controls) │ set_states │ message screen │ +│ firmware update entity + auto-update │ install_fw │ │ +│ websocket API + sidebar panel (Lit) │ ◀───────── │ board package: CO5300 display, │ +└──────────────────────────────────────────┘ events │ CST9217 touch, AXP2101 battery, │ + ▲ HACS (release zip) hello / │ screen brightness number │ + │ control └──────────────────────────────────────┘ + GitHub Releases ──────▶ GitHub Pages: web installer + firmware// ▲ OTA download / USB flash +``` + +## Subsystems + +- The screen is an ordinary ESPHome device, adopted by Home Assistant's ESPHome integration. The custom integration opens no connection of its own. It calls the device's user-defined ESPHome actions, which Home Assistant exposes as services `esphome._` (node name with `-` replaced by `_`). It also listens to the `esphome.ha_controller_*` events fired by the device. +- Home Assistant's ESPHome integration adds `device_id` to every device event. It requires the "Allow the device to perform Home Assistant actions" option for actions, but not for events (`homeassistant/components/esphome/manager.py`). The design uses events only, so that option can stay off. +- The integration is the single source of truth for both the layout and the version. The firmware is a generic renderer. + +- **Integration** (`custom_components/ha_controller/`): stores and validates layouts, compiles them into the device payload, runs the sync engine and exposes the websocket API used by the panel. +- **Panel** (`custom_components/ha_controller/frontend/`): the block map editor, built with Lit and Vite and served from the integration. +- **Firmware** (`esphome/`): a generic renderer. It parses the layout and states it receives, draws the blocks and reports touches as events. +- **Distribution** (`.github/scripts/`, `.github/workflows/`): HACS release zip, firmware builds and the web installer on GitHub Pages. + +## Handshake: hello, layout and states + +When the screen connects (or reboots) it fires a `hello` event carrying its firmware version and the protocol version. When the revision differs, the integration answers with `set_layout` (the compiled layout payload with its revision) and then `set_states` (the current Home Assistant states of the entities the layout uses). The integration pushes the layout only when the hello's revision differs from its own, and after a `connected` hello with the same revision it pushes all states. Afterwards it sends `set_states` again whenever a watched entity changes, and `set_layout` whenever the stored layout changes. The exact messages are defined in `docs/protocol/README.md` and pinned by `docs/protocol/fixtures/`. + +## Controls become service calls + +A touch on a block (a knob turn, a tap on a custom item) is sent by the firmware as a `control` event. The integration maps the event to a Home Assistant service call using the stored layout, never trusting the device for entity ids or service names, and runs it. The resulting state change flows back to the screen through `set_states`. + +## Firmware updates + +The integration version is the single version of the repository. The integration creates an `update` entity per screen: the installed version comes from the last hello and the latest version is the integration version. Installing calls the device's `install_firmware` action with the OTA URL on GitHub Pages (`firmware//`). With the `auto_update` option on, a hello reporting a different version triggers one automatic install attempt per screen and version, only for release versions. OTA needs internet access from the screen. Without it, re-flash over USB from the web installer. + +## Repository layout + +The repository root holds no files except `README.md` (GitHub and HACS landing page), `hacs.json` (HACS reads it only at the root) and `.gitignore`. Everything else lives in a folder: + +| Path | Content | +|---|---| +| `docs/` | User and developer documentation. `docs/protocol/` holds the protocol doc (`README.md`) and its shared fixtures (`fixtures/`), the cross-language contract. `docs/superpowers/` holds this spec and the plans. | +| `custom_components/` | Everything for the Home Assistant integration. HACS allows a single directory here, so development files live inside it, or next to it as plain files. | +| `custom_components/ha_controller/` | The integration (Python). Also holds `emoji.json` (canonical emoji list, also read by the firmware build and the panel), `brand/`, `tests/` (pytest), and `frontend/` (panel source in TypeScript, Lit and Vite, built to `frontend/dist/`, which is git-ignored). | +| `custom_components/pyproject.toml`, `requirements_test.txt`, `__init__.py` | Python test and lint configuration for the integration. The empty `__init__.py` keeps test imports under `custom_components.ha_controller`. | +| `esphome/` | Everything for the firmware: device config, packages, simulator config, external components, C++ host tests, web installer page, `requirements.txt` (ESPHome version) and its venv (`esphome/.venv`, git-ignored) | +| `.github/workflows/` | CI, firmware CI, release | +| `.github/scripts/` | Release and repository-check tooling (versioning, packaging, GitHub Pages site builder, docs and fixture checks), with its own `pyproject.toml`, `requirements.txt` and `tests/` | +| `.claude/` | `CLAUDE.md`, Claude Code skills and agents | +| `3D_models/`, `files/` | Existing enclosure models (unchanged) | diff --git a/docs/configuration.md b/docs/configuration.md new file mode 100644 index 0000000..3d15837 --- /dev/null +++ b/docs/configuration.md @@ -0,0 +1,53 @@ +# Configuring HA Controller + +The HA Controller panel edits what each screen shows. Changes only reach the screen when you press Save. + +## Opening the panel + +Open **HA Controller** in the Home Assistant sidebar. The panel is only available to administrators. If you have several screens, pick one in the header. + +The status line next to the title tells you whether the screen is online and whether it is up to date: + +- `Offline`: the screen is not connected. Saved changes are delivered when it reconnects. +- `Online · firmware · syncing…`: the screen is receiving the latest layout. +- `Online · firmware · in sync`: the screen shows the saved layout. +- `Online · firmware — update available`: the screen firmware differs from the integration version. Update the firmware. + +## The block map + +The map shows every block of the screen as a tile. Each block is a full-screen page on the device. The block marked **start** is the one shown when the screen wakes up. + +- Select a block to edit it on the right (below the map on narrow windows). +- Click a **+** next to a block to add a neighbouring block there. New blocks are named "Block 5", "Block 6" and so on. +- Set another start block with "Set as start block". You cannot delete the start block, nor a block that would leave other blocks unreachable from the start. + +## How swiping follows the map + +The map is the layout of the pages on the screen. Put a finger on the right edge and slide left to open the block on the right. The same works for every edge: slide right from the left edge to open the block on the left, slide up from the bottom edge to open the block below, and slide down from the top edge to open the block above. + +## Block types + +- **Light**: controls a light entity (tap to toggle, slide to change brightness). +- **Thermostat**: controls a climate entity. +- **Custom**: a free page of up to 6 items, shown in order. Items are a text, an emoji, an entity state (optionally an attribute), the screen battery or the screen brightness. Use the arrows to reorder items and the remove button to delete one. + +## Fonts and backgrounds + +Each block has a font size (S, M, L or XL) and a background colour, chosen from the palette or with a custom colour. The text colour is chosen automatically so it stays readable. Custom items can inherit the font size of their block or override it. + +## Screen settings + +Under the map, **Sleep after (seconds)** sets how long the screen stays on without interaction. The default is 20 seconds. `0` keeps the screen on. Otherwise use a value between 5 and 3600. + +## Saving + +Save and Revert are enabled once you change something. Save is disabled while the layout has errors, which are listed under the map. Revert discards your changes. After saving, the panel tells you whether the new layout was sent to the screen or will be delivered when it reconnects. The panel never overwrites your unsaved changes when the status refreshes. + +## Limits + +- 32 blocks per screen +- 6 items per custom block +- 32 characters per block name +- 64 characters per text +- 64 supported emoji; only emoji from that set can be used +- 24 KB (24,576 bytes) for the whole layout once compiled for the screen. A layout above that limit is refused when you save it diff --git a/docs/development.md b/docs/development.md new file mode 100644 index 0000000..89e69eb --- /dev/null +++ b/docs/development.md @@ -0,0 +1,159 @@ +# Development + +## Prerequisites + +- Python 3.14 (integration tests and repository checks). +- Node 24 (panel build). +- Firmware: a Python 3.13 venv with ESPHome, CMake and SDL2 (see [Firmware](#firmware)). + +Each part of the repository has its own virtual environment: the integration uses `custom_components/.venv`, the repository checks use `.github/scripts/.venv`. + +## Home Assistant integration + +Create the environment and install the test requirements from the repository root: + +```bash +python3.14 -m venv custom_components/.venv +custom_components/.venv/bin/pip install -r custom_components/requirements_test.txt +``` + +Run the tests and the linter: + +```bash +custom_components/.venv/bin/pytest custom_components/ha_controller/tests +custom_components/.venv/bin/ruff check custom_components +``` + +### Running a development Home Assistant + +Symlink the integration into the configuration directory of a development Home Assistant, then restart it: + +```bash +ln -s "$PWD/custom_components/ha_controller" /custom_components/ha_controller +``` + +Add the integration from Settings › Devices & services. The sidebar panel only shows up once the panel bundle has been built; until then Home Assistant logs a warning that the bundle is missing. + +### Watching the traffic + +The screen reports itself with ESPHome events. Open Developer tools › Events, listen to `esphome.ha_controller_hello` and reconnect the screen: every hello shows up there, followed by the layout the integration sends back with `set_layout`. + +## Panel + +The panel is TypeScript with Lit and Vite, in `custom_components/ha_controller/frontend/` (Node 24). Run these from the repository root: + +```bash +npm --prefix custom_components/ha_controller/frontend ci # install +npm --prefix custom_components/ha_controller/frontend test # unit and component tests +npm --prefix custom_components/ha_controller/frontend run dev # mock harness (dev/index.html) in the browser +npm --prefix custom_components/ha_controller/frontend run build -- --watch # rebuild dist/ while testing in Home Assistant +``` + +`npm run dev` serves the panel against `dev/mock-hass.ts`, an in-memory fake of the websocket API seeded with the reference layout. The production bundle is `frontend/dist/ha-controller-panel.js` (git-ignored); the integration serves it to the sidebar panel. + +## Firmware + +The firmware is ESPHome with LVGL, in `esphome/`. The hardware is described in [hardware.md](hardware.md). + +### Prerequisites + +- Python 3.13 (CI uses 3.13; ESPHome is pinned in `esphome/requirements.txt`). +- CMake and a C++ compiler for the host tests. +- SDL2 (`brew install sdl2` or `sudo apt-get install libsdl2-dev`) for the simulator. + +```bash +python3.13 -m venv esphome/.venv +esphome/.venv/bin/pip install -r esphome/requirements.txt +``` + +### Commands + +Run these from the repository root: + +```bash +# Host tests for the pure C++ logic +cmake -S esphome/tests -B esphome/tests/build +cmake --build esphome/tests/build +ctest --test-dir esphome/tests/build --output-on-failure + +# Compile the device and the simulator configs +esphome/.venv/bin/esphome compile esphome/ha-controller.yaml +esphome/.venv/bin/esphome compile esphome/simulator.yaml + +# Flash the screen over USB-C (first flash, or when OTA is not possible) +esphome/.venv/bin/esphome run esphome/ha-controller.yaml + +# Run the simulator (an SDL window on the development machine) +esphome/.venv/bin/esphome run esphome/simulator.yaml +``` + +`esphome/secrets.yaml` must never be committed. ESPHome recreates `esphome/.gitignore` on every compile; it is git-ignored. + +### Connecting Home Assistant to the simulator + +1. Run `esphome/.venv/bin/esphome run esphome/simulator.yaml`. The window shows "Waiting for Home Assistant". +2. In Home Assistant, add an ESPHome device on `:6053`. +3. Add the HA Controller integration and pick "HA Controller Simulator". +4. Within 5 s the simulator shows "No blocks yet". Developer tools › Events shows `esphome.ha_controller_hello` with the reasons `connected` and then `applied`. + +Edit the layout in the panel and the simulator follows. Mouse drags stand in for finger swipes. The simulator has no HTTP OTA, so `install_firmware` exists only in the device config. + +### Manual hardware checklist + +Plan 4 could not test these on the board. Run them in one go with the firmware flashed over USB-C and, where marked, the simulator connected to Home Assistant. + +**Display, touch and power** (device) + +- The round display shows "HA Controller", the version and 💡, centred. +- Tapping near the top, right, bottom and left edges logs about `(233,5)`, `(460,233)`, `(233,460)` and `(5,233)`. Otherwise fix `transform` (`mirror_x`, `mirror_y`, `swap_xy`) and repeat. +- With a battery: `Battery` reads 0–100 %, `Battery voltage` 3.3–4.3 V, and `Charging` turns on when USB is plugged in. +- Without a battery: level and voltage are unknown (NaN) and there are no errors. +- The `Screen brightness` number dims the panel. +- Wi-Fi provisioning works through the `HA Controller` access point and its captive portal. + +**End to end with Home Assistant** (simulator) + +- The simulator shows "No blocks yet" within 5 s of the connection; the hello events show `connected` then `applied`. +- In the panel, add three blocks and save. The simulator shows the start block's name on its background. +- Heartbeat hellos arrive every 60 s with a revision equal to the panel's. + +**Navigation** (simulator, then device with a finger) + +Build the reference map in the panel: Kitchen start, Lights above, Hello World left, Bedroom below Hello World. + +- From Kitchen, a drag from the left edge to the right slides to Hello World. +- From the top edge downwards slides to Lights. +- From the right edge leftwards rubber-bands by at most 48 px and returns. +- From Hello World, the bottom edge upwards slides to Bedroom. +- A drag starting in the centre does nothing. +- A short slow drag snaps back; a quick flick commits. +- The edge hints match the neighbours. +- Saving a layout from the panel while holding a drag shows the new layout cleanly, with no stuck half-page. +- On the device, the slides look smooth (about 30 fps or better). If not, follow the tuning order in [hardware.md](hardware.md#performance-settings) and record the result there. + +**Controls** (simulator with Home Assistant, then device) + +- Light: the knob shows Home Assistant's brightness; dragging to about 30 % and releasing sets the light to 30 %; a centre tap toggles it; a brightness change in Home Assistant moves the knob within 1 s; incoming updates do not move the knob while dragging. +- On/off-only light: a toggle button. +- Climate: steps of 0.5 °C; release updates the target; `Now …` and the action are shown. +- Custom block: text, emoji and the outdoor temperature are shown and follow sensor changes; the battery row shows `🔋 76 %`; the brightness slider changes `number.*_screen_brightness`. +- Renamed entity: renaming a bound entity in Home Assistant shows `—` and `Unavailable` and disables its control. +- Taps give immediate visual feedback. +- On the device: repeat the light, climate and custom checks, the battery row shows the real level, the brightness slider dims the panel smoothly, and with the battery unplugged the row shows `🔋 — %` and nothing crashes. + +**Sleep** (simulator, then device) + +- Simulator: after 20 s without input the log shows `screen_off` and the window stops updating; clicking the light knob position wakes the screen without toggling or moving anything; a delay of 5 s in the panel sleeps after 5 s and `0` keeps the screen awake; a Home Assistant state change made while asleep is visible right after waking. +- Device: the panel goes black after the delay; a tap on the knob area only wakes the screen, which then stays awake for the full delay; changing `Screen brightness` from Home Assistant while asleep keeps the panel dark and the new level shows on wake. +- Watch for a one-frame flash of stale content on wake. + +**Over-the-air update** (device) + +1. Bump `esphome/version.yaml` locally to `0.1.1` (do not commit) and compile. +2. Find the build output with `find esphome/.esphome/build -name firmware.ota.bin`. In that directory, create the checksum with `md5 -q firmware.ota.bin > firmware.ota.bin.md5` (Linux: `md5sum firmware.ota.bin | cut -d' ' -f1 > firmware.ota.bin.md5`), then serve it with `python3 -m http.server 8000 -d `. +3. In Developer tools › Actions, call `esphome.ha_controller__install_firmware` with the LAN URLs of the `.bin` and the `.md5`. The screen shows "Updating firmware…", reboots, and the next hello carries `0.1.1`. +4. Run it once while the screen sleeps: the screen must wake first. +5. Repeat with a wrong `.md5`. The screen shows "Update failed" for 5 s, then the pages return. +6. Revert `version.yaml`. + +Plain `http://` URLs are fine for the LAN test: `verify_ssl` only affects HTTPS. diff --git a/docs/getting-started.md b/docs/getting-started.md new file mode 100644 index 0000000..784730e --- /dev/null +++ b/docs/getting-started.md @@ -0,0 +1,14 @@ +# Getting started + +1. **Hardware and enclosure.** You need a Waveshare ESP32-S3-Touch-AMOLED-1.75. Print an enclosure from the [3D models](../3D_models/) (see [Hardware](hardware.md)). +2. **Flash the firmware.** Open in Chrome or Edge, connect the board over USB and click Install. Note the firmware version shown on the page. +3. **Connect to Wi-Fi.** Use Improv in the installer, or join the `HA Controller` access point and use its captive portal. +4. **Adopt the device.** In Home Assistant, the ESPHome device is discovered. Adopt it under Settings > Devices & services. +5. **Install the integration.** In HACS, add the custom repository `https://github.com/pyxel-dev/HA-controller` (type Integration). Install the **same version** as shown on the installer page, then restart Home Assistant. +6. **Add the integration.** Go to Settings > Devices & services > Add integration > HA Controller, then pick the screen. +7. **Open the panel.** Open HA Controller in the sidebar and design your screens (see [Configuration](configuration.md)). + +## Troubleshooting + +- **The screen stays on "Waiting for Home Assistant".** Check that the ESPHome device and the HA Controller entry both exist. If the hello events never show up under Developer tools > Events, enable "Allow the device to perform Home Assistant actions" in the ESPHome device options. +- **"Firmware update required".** See [Updates](updates.md). diff --git a/docs/hardware.md b/docs/hardware.md new file mode 100644 index 0000000..e651d78 --- /dev/null +++ b/docs/hardware.md @@ -0,0 +1,61 @@ +# Hardware + +The firmware targets the Waveshare ESP32-S3-Touch-AMOLED-1.75: an ESP32-S3R8 (8 MB octal PSRAM, 16 MB flash) with a 1.75" round AMOLED (466×466) and a capacitive touch panel, powered over USB-C or a LiPo battery. + +## Pins and buses + +| Item | Value | +|---|---| +| Display | CO5300 over QSPI. CS GPIO12, SCLK GPIO38, D0–D3 GPIO4/5/6/7, RESET GPIO39. TE (GPIO13) is not used. | +| Touch | CST9217 at I²C 0x5A. INT GPIO11, RESET GPIO40. Transform: `mirror_x` + `mirror_y`. | +| I²C bus | SDA GPIO15, SCL GPIO14, 400 kHz. | + +The I²C bus is shared by these devices: + +| Device | Address | Used by the firmware | +|---|---|---| +| AXP2101 (PMU) | 0x34 | yes (battery) | +| TCA9554 (IO expander) | 0x20 | no | +| QMI8658 (IMU) | 0x6B | no | +| PCF85063 (RTC) | 0x51 | no | +| ES8311 (audio codec) | 0x18 | no | +| ES7210 (audio ADC) | 0x40 | no | + +The touch driver is the external component `cst9217` from `shelson/esphome-cst9217`, pinned to a commit SHA in `esphome/packages/board-waveshare-amoled-175.yaml`. Keep it pinned. + +## Power and battery + +The AXP2101 reports the battery state through the `axp2101_battery` component (`esphome/components/axp2101_battery/`). The display and touch rails are powered by default, so the firmware does not touch the LDO registers. + +Registers used (from XPowersLib): + +- Enable the ADC: set bit 0 of 0x30. +- Enable battery detection: set bit 0 of 0x68. +- Battery present: bit 3 of 0x00. +- Charging: `(reg 0x01 >> 5) == 0x01`. +- Battery percentage: register 0xA4 (0–100). +- Battery voltage in mV: `((reg 0x34 & 0x1F) << 8) | reg 0x35`. + +Without a battery the level and voltage are unknown (NaN) and nothing logs an error. While the screen sleeps the panel brightness is 0 and LVGL is paused; the Wi-Fi and API connections stay up. + +## Performance settings + +- LVGL draws with `lvgl: buffer_size: 25%` (in `esphome/packages/ui.yaml`). This is the current setting. +- It has not been tuned on hardware yet. If the page slides stutter (below about 30 fps), try these in order and keep the best: + 1. `lvgl: buffer_size: 100%`; + 2. `esp32: framework: sdkconfig_options: {CONFIG_ESP32S3_DATA_CACHE_64KB: "y", CONFIG_ESP32S3_DATA_CACHE_LINE_64B: "y"}`; + 3. `lvgl: buffer_size: 12%`. +- Record the result here once measured. +- Image size: about 2.0 MB, in an app partition of about 8.1 MB (ESPHome sizes the partitions for 16 MB flash). + +## Fonts + +Fonts are declared in `esphome/packages/ui.yaml` and reach LVGL through `font::Font::get_lv_font()`. The text font uses `glyphsets: [GF_Latin_Core]` and the Google Fonts source (`gfonts`); both were accepted by ESPHome 2026.10.2, so no explicit-glyph fallback was needed. The emoji fonts take their glyphs from `custom_components/ha_controller/emoji.json`. + +## Sleep + +Sleep uses `touchscreen::TouchListener::release()` to wake on touch (the touch that wakes the screen is swallowed) and the `lvgl.pause`, `lvgl.resume` and `lvgl.widget.redraw` actions to stop and restart drawing. + +## Enclosures + +Printable enclosures are in [`3D_models/`](../3D_models/), in two variants: [with a PWR button](../3D_models/with_pwr_button) and [without one](../3D_models/without_pwr_button). diff --git a/docs/protocol/README.md b/docs/protocol/README.md new file mode 100644 index 0000000..449dce8 --- /dev/null +++ b/docs/protocol/README.md @@ -0,0 +1,170 @@ +# Device protocol v1 + +## 6. Layout model (integration and panel) + +The layout is stored per screen under the Home Assistant storage key `ha_controller.layout.` and exchanged with the panel over websocket. The reference layout `docs/protocol/fixtures/layouts/valid/reference.json` mirrors the screenshot: + +```json +{ "version": 1, "start": "b1", "settings": { "sleep_timeout": 20 }, "blocks": [ + { "id": "b1", "x": 0, "y": 0, "name": "Kitchen", "background": "#5B9E4D", "font_size": "m", + "type": "entity", "entity_id": "light.kitchen" }, + { "id": "b2", "x": 0, "y": -1, "name": "Lights", "background": "#C94F3D", "font_size": "m", + "type": "entity", "entity_id": "light.living_room" }, + { "id": "b3", "x": -1, "y": 0, "name": "Hello World", "background": "#4F86DD", "font_size": "l", + "type": "custom", "items": [ + { "id": "i1", "kind": "text", "text": "Hello World", "font_size": null }, + { "id": "i2", "kind": "emoji", "emoji": "👋", "font_size": "xl" }, + { "id": "i3", "kind": "entity", "entity_id": "sensor.outdoor_temperature", "attribute": null, "font_size": "s" }, + { "id": "i4", "kind": "battery", "font_size": "s" }, + { "id": "i5", "kind": "brightness", "font_size": null } ] }, + { "id": "b4", "x": -1, "y": 1, "name": "Bedroom", "background": "#7B2FA0", "font_size": "m", + "type": "entity", "entity_id": "climate.bedroom" } ] } +``` + +Unknown keys are ignored, so the panel can keep `entity_id` and `items` when the user switches a block's type. + +Validation returns a list of `{code, ref}`, where `ref` is the offending block or item id, or `null`. An empty list means the layout is valid. It runs in three phases: +1. **Structure.** It stops at the first error. +2. **Per-field checks.** All errors are collected. +3. **Connectivity.** Only runs if phase 2 found nothing. + +| Code | Rule | +|---|---| +| `invalid_structure` | `version` must be `1`, `settings` an object, `blocks` a list, and blocks and items objects with the expected JSON types | +| `too_many_blocks` | At most 32 blocks | +| `invalid_sleep_timeout` | `settings.sleep_timeout` is an integer (not a boolean): `0` (never) or 5–3600 seconds | +| `invalid_id` | Ids match `^[a-z][a-z0-9]{0,7}$` | +| `duplicate_id` | Ids are unique across blocks **and** items | +| `coordinate_out_of_range` | `-32 ≤ x, y ≤ 32` (integers) | +| `duplicate_position` | One block per cell (ref = the later block) | +| `invalid_start` | `start` is `null` if and only if there are no blocks; otherwise it is the id of an existing block | +| `disconnected` | Every block is reachable from `start` through 4-neighbour cells (one error per unreachable block, in layout order) | +| `invalid_name` | 1–32 characters after trimming | +| `invalid_background` | `^#[0-9A-Fa-f]{6}$` | +| `invalid_font_size` | Block: `s`/`m`/`l`/`xl`. Item: the same, or `null` (inherit). | +| `invalid_type` | `entity` or `custom` | +| `invalid_entity` | Entity block: an `entity_id` of domain `light` or `climate`. Entity item: an id matching `^[a-z0-9_]+\.[a-z0-9_]+$`, and `attribute` either `null` or 1–64 characters. | +| `too_many_items` | At most 6 items per custom block | +| `invalid_item` | `kind` is one of `text`, `emoji`, `entity`, `battery`, `brightness` | +| `invalid_text` | Text item: 1–64 characters | +| `unsupported_emoji` | Emoji item: after removing U+FE0F, the value is an entry of `emoji.json` | +| `payload_too_large` | The compiled payload (§7.3) is larger than 24 576 UTF-8 bytes. Checked by the integration only. | + +Lengths count Unicode code points (Python `len`, JavaScript `Array.from(text).length`), and names are trimmed of Unicode whitespace (`str.strip()`, `String.prototype.trim()`). The fixtures `astral-text` (valid) and `invalid_name-astral` pin this. + +Entities that do not exist (yet) are valid; the screen shows them as unavailable. + +## 7. Device protocol v1 (normative) + +`PROTOCOL_VERSION = 1`. This page is the living copy of this section. `docs/protocol/fixtures/` pins it with examples, used by the tests of all three implementations. + +**7.1 Actions (Home Assistant → screen).** Services `esphome._`: + +| Action | Variables | Effect | +|---|---|---| +| `set_layout` | `layout: string` (payload JSON, §7.3) | Parse it. On success, rebuild the pages and adopt `rev`. Then fire a hello with reason `applied`; this also happens after a failure, with the revision unchanged. | +| `set_states` | `states: string` (JSON array, §7.4) | Apply each update to the block or item with that id. Unknown ids are ignored. | +| `install_firmware` | `url: string`, `md5_url: string` | Show `Updating firmware…`, render it immediately, then run `ota.http_request.flash`. On failure, show `Update failed` for 5 s. | + +**7.2 Events (screen → Home Assistant).** Data values are strings, and Home Assistant adds `device_id`. + +| Event | Data | When | +|---|---|---| +| `esphome.ha_controller_hello` | `node` (ESPHome node name), `version` (firmware version), `protocol` (`"1"`), `revision` (applied `rev` or `none`), `reason` (`connected` / `heartbeat` / `applied`) | 5 s after an API client connects, every 60 s while connected, and after each `set_layout` | +| `esphome.ha_controller_control` | `block` (block id), `item` (item id or empty), `op` (`toggle` / `set`), `value` (decimal, `%.2f`) | Centre tap on a light (`toggle`), knob release (`set`) | + +**7.3 Layout payload.** The integration compiles it from the stored layout: +- **Top level:** `v` (1), `rev`, `start` (id or `null`), `sleep` (integer seconds, `0` = never), `blocks`. +- **Block:** `id`, `x`, `y`, `name`, `bg` (6 uppercase hex digits, no `#`), `font`, `widget`. + - `widget` is `light` or `climate` (taken from the entity domain), or `custom`. + - Custom blocks also carry `items` (possibly empty). Entity blocks carry no `items`. +- **Item:** `id`, `kind`, `font` (the item's size, or the block's when the item's is `null`). + - `text` items carry `text` (the text). + - `emoji` items carry `text` (the emoji without U+FE0F). + - Other kinds carry no `text`. +- No entity ids are sent to the screen. +- `rev` is the first 8 hex chars of SHA-256 over the UTF-8 bytes of `json.dumps(payload_without_rev, sort_keys=True, separators=(",", ":"), ensure_ascii=False)`. + - Golden values: empty payload (`sleep` 20) → `c4aad3fa`; `payloads/valid/reference.json` → `90538742`; `payloads/valid/emoji-variation.json` → `5387d4ea`. +- **Transport encoding:** compact JSON (`separators=(",", ":")`, `ensure_ascii=False`), at most 24 576 bytes. + +Device parse errors: +- `bad_json`: not JSON, or not an object. +- `unsupported_version`: `v != 1`. +- `invalid_payload`: a missing or mistyped field, an unknown `widget`, `kind` or `font`, or a `sleep` outside 0–3600. + +**7.4 State updates.** A JSON array. Each element has `id` (block or item id) and `available` (bool, default `true`): + +| Target | Fields | +|---|---| +| Light block | `on` (bool), `brightness` (0–100 integer; `null` for on/off-only lights; `0` when a dimmable light is off) | +| Climate block | `target` (number or `null`), `min`, `max`, `step` (numbers), `unit` (`°C`/`°F`), `current` (display string), `action` (display string, e.g. `Heating`) | +| Entity item | `text` (display string) | + +An unavailable or missing entity sends `{"id": …, "available": false}`. Entity items send `{"id": …, "text": "—"}` instead. Updates are sent in layout order, in chunks of at most 8 192 bytes. + +**7.5 Handshake and resync** (integration side): +- **On a hello from the screen's `device_id`:** record the node, version, protocol, revision and time. Then: + - If `protocol ≠ 1`, push nothing (auto-update may run, §11). + - Else, if `revision ≠` the current revision, push the layout and then all states. Push immediately when `reason = connected`. Otherwise push at most once per 300 s for the same revision. + - Else, if `reason = connected`, or this is the first hello since the integration (re)started, push all states. After an integration reload the ESPHome connection stays up, so no `connected` hello arrives. +- **Entity state changes:** coalesced for 200 ms, then pushed for the changed entities. This only happens while the screen is online (a hello within the last 150 s) and on protocol 1. +- **Saving a layout:** pushes it immediately if the screen is online. + +**7.6 Control mapping** (integration side). The entity always comes from the layout, never from the event. + +| Block | op | Service call | +|---|---|---| +| Light | `toggle` | `light.toggle` `{entity_id}` | +| Light | `set`, value ≤ 0 | `light.turn_off` `{entity_id}` | +| Light | `set`, value > 0 | `light.turn_on` `{entity_id, brightness_pct: round(clamp(value, 1, 100))}` | +| Climate | `set` | `climate.set_temperature` `{entity_id, temperature: clamp(value, min_temp, max_temp)}` (bounds from the current state, defaults 7/35) | + +Anything else is ignored: an unknown block, a custom block, an unparsable value. Service errors are logged, never raised. + +**7.7 State builders** (integration side): +- **Light:** + - Unavailable if the entity is missing, `unavailable` or `unknown`. + - Dimmable if `supported_color_modes` contains a mode other than `onoff`. + - Brightness: `round((attribute brightness or 255) × 100 / 255)` when on, `0` when off, `null` when not dimmable. +- **Climate:** + - `unit` is Home Assistant's temperature unit. + - `step` is `target_temp_step`, or else `0.5` for °C and `1` for °F. + - `min`/`max` come from `min_temp`/`max_temp` (defaults 7/35). + - `current` is `" "`, or `—`. + - `action` is `hvac_action`, or else the state, with `_` replaced by a space and the first letter capitalised. +- **Entity item:** + - `—` if the entity is missing, `unavailable` or `unknown`, or if the attribute is missing. + - A numeric value is rounded to the entity registry's `sensor.display_precision`, or else `suggested_display_precision`, or else left unchanged. + - The result is `" "` when a unit exists, truncated to 64 characters. + + +## Fixtures + +`fixtures/` is the executable contract of this protocol. The examples pin it, and all three implementations test themselves against them. All files are UTF-8 JSON without a BOM. + +| Folder | Content | Read by | +|---|---|---| +| `fixtures/layouts/valid`, `fixtures/layouts/invalid` | Stored layouts and the validation error each invalid one must produce | pytest in `custom_components/ha_controller/tests`, vitest in `custom_components/ha_controller/frontend/test` | +| `fixtures/payloads/valid` | A stored layout and the compiled payload (with golden `rev`) | pytest in `custom_components/ha_controller/tests`, vitest in `custom_components/ha_controller/frontend/test`, doctest in `esphome/tests` | +| `fixtures/payloads/invalid` | Raw strings sent to `set_layout` and the parse error expected | doctest in `esphome/tests` | +| `fixtures/states` | Home Assistant states and the expected update objects | pytest in `custom_components/ha_controller/tests` | +| `fixtures/controls` | Control events and the expected service call | pytest in `custom_components/ha_controller/tests` | +| `fixtures/colors.json` | Background colours and the expected text colour | pytest in `custom_components/ha_controller/tests`, vitest in `custom_components/ha_controller/frontend/test`, doctest in `esphome/tests` | + +The consumers are: + +- pytest: `custom_components/ha_controller/tests` and `.github/scripts/tests` (the latter checks the fixtures themselves); +- vitest: `custom_components/ha_controller/frontend/test`; +- doctest: `esphome/tests`. + +### One broken rule per invalid fixture + +Each file in `fixtures/layouts/invalid` takes a valid layout and breaks exactly one rule. Its stem is the expected error code, or the code followed by `-` and a suffix when a code has several cases. + +### Canonical revision + +```python +hashlib.sha256(json.dumps(p, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()).hexdigest()[:8] +``` + +`p` is the payload without its `rev` key. Recompute the golden `rev` of `fixtures/payloads/valid/*.json` whenever a payload changes. diff --git a/docs/protocol/fixtures/colors.json b/docs/protocol/fixtures/colors.json new file mode 100644 index 0000000..8ed6457 --- /dev/null +++ b/docs/protocol/fixtures/colors.json @@ -0,0 +1,38 @@ +[ + { + "bg": "#FFFFFF", + "text": "#000000" + }, + { + "bg": "#000000", + "text": "#FFFFFF" + }, + { + "bg": "#5B9E4D", + "text": "#FFFFFF" + }, + { + "bg": "#4F86DD", + "text": "#FFFFFF" + }, + { + "bg": "#C94F3D", + "text": "#FFFFFF" + }, + { + "bg": "#7B2FA0", + "text": "#FFFFFF" + }, + { + "bg": "#F1C40F", + "text": "#000000" + }, + { + "bg": "#9E9E9E", + "text": "#000000" + }, + { + "bg": "#8C8C8C", + "text": "#FFFFFF" + } +] diff --git a/docs/protocol/fixtures/controls/climate-clamp.json b/docs/protocol/fixtures/controls/climate-clamp.json new file mode 100644 index 0000000..4590942 --- /dev/null +++ b/docs/protocol/fixtures/controls/climate-clamp.json @@ -0,0 +1,26 @@ +{ + "layout": "reference", + "hass_states": { + "climate.bedroom": { + "state": "heat", + "attributes": { + "min_temp": 7, + "max_temp": 35 + } + } + }, + "event": { + "block": "b4", + "item": "", + "op": "set", + "value": "50.00" + }, + "expect_call": { + "domain": "climate", + "service": "set_temperature", + "data": { + "entity_id": "climate.bedroom", + "temperature": 35 + } + } +} diff --git a/docs/protocol/fixtures/controls/climate-set.json b/docs/protocol/fixtures/controls/climate-set.json new file mode 100644 index 0000000..8794970 --- /dev/null +++ b/docs/protocol/fixtures/controls/climate-set.json @@ -0,0 +1,26 @@ +{ + "layout": "reference", + "hass_states": { + "climate.bedroom": { + "state": "heat", + "attributes": { + "min_temp": 7, + "max_temp": 35 + } + } + }, + "event": { + "block": "b4", + "item": "", + "op": "set", + "value": "21.50" + }, + "expect_call": { + "domain": "climate", + "service": "set_temperature", + "data": { + "entity_id": "climate.bedroom", + "temperature": 21.5 + } + } +} diff --git a/docs/protocol/fixtures/controls/ignored-bad-value.json b/docs/protocol/fixtures/controls/ignored-bad-value.json new file mode 100644 index 0000000..290ad87 --- /dev/null +++ b/docs/protocol/fixtures/controls/ignored-bad-value.json @@ -0,0 +1,11 @@ +{ + "layout": "reference", + "hass_states": {}, + "event": { + "block": "b1", + "item": "", + "op": "set", + "value": "abc" + }, + "expect_call": null +} diff --git a/docs/protocol/fixtures/controls/ignored-climate-toggle.json b/docs/protocol/fixtures/controls/ignored-climate-toggle.json new file mode 100644 index 0000000..dd5e767 --- /dev/null +++ b/docs/protocol/fixtures/controls/ignored-climate-toggle.json @@ -0,0 +1,11 @@ +{ + "layout": "reference", + "hass_states": {}, + "event": { + "block": "b4", + "item": "", + "op": "toggle", + "value": "0.00" + }, + "expect_call": null +} diff --git a/docs/protocol/fixtures/controls/ignored-custom-block.json b/docs/protocol/fixtures/controls/ignored-custom-block.json new file mode 100644 index 0000000..8e65c09 --- /dev/null +++ b/docs/protocol/fixtures/controls/ignored-custom-block.json @@ -0,0 +1,11 @@ +{ + "layout": "reference", + "hass_states": {}, + "event": { + "block": "b3", + "item": "", + "op": "set", + "value": "1" + }, + "expect_call": null +} diff --git a/docs/protocol/fixtures/controls/ignored-unknown-block.json b/docs/protocol/fixtures/controls/ignored-unknown-block.json new file mode 100644 index 0000000..15c4a1b --- /dev/null +++ b/docs/protocol/fixtures/controls/ignored-unknown-block.json @@ -0,0 +1,11 @@ +{ + "layout": "reference", + "hass_states": {}, + "event": { + "block": "zz", + "item": "", + "op": "set", + "value": "1" + }, + "expect_call": null +} diff --git a/docs/protocol/fixtures/controls/light-set-over.json b/docs/protocol/fixtures/controls/light-set-over.json new file mode 100644 index 0000000..50e6a98 --- /dev/null +++ b/docs/protocol/fixtures/controls/light-set-over.json @@ -0,0 +1,18 @@ +{ + "layout": "reference", + "hass_states": {}, + "event": { + "block": "b2", + "item": "", + "op": "set", + "value": "150" + }, + "expect_call": { + "domain": "light", + "service": "turn_on", + "data": { + "entity_id": "light.living_room", + "brightness_pct": 100 + } + } +} diff --git a/docs/protocol/fixtures/controls/light-set-zero.json b/docs/protocol/fixtures/controls/light-set-zero.json new file mode 100644 index 0000000..e79c924 --- /dev/null +++ b/docs/protocol/fixtures/controls/light-set-zero.json @@ -0,0 +1,17 @@ +{ + "layout": "reference", + "hass_states": {}, + "event": { + "block": "b1", + "item": "", + "op": "set", + "value": "0.00" + }, + "expect_call": { + "domain": "light", + "service": "turn_off", + "data": { + "entity_id": "light.kitchen" + } + } +} diff --git a/docs/protocol/fixtures/controls/light-set.json b/docs/protocol/fixtures/controls/light-set.json new file mode 100644 index 0000000..5340543 --- /dev/null +++ b/docs/protocol/fixtures/controls/light-set.json @@ -0,0 +1,18 @@ +{ + "layout": "reference", + "hass_states": {}, + "event": { + "block": "b1", + "item": "", + "op": "set", + "value": "42.40" + }, + "expect_call": { + "domain": "light", + "service": "turn_on", + "data": { + "entity_id": "light.kitchen", + "brightness_pct": 42 + } + } +} diff --git a/docs/protocol/fixtures/controls/light-toggle.json b/docs/protocol/fixtures/controls/light-toggle.json new file mode 100644 index 0000000..25bfddc --- /dev/null +++ b/docs/protocol/fixtures/controls/light-toggle.json @@ -0,0 +1,17 @@ +{ + "layout": "reference", + "hass_states": {}, + "event": { + "block": "b1", + "item": "", + "op": "toggle", + "value": "0.00" + }, + "expect_call": { + "domain": "light", + "service": "toggle", + "data": { + "entity_id": "light.kitchen" + } + } +} diff --git a/docs/protocol/fixtures/layouts/invalid/coordinate_out_of_range.json b/docs/protocol/fixtures/layouts/invalid/coordinate_out_of_range.json new file mode 100644 index 0000000..bdfe85b --- /dev/null +++ b/docs/protocol/fixtures/layouts/invalid/coordinate_out_of_range.json @@ -0,0 +1,25 @@ +{ + "expect": { + "code": "coordinate_out_of_range", + "ref": "b1" + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 0 + }, + "blocks": [ + { + "id": "b1", + "x": 33, + "y": -2, + "name": "Solo", + "background": "#000000", + "font_size": "s", + "type": "custom", + "items": [] + } + ] + } +} diff --git a/docs/protocol/fixtures/layouts/invalid/disconnected.json b/docs/protocol/fixtures/layouts/invalid/disconnected.json new file mode 100644 index 0000000..a6245c4 --- /dev/null +++ b/docs/protocol/fixtures/layouts/invalid/disconnected.json @@ -0,0 +1,85 @@ +{ + "expect": { + "code": "disconnected", + "ref": "b4" + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "light.kitchen" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "background": "#C94F3D", + "font_size": "m", + "type": "entity", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font_size": null + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "👋", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "sensor.outdoor_temperature", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "battery", + "font_size": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font_size": null + } + ] + }, + { + "id": "b4", + "x": -1, + "y": 2, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] + } +} diff --git a/docs/protocol/fixtures/layouts/invalid/duplicate_id.json b/docs/protocol/fixtures/layouts/invalid/duplicate_id.json new file mode 100644 index 0000000..c976924 --- /dev/null +++ b/docs/protocol/fixtures/layouts/invalid/duplicate_id.json @@ -0,0 +1,85 @@ +{ + "expect": { + "code": "duplicate_id", + "ref": "b1" + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "light.kitchen" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "background": "#C94F3D", + "font_size": "m", + "type": "entity", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font_size": null + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "👋", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "sensor.outdoor_temperature", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "battery", + "font_size": "s" + }, + { + "id": "b1", + "kind": "brightness", + "font_size": null + } + ] + }, + { + "id": "b4", + "x": -1, + "y": 1, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] + } +} diff --git a/docs/protocol/fixtures/layouts/invalid/duplicate_position.json b/docs/protocol/fixtures/layouts/invalid/duplicate_position.json new file mode 100644 index 0000000..2275e77 --- /dev/null +++ b/docs/protocol/fixtures/layouts/invalid/duplicate_position.json @@ -0,0 +1,85 @@ +{ + "expect": { + "code": "duplicate_position", + "ref": "b4" + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "light.kitchen" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "background": "#C94F3D", + "font_size": "m", + "type": "entity", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font_size": null + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "👋", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "sensor.outdoor_temperature", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "battery", + "font_size": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font_size": null + } + ] + }, + { + "id": "b4", + "x": 0, + "y": 0, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] + } +} diff --git a/docs/protocol/fixtures/layouts/invalid/invalid_background.json b/docs/protocol/fixtures/layouts/invalid/invalid_background.json new file mode 100644 index 0000000..abc7b13 --- /dev/null +++ b/docs/protocol/fixtures/layouts/invalid/invalid_background.json @@ -0,0 +1,85 @@ +{ + "expect": { + "code": "invalid_background", + "ref": "b2" + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "light.kitchen" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "background": "red", + "font_size": "m", + "type": "entity", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font_size": null + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "👋", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "sensor.outdoor_temperature", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "battery", + "font_size": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font_size": null + } + ] + }, + { + "id": "b4", + "x": -1, + "y": 1, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] + } +} diff --git a/docs/protocol/fixtures/layouts/invalid/invalid_entity-item.json b/docs/protocol/fixtures/layouts/invalid/invalid_entity-item.json new file mode 100644 index 0000000..07a5134 --- /dev/null +++ b/docs/protocol/fixtures/layouts/invalid/invalid_entity-item.json @@ -0,0 +1,85 @@ +{ + "expect": { + "code": "invalid_entity", + "ref": "i3" + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "light.kitchen" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "background": "#C94F3D", + "font_size": "m", + "type": "entity", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font_size": null + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "👋", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "not an entity", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "battery", + "font_size": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font_size": null + } + ] + }, + { + "id": "b4", + "x": -1, + "y": 1, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] + } +} diff --git a/docs/protocol/fixtures/layouts/invalid/invalid_entity.json b/docs/protocol/fixtures/layouts/invalid/invalid_entity.json new file mode 100644 index 0000000..1a9c855 --- /dev/null +++ b/docs/protocol/fixtures/layouts/invalid/invalid_entity.json @@ -0,0 +1,85 @@ +{ + "expect": { + "code": "invalid_entity", + "ref": "b1" + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "switch.kettle" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "background": "#C94F3D", + "font_size": "m", + "type": "entity", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font_size": null + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "👋", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "sensor.outdoor_temperature", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "battery", + "font_size": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font_size": null + } + ] + }, + { + "id": "b4", + "x": -1, + "y": 1, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] + } +} diff --git a/docs/protocol/fixtures/layouts/invalid/invalid_font_size-item.json b/docs/protocol/fixtures/layouts/invalid/invalid_font_size-item.json new file mode 100644 index 0000000..49f6b79 --- /dev/null +++ b/docs/protocol/fixtures/layouts/invalid/invalid_font_size-item.json @@ -0,0 +1,85 @@ +{ + "expect": { + "code": "invalid_font_size", + "ref": "i1" + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "light.kitchen" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "background": "#C94F3D", + "font_size": "m", + "type": "entity", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font_size": "huge" + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "👋", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "sensor.outdoor_temperature", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "battery", + "font_size": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font_size": null + } + ] + }, + { + "id": "b4", + "x": -1, + "y": 1, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] + } +} diff --git a/docs/protocol/fixtures/layouts/invalid/invalid_font_size.json b/docs/protocol/fixtures/layouts/invalid/invalid_font_size.json new file mode 100644 index 0000000..c5ea2a8 --- /dev/null +++ b/docs/protocol/fixtures/layouts/invalid/invalid_font_size.json @@ -0,0 +1,85 @@ +{ + "expect": { + "code": "invalid_font_size", + "ref": "b2" + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "light.kitchen" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "background": "#C94F3D", + "font_size": "xxl", + "type": "entity", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font_size": null + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "👋", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "sensor.outdoor_temperature", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "battery", + "font_size": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font_size": null + } + ] + }, + { + "id": "b4", + "x": -1, + "y": 1, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] + } +} diff --git a/docs/protocol/fixtures/layouts/invalid/invalid_id.json b/docs/protocol/fixtures/layouts/invalid/invalid_id.json new file mode 100644 index 0000000..82916a0 --- /dev/null +++ b/docs/protocol/fixtures/layouts/invalid/invalid_id.json @@ -0,0 +1,85 @@ +{ + "expect": { + "code": "invalid_id", + "ref": "B4" + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "light.kitchen" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "background": "#C94F3D", + "font_size": "m", + "type": "entity", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font_size": null + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "👋", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "sensor.outdoor_temperature", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "battery", + "font_size": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font_size": null + } + ] + }, + { + "id": "B4", + "x": -1, + "y": 1, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] + } +} diff --git a/docs/protocol/fixtures/layouts/invalid/invalid_item.json b/docs/protocol/fixtures/layouts/invalid/invalid_item.json new file mode 100644 index 0000000..aa38cd8 --- /dev/null +++ b/docs/protocol/fixtures/layouts/invalid/invalid_item.json @@ -0,0 +1,85 @@ +{ + "expect": { + "code": "invalid_item", + "ref": "i4" + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "light.kitchen" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "background": "#C94F3D", + "font_size": "m", + "type": "entity", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font_size": null + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "👋", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "sensor.outdoor_temperature", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "image", + "font_size": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font_size": null + } + ] + }, + { + "id": "b4", + "x": -1, + "y": 1, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] + } +} diff --git a/docs/protocol/fixtures/layouts/invalid/invalid_name-astral.json b/docs/protocol/fixtures/layouts/invalid/invalid_name-astral.json new file mode 100644 index 0000000..99bd713 --- /dev/null +++ b/docs/protocol/fixtures/layouts/invalid/invalid_name-astral.json @@ -0,0 +1,32 @@ +{ + "expect": { + "code": "invalid_name", + "ref": "b1" + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋", + "font_size": null + } + ] + } + ] + } +} diff --git a/docs/protocol/fixtures/layouts/invalid/invalid_name.json b/docs/protocol/fixtures/layouts/invalid/invalid_name.json new file mode 100644 index 0000000..a3b6402 --- /dev/null +++ b/docs/protocol/fixtures/layouts/invalid/invalid_name.json @@ -0,0 +1,85 @@ +{ + "expect": { + "code": "invalid_name", + "ref": "b2" + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "light.kitchen" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": " ", + "background": "#C94F3D", + "font_size": "m", + "type": "entity", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font_size": null + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "👋", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "sensor.outdoor_temperature", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "battery", + "font_size": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font_size": null + } + ] + }, + { + "id": "b4", + "x": -1, + "y": 1, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] + } +} diff --git a/docs/protocol/fixtures/layouts/invalid/invalid_sleep_timeout.json b/docs/protocol/fixtures/layouts/invalid/invalid_sleep_timeout.json new file mode 100644 index 0000000..2576ad1 --- /dev/null +++ b/docs/protocol/fixtures/layouts/invalid/invalid_sleep_timeout.json @@ -0,0 +1,85 @@ +{ + "expect": { + "code": "invalid_sleep_timeout", + "ref": null + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 3 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "light.kitchen" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "background": "#C94F3D", + "font_size": "m", + "type": "entity", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font_size": null + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "👋", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "sensor.outdoor_temperature", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "battery", + "font_size": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font_size": null + } + ] + }, + { + "id": "b4", + "x": -1, + "y": 1, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] + } +} diff --git a/docs/protocol/fixtures/layouts/invalid/invalid_start-empty.json b/docs/protocol/fixtures/layouts/invalid/invalid_start-empty.json new file mode 100644 index 0000000..01d9e95 --- /dev/null +++ b/docs/protocol/fixtures/layouts/invalid/invalid_start-empty.json @@ -0,0 +1,14 @@ +{ + "expect": { + "code": "invalid_start", + "ref": null + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [] + } +} diff --git a/docs/protocol/fixtures/layouts/invalid/invalid_start.json b/docs/protocol/fixtures/layouts/invalid/invalid_start.json new file mode 100644 index 0000000..eeeb16d --- /dev/null +++ b/docs/protocol/fixtures/layouts/invalid/invalid_start.json @@ -0,0 +1,85 @@ +{ + "expect": { + "code": "invalid_start", + "ref": null + }, + "layout": { + "version": 1, + "start": "zz", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "light.kitchen" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "background": "#C94F3D", + "font_size": "m", + "type": "entity", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font_size": null + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "👋", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "sensor.outdoor_temperature", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "battery", + "font_size": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font_size": null + } + ] + }, + { + "id": "b4", + "x": -1, + "y": 1, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] + } +} diff --git a/docs/protocol/fixtures/layouts/invalid/invalid_structure-settings.json b/docs/protocol/fixtures/layouts/invalid/invalid_structure-settings.json new file mode 100644 index 0000000..8cbe925 --- /dev/null +++ b/docs/protocol/fixtures/layouts/invalid/invalid_structure-settings.json @@ -0,0 +1,83 @@ +{ + "expect": { + "code": "invalid_structure", + "ref": null + }, + "layout": { + "version": 1, + "start": "b1", + "settings": 20, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "light.kitchen" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "background": "#C94F3D", + "font_size": "m", + "type": "entity", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font_size": null + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "👋", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "sensor.outdoor_temperature", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "battery", + "font_size": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font_size": null + } + ] + }, + { + "id": "b4", + "x": -1, + "y": 1, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] + } +} diff --git a/docs/protocol/fixtures/layouts/invalid/invalid_structure-version.json b/docs/protocol/fixtures/layouts/invalid/invalid_structure-version.json new file mode 100644 index 0000000..4192b9c --- /dev/null +++ b/docs/protocol/fixtures/layouts/invalid/invalid_structure-version.json @@ -0,0 +1,85 @@ +{ + "expect": { + "code": "invalid_structure", + "ref": null + }, + "layout": { + "version": 2, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "light.kitchen" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "background": "#C94F3D", + "font_size": "m", + "type": "entity", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font_size": null + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "👋", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "sensor.outdoor_temperature", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "battery", + "font_size": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font_size": null + } + ] + }, + { + "id": "b4", + "x": -1, + "y": 1, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] + } +} diff --git a/docs/protocol/fixtures/layouts/invalid/invalid_structure.json b/docs/protocol/fixtures/layouts/invalid/invalid_structure.json new file mode 100644 index 0000000..f48243b --- /dev/null +++ b/docs/protocol/fixtures/layouts/invalid/invalid_structure.json @@ -0,0 +1,14 @@ +{ + "expect": { + "code": "invalid_structure", + "ref": null + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": {} + } +} diff --git a/docs/protocol/fixtures/layouts/invalid/invalid_text.json b/docs/protocol/fixtures/layouts/invalid/invalid_text.json new file mode 100644 index 0000000..a0a169e --- /dev/null +++ b/docs/protocol/fixtures/layouts/invalid/invalid_text.json @@ -0,0 +1,85 @@ +{ + "expect": { + "code": "invalid_text", + "ref": "i1" + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "light.kitchen" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "background": "#C94F3D", + "font_size": "m", + "type": "entity", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "font_size": null + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "👋", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "sensor.outdoor_temperature", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "battery", + "font_size": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font_size": null + } + ] + }, + { + "id": "b4", + "x": -1, + "y": 1, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] + } +} diff --git a/docs/protocol/fixtures/layouts/invalid/invalid_type.json b/docs/protocol/fixtures/layouts/invalid/invalid_type.json new file mode 100644 index 0000000..1201756 --- /dev/null +++ b/docs/protocol/fixtures/layouts/invalid/invalid_type.json @@ -0,0 +1,85 @@ +{ + "expect": { + "code": "invalid_type", + "ref": "b2" + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "light.kitchen" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "background": "#C94F3D", + "font_size": "m", + "type": "gauge", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font_size": null + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "👋", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "sensor.outdoor_temperature", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "battery", + "font_size": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font_size": null + } + ] + }, + { + "id": "b4", + "x": -1, + "y": 1, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] + } +} diff --git a/docs/protocol/fixtures/layouts/invalid/too_many_blocks.json b/docs/protocol/fixtures/layouts/invalid/too_many_blocks.json new file mode 100644 index 0000000..04c7dba --- /dev/null +++ b/docs/protocol/fixtures/layouts/invalid/too_many_blocks.json @@ -0,0 +1,345 @@ +{ + "expect": { + "code": "too_many_blocks", + "ref": null + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Block 1", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b2", + "x": 1, + "y": 0, + "name": "Block 2", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b3", + "x": 2, + "y": 0, + "name": "Block 3", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b4", + "x": 3, + "y": 0, + "name": "Block 4", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b5", + "x": 4, + "y": 0, + "name": "Block 5", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b6", + "x": 5, + "y": 0, + "name": "Block 6", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b7", + "x": 6, + "y": 0, + "name": "Block 7", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b8", + "x": 7, + "y": 0, + "name": "Block 8", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b9", + "x": 8, + "y": 0, + "name": "Block 9", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b10", + "x": 9, + "y": 0, + "name": "Block 10", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b11", + "x": 10, + "y": 0, + "name": "Block 11", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b12", + "x": 11, + "y": 0, + "name": "Block 12", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b13", + "x": 12, + "y": 0, + "name": "Block 13", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b14", + "x": 13, + "y": 0, + "name": "Block 14", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b15", + "x": 14, + "y": 0, + "name": "Block 15", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b16", + "x": 15, + "y": 0, + "name": "Block 16", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b17", + "x": 16, + "y": 0, + "name": "Block 17", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b18", + "x": 17, + "y": 0, + "name": "Block 18", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b19", + "x": 18, + "y": 0, + "name": "Block 19", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b20", + "x": 19, + "y": 0, + "name": "Block 20", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b21", + "x": 20, + "y": 0, + "name": "Block 21", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b22", + "x": 21, + "y": 0, + "name": "Block 22", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b23", + "x": 22, + "y": 0, + "name": "Block 23", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b24", + "x": 23, + "y": 0, + "name": "Block 24", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b25", + "x": 24, + "y": 0, + "name": "Block 25", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b26", + "x": 25, + "y": 0, + "name": "Block 26", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b27", + "x": 26, + "y": 0, + "name": "Block 27", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b28", + "x": 27, + "y": 0, + "name": "Block 28", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b29", + "x": 28, + "y": 0, + "name": "Block 29", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b30", + "x": 29, + "y": 0, + "name": "Block 30", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b31", + "x": 30, + "y": 0, + "name": "Block 31", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b32", + "x": 31, + "y": 0, + "name": "Block 32", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + }, + { + "id": "b33", + "x": 32, + "y": 0, + "name": "Block 33", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [] + } + ] + } +} diff --git a/docs/protocol/fixtures/layouts/invalid/too_many_items.json b/docs/protocol/fixtures/layouts/invalid/too_many_items.json new file mode 100644 index 0000000..9e9391a --- /dev/null +++ b/docs/protocol/fixtures/layouts/invalid/too_many_items.json @@ -0,0 +1,97 @@ +{ + "expect": { + "code": "too_many_items", + "ref": "b3" + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "light.kitchen" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "background": "#C94F3D", + "font_size": "m", + "type": "entity", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font_size": null + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "👋", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "sensor.outdoor_temperature", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "battery", + "font_size": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font_size": null + }, + { + "id": "i6", + "kind": "text", + "text": "A", + "font_size": null + }, + { + "id": "i7", + "kind": "text", + "text": "B", + "font_size": null + } + ] + }, + { + "id": "b4", + "x": -1, + "y": 1, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] + } +} diff --git a/docs/protocol/fixtures/layouts/invalid/unsupported_emoji.json b/docs/protocol/fixtures/layouts/invalid/unsupported_emoji.json new file mode 100644 index 0000000..7a673ce --- /dev/null +++ b/docs/protocol/fixtures/layouts/invalid/unsupported_emoji.json @@ -0,0 +1,85 @@ +{ + "expect": { + "code": "unsupported_emoji", + "ref": "i2" + }, + "layout": { + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "light.kitchen" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "background": "#C94F3D", + "font_size": "m", + "type": "entity", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font_size": null + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "🦄", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "sensor.outdoor_temperature", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "battery", + "font_size": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font_size": null + } + ] + }, + { + "id": "b4", + "x": -1, + "y": 1, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] + } +} diff --git a/docs/protocol/fixtures/layouts/valid/astral-text.json b/docs/protocol/fixtures/layouts/valid/astral-text.json new file mode 100644 index 0000000..2ab4436 --- /dev/null +++ b/docs/protocol/fixtures/layouts/valid/astral-text.json @@ -0,0 +1,26 @@ +{ + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡💡", + "background": "#000000", + "font_size": "m", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋👋", + "font_size": null + } + ] + } + ] +} diff --git a/docs/protocol/fixtures/layouts/valid/emoji-variation.json b/docs/protocol/fixtures/layouts/valid/emoji-variation.json new file mode 100644 index 0000000..7eb8b85 --- /dev/null +++ b/docs/protocol/fixtures/layouts/valid/emoji-variation.json @@ -0,0 +1,26 @@ +{ + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 3600 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Snow", + "background": "#FFFFFF", + "font_size": "xl", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "emoji", + "emoji": "❄️", + "font_size": null + } + ] + } + ] +} diff --git a/docs/protocol/fixtures/layouts/valid/empty.json b/docs/protocol/fixtures/layouts/valid/empty.json new file mode 100644 index 0000000..3cd8f9c --- /dev/null +++ b/docs/protocol/fixtures/layouts/valid/empty.json @@ -0,0 +1,8 @@ +{ + "version": 1, + "start": null, + "settings": { + "sleep_timeout": 20 + }, + "blocks": [] +} diff --git a/docs/protocol/fixtures/layouts/valid/reference.json b/docs/protocol/fixtures/layouts/valid/reference.json new file mode 100644 index 0000000..2ebd691 --- /dev/null +++ b/docs/protocol/fixtures/layouts/valid/reference.json @@ -0,0 +1,79 @@ +{ + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 20 + }, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "background": "#5B9E4D", + "font_size": "m", + "type": "entity", + "entity_id": "light.kitchen" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "background": "#C94F3D", + "font_size": "m", + "type": "entity", + "entity_id": "light.living_room" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "background": "#4F86DD", + "font_size": "l", + "type": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font_size": null + }, + { + "id": "i2", + "kind": "emoji", + "emoji": "👋", + "font_size": "xl" + }, + { + "id": "i3", + "kind": "entity", + "entity_id": "sensor.outdoor_temperature", + "attribute": null, + "font_size": "s" + }, + { + "id": "i4", + "kind": "battery", + "font_size": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font_size": null + } + ] + }, + { + "id": "b4", + "x": -1, + "y": 1, + "name": "Bedroom", + "background": "#7B2FA0", + "font_size": "m", + "type": "entity", + "entity_id": "climate.bedroom" + } + ] +} diff --git a/docs/protocol/fixtures/layouts/valid/single.json b/docs/protocol/fixtures/layouts/valid/single.json new file mode 100644 index 0000000..aabeba2 --- /dev/null +++ b/docs/protocol/fixtures/layouts/valid/single.json @@ -0,0 +1,19 @@ +{ + "version": 1, + "start": "b1", + "settings": { + "sleep_timeout": 0 + }, + "blocks": [ + { + "id": "b1", + "x": 3, + "y": -2, + "name": "Solo", + "background": "#000000", + "font_size": "s", + "type": "custom", + "items": [] + } + ] +} diff --git a/docs/protocol/fixtures/payloads/invalid/bad_json-array.json b/docs/protocol/fixtures/payloads/invalid/bad_json-array.json new file mode 100644 index 0000000..2ae4a97 --- /dev/null +++ b/docs/protocol/fixtures/payloads/invalid/bad_json-array.json @@ -0,0 +1,4 @@ +{ + "expect": "bad_json", + "text": "[1,2]" +} diff --git a/docs/protocol/fixtures/payloads/invalid/bad_json.json b/docs/protocol/fixtures/payloads/invalid/bad_json.json new file mode 100644 index 0000000..02556ae --- /dev/null +++ b/docs/protocol/fixtures/payloads/invalid/bad_json.json @@ -0,0 +1,4 @@ +{ + "expect": "bad_json", + "text": "{\"v\":1," +} diff --git a/docs/protocol/fixtures/payloads/invalid/invalid_payload-sleep.json b/docs/protocol/fixtures/payloads/invalid/invalid_payload-sleep.json new file mode 100644 index 0000000..37b3dee --- /dev/null +++ b/docs/protocol/fixtures/payloads/invalid/invalid_payload-sleep.json @@ -0,0 +1,4 @@ +{ + "expect": "invalid_payload", + "text": "{\"v\":1,\"rev\":\"x\",\"start\":null,\"sleep\":-1,\"blocks\":[]}" +} diff --git a/docs/protocol/fixtures/payloads/invalid/invalid_payload-widget.json b/docs/protocol/fixtures/payloads/invalid/invalid_payload-widget.json new file mode 100644 index 0000000..a8c6e7c --- /dev/null +++ b/docs/protocol/fixtures/payloads/invalid/invalid_payload-widget.json @@ -0,0 +1,4 @@ +{ + "expect": "invalid_payload", + "text": "{\"v\":1,\"rev\":\"x\",\"start\":\"b1\",\"sleep\":20,\"blocks\":[{\"id\":\"b1\",\"x\":0,\"y\":0,\"name\":\"A\",\"bg\":\"000000\",\"font\":\"m\",\"widget\":\"gauge\"}]}" +} diff --git a/docs/protocol/fixtures/payloads/invalid/invalid_payload.json b/docs/protocol/fixtures/payloads/invalid/invalid_payload.json new file mode 100644 index 0000000..d94e132 --- /dev/null +++ b/docs/protocol/fixtures/payloads/invalid/invalid_payload.json @@ -0,0 +1,4 @@ +{ + "expect": "invalid_payload", + "text": "{\"v\":1,\"rev\":\"x\",\"start\":\"b1\",\"blocks\":[{\"id\":\"b1\"}]}" +} diff --git a/docs/protocol/fixtures/payloads/invalid/unsupported_version.json b/docs/protocol/fixtures/payloads/invalid/unsupported_version.json new file mode 100644 index 0000000..ba34385 --- /dev/null +++ b/docs/protocol/fixtures/payloads/invalid/unsupported_version.json @@ -0,0 +1,4 @@ +{ + "expect": "unsupported_version", + "text": "{\"v\":2,\"rev\":\"x\",\"start\":null,\"blocks\":[]}" +} diff --git a/docs/protocol/fixtures/payloads/valid/emoji-variation.json b/docs/protocol/fixtures/payloads/valid/emoji-variation.json new file mode 100644 index 0000000..953dec4 --- /dev/null +++ b/docs/protocol/fixtures/payloads/valid/emoji-variation.json @@ -0,0 +1,28 @@ +{ + "layout": "emoji-variation", + "payload": { + "v": 1, + "rev": "5387d4ea", + "start": "b1", + "sleep": 3600, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Snow", + "bg": "FFFFFF", + "font": "xl", + "widget": "custom", + "items": [ + { + "id": "i1", + "kind": "emoji", + "text": "❄", + "font": "xl" + } + ] + } + ] + } +} diff --git a/docs/protocol/fixtures/payloads/valid/empty.json b/docs/protocol/fixtures/payloads/valid/empty.json new file mode 100644 index 0000000..3a4e6b8 --- /dev/null +++ b/docs/protocol/fixtures/payloads/valid/empty.json @@ -0,0 +1,10 @@ +{ + "layout": "empty", + "payload": { + "v": 1, + "rev": "c4aad3fa", + "start": null, + "sleep": 20, + "blocks": [] + } +} diff --git a/docs/protocol/fixtures/payloads/valid/reference.json b/docs/protocol/fixtures/payloads/valid/reference.json new file mode 100644 index 0000000..a9f0752 --- /dev/null +++ b/docs/protocol/fixtures/payloads/valid/reference.json @@ -0,0 +1,76 @@ +{ + "layout": "reference", + "payload": { + "v": 1, + "rev": "90538742", + "start": "b1", + "sleep": 20, + "blocks": [ + { + "id": "b1", + "x": 0, + "y": 0, + "name": "Kitchen", + "bg": "5B9E4D", + "font": "m", + "widget": "light" + }, + { + "id": "b2", + "x": 0, + "y": -1, + "name": "Lights", + "bg": "C94F3D", + "font": "m", + "widget": "light" + }, + { + "id": "b3", + "x": -1, + "y": 0, + "name": "Hello World", + "bg": "4F86DD", + "font": "l", + "widget": "custom", + "items": [ + { + "id": "i1", + "kind": "text", + "text": "Hello World", + "font": "l" + }, + { + "id": "i2", + "kind": "emoji", + "text": "👋", + "font": "xl" + }, + { + "id": "i3", + "kind": "entity", + "font": "s" + }, + { + "id": "i4", + "kind": "battery", + "font": "s" + }, + { + "id": "i5", + "kind": "brightness", + "font": "l" + } + ] + }, + { + "id": "b4", + "x": -1, + "y": 1, + "name": "Bedroom", + "bg": "7B2FA0", + "font": "m", + "widget": "climate" + } + ] + } +} diff --git a/docs/protocol/fixtures/states/all-missing.json b/docs/protocol/fixtures/states/all-missing.json new file mode 100644 index 0000000..df191af --- /dev/null +++ b/docs/protocol/fixtures/states/all-missing.json @@ -0,0 +1,24 @@ +{ + "layout": "reference", + "unit": "°C", + "entity_ids": null, + "hass_states": {}, + "updates": [ + { + "id": "b1", + "available": false + }, + { + "id": "b2", + "available": false + }, + { + "id": "i3", + "text": "—" + }, + { + "id": "b4", + "available": false + } + ] +} diff --git a/docs/protocol/fixtures/states/climate-defaults.json b/docs/protocol/fixtures/states/climate-defaults.json new file mode 100644 index 0000000..e0941ce --- /dev/null +++ b/docs/protocol/fixtures/states/climate-defaults.json @@ -0,0 +1,29 @@ +{ + "layout": "reference", + "unit": "°C", + "entity_ids": [ + "climate.bedroom" + ], + "hass_states": { + "climate.bedroom": { + "state": "off", + "attributes": { + "temperature": null, + "current_temperature": null + } + } + }, + "updates": [ + { + "id": "b4", + "available": true, + "target": null, + "min": 7, + "max": 35, + "step": 0.5, + "unit": "°C", + "current": "—", + "action": "Off" + } + ] +} diff --git a/docs/protocol/fixtures/states/climate-heating.json b/docs/protocol/fixtures/states/climate-heating.json new file mode 100644 index 0000000..c4fa0ce --- /dev/null +++ b/docs/protocol/fixtures/states/climate-heating.json @@ -0,0 +1,33 @@ +{ + "layout": "reference", + "unit": "°C", + "entity_ids": [ + "climate.bedroom" + ], + "hass_states": { + "climate.bedroom": { + "state": "heat", + "attributes": { + "temperature": 20.5, + "current_temperature": 19.8, + "min_temp": 7, + "max_temp": 35, + "target_temp_step": 0.5, + "hvac_action": "heating" + } + } + }, + "updates": [ + { + "id": "b4", + "available": true, + "target": 20.5, + "min": 7, + "max": 35, + "step": 0.5, + "unit": "°C", + "current": "19.8 °C", + "action": "Heating" + } + ] +} diff --git a/docs/protocol/fixtures/states/entity-missing.json b/docs/protocol/fixtures/states/entity-missing.json new file mode 100644 index 0000000..3d3ec18 --- /dev/null +++ b/docs/protocol/fixtures/states/entity-missing.json @@ -0,0 +1,14 @@ +{ + "layout": "reference", + "unit": "°C", + "entity_ids": [ + "sensor.outdoor_temperature" + ], + "hass_states": {}, + "updates": [ + { + "id": "i3", + "text": "—" + } + ] +} diff --git a/docs/protocol/fixtures/states/entity-precision.json b/docs/protocol/fixtures/states/entity-precision.json new file mode 100644 index 0000000..c89b542 --- /dev/null +++ b/docs/protocol/fixtures/states/entity-precision.json @@ -0,0 +1,28 @@ +{ + "layout": "reference", + "unit": "°C", + "entity_ids": [ + "sensor.outdoor_temperature" + ], + "hass_states": { + "sensor.outdoor_temperature": { + "state": "12.345", + "attributes": { + "unit_of_measurement": "°C" + } + } + }, + "registry_options": { + "sensor.outdoor_temperature": { + "sensor": { + "display_precision": 1 + } + } + }, + "updates": [ + { + "id": "i3", + "text": "12.3 °C" + } + ] +} diff --git a/docs/protocol/fixtures/states/light-dimmable-off.json b/docs/protocol/fixtures/states/light-dimmable-off.json new file mode 100644 index 0000000..ee2aa57 --- /dev/null +++ b/docs/protocol/fixtures/states/light-dimmable-off.json @@ -0,0 +1,25 @@ +{ + "layout": "reference", + "unit": "°C", + "entity_ids": [ + "light.living_room" + ], + "hass_states": { + "light.living_room": { + "state": "off", + "attributes": { + "supported_color_modes": [ + "color_temp" + ] + } + } + }, + "updates": [ + { + "id": "b2", + "available": true, + "on": false, + "brightness": 0 + } + ] +} diff --git a/docs/protocol/fixtures/states/light-dimmable-on.json b/docs/protocol/fixtures/states/light-dimmable-on.json new file mode 100644 index 0000000..9a99452 --- /dev/null +++ b/docs/protocol/fixtures/states/light-dimmable-on.json @@ -0,0 +1,26 @@ +{ + "layout": "reference", + "unit": "°C", + "entity_ids": [ + "light.kitchen" + ], + "hass_states": { + "light.kitchen": { + "state": "on", + "attributes": { + "brightness": 128, + "supported_color_modes": [ + "brightness" + ] + } + } + }, + "updates": [ + { + "id": "b1", + "available": true, + "on": true, + "brightness": 50 + } + ] +} diff --git a/docs/protocol/fixtures/states/light-onoff.json b/docs/protocol/fixtures/states/light-onoff.json new file mode 100644 index 0000000..24d35da --- /dev/null +++ b/docs/protocol/fixtures/states/light-onoff.json @@ -0,0 +1,25 @@ +{ + "layout": "reference", + "unit": "°C", + "entity_ids": [ + "light.kitchen" + ], + "hass_states": { + "light.kitchen": { + "state": "on", + "attributes": { + "supported_color_modes": [ + "onoff" + ] + } + } + }, + "updates": [ + { + "id": "b1", + "available": true, + "on": true, + "brightness": null + } + ] +} diff --git a/docs/protocol/fixtures/states/light-unavailable.json b/docs/protocol/fixtures/states/light-unavailable.json new file mode 100644 index 0000000..a24b34d --- /dev/null +++ b/docs/protocol/fixtures/states/light-unavailable.json @@ -0,0 +1,19 @@ +{ + "layout": "reference", + "unit": "°C", + "entity_ids": [ + "light.kitchen" + ], + "hass_states": { + "light.kitchen": { + "state": "unavailable", + "attributes": {} + } + }, + "updates": [ + { + "id": "b1", + "available": false + } + ] +} diff --git a/docs/releasing.md b/docs/releasing.md new file mode 100644 index 0000000..476a16a --- /dev/null +++ b/docs/releasing.md @@ -0,0 +1,25 @@ +# Releasing + +## One-time setup + +- Settings > Pages > Source: "GitHub Actions". +- Settings > Environments > `github-pages` > Deployment branches and tags: add a tag rule `v*`. By default the environment only accepts the default branch, so the `pages` job of a tag run would be rejected. +- Set the repository description and topics, which HACS requires. + +## Steps + +1. Set the version everywhere: `.github/scripts/.venv/bin/python .github/scripts/versioning.py bump X.Y.Z`. +2. Commit it: `git commit -am "chore: release X.Y.Z"`. +3. Tag and push: `git tag vX.Y.Z && git push origin main vX.Y.Z`. +4. Watch the "Release" workflow. +5. Check that the Pages installer shows X.Y.Z and that HACS offers X.Y.Z. + +The workflow builds the panel, packages `ha_controller.zip`, compiles the firmware, rebuilds and deploys the GitHub Pages site with the new firmware and every earlier released firmware, and only then creates the GitHub release with the zip and the firmware files. Pages is deployed before the release so that the `firmware//ha-controller.ota.bin` URLs already exist when HACS offers the new version; otherwise the first automatic update would get a 404. + +## Dry runs + +Run the "Release" workflow with `workflow_dispatch`. Only the `build` job runs, and it uploads a `dist` artifact without creating a release. + +## Stable OTA URLs + +Installed integrations download `firmware//ha-controller.ota.bin` from the Pages site. Never change this layout. diff --git a/docs/superpowers/plans/2026-11-16-ha-controller-1-foundation.md b/docs/superpowers/plans/2026-11-16-ha-controller-1-foundation.md new file mode 100644 index 0000000..015086d --- /dev/null +++ b/docs/superpowers/plans/2026-11-16-ha-controller-1-foundation.md @@ -0,0 +1,337 @@ +# HA Controller — Plan 1: Foundation & Protocol Contract + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Set up the repository conventions, the documentation skeleton and the Claude Code guidance. Then write the cross-language protocol contract that plans 2–5 build on: the protocol doc, the emoji list and the shared fixtures. + +**Architecture:** Documentation and data only, plus Python tests that keep the docs linked and the fixtures well formed. The fixtures are the executable contract: plan 2 (Python), plan 3 (TypeScript) and plan 4 (C++) all test against them. + +**Tech Stack:** Markdown, JSON, Python 3.14, pytest, ruff, GitHub Actions. + +**Spec:** `docs/superpowers/specs/2026-11-16-ha-controller-design.md` + +## Global Constraints + +- Everything is written in English: code, comments, docs, UI strings and commit messages. +- Repository `pyxel-dev/HA-controller`. Product name "HA Controller". Integration domain `ha_controller`. ESPHome project `pyxel-dev.ha-controller`. +- Python 3.14, pytest, ruff. The repository checks run in their own venv `.github/scripts/.venv`, installed from `.github/scripts/requirements.txt`. +- Layout model and protocol v1 exactly as spec §6–§7. Golden revisions: `c4aad3fa` (empty), `90538742` (reference), `5387d4ea` (emoji-variation). +- `3D_models/` and `files/` stay untouched. + +## Review Focus + +1. **Invalid fixtures that break more than one rule.** Plans 2–3 would then pass for the wrong reason. Each invalid fixture is the reference layout (or `single`/`empty`) plus exactly one mutation. Plans 2 and 3 assert the full error list equals exactly the one expected error. +2. **Emoji entries the firmware cannot render.** This means multi-code-point sequences: U+FE0F, ZWJ, skin tones. `test_emoji_list_is_well_formed` asserts one code point per entry. +3. **Non-UTF-8 or BOM-prefixed fixture files** (they hold `°`, `—` and emoji). `test_all_fixtures_are_utf8_json` rejects them. +4. **A golden `rev` that drifts from the canonical hash.** `test_payload_revisions_match_canonical_hash` recomputes it. +5. **Docs linking to files that do not exist yet.** Later plans add docs. `test_relative_links_resolve` keeps every relative link valid at each commit. + +--- + +### Task 1: Repository conventions, docs skeleton and CI + +**Files:** +- Create: `.claude/CLAUDE.md`, `docs/README.md`, `docs/architecture.md`, `.github/scripts/pyproject.toml`, `.github/scripts/requirements.txt`, `.github/scripts/tests/__init__.py`, `.github/scripts/tests/test_docs_links.py`, `.github/workflows/ci.yml` +- Modify: `README.md` (rewrite in English), `.gitignore` + +**Interfaces:** +- Produces: + - `.github/scripts/pyproject.toml` with `[tool.pytest.ini_options] testpaths = ["tests"]` and `[tool.ruff] target-version = "py314"`, `line-length = 100`, lint rules `E,F,I,UP,B`. + - `.github/scripts/requirements.txt` (`pytest`, `ruff`) for the repository checks. Plan 2 gives the integration its own test requirements under `custom_components/`. + - `.github/workflows/ci.yml` with a single job `repo-checks`. Later plans add jobs. + - The repository root keeps no files except `README.md`, `hacs.json` (plan 2) and `.gitignore`. + - `docs/README.md` as the docs index. Later plans add links. + - `.claude/CLAUDE.md` with a `## Commands` table and a `## Skills and agents` section. Later plans append rows. + +- [ ] **Step 1: Write the failing tests** in `.github/scripts/tests/test_docs_links.py`. + +```python +DOC_ROOTS = ["README.md", ".claude/CLAUDE.md", "docs"] # docs/superpowers/** is excluded + +def test_relative_links_resolve(): + # For every markdown link [text](target) whose target does not start with + # http://, https://, mailto: or '#': strip the '#anchor' and assert + # (md_file.parent / target).resolve().exists(); report every broken link. + ... + +def test_docs_index_lists_every_doc(): + # Every docs/*.md file except docs/README.md is linked from docs/README.md. + ... +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `pytest .github/scripts/tests -v` +Expected: FAIL (`docs/README.md` is missing). + +- [ ] **Step 3: Write the docs and config** + - **`README.md`:** + - Keep the title "HA Controller". + - One paragraph pitch, then feature bullets: + - block map editor in Home Assistant; + - edge-swipe navigation; + - light and thermostat knobs; + - custom blocks; + - automatic firmware updates. + - Status line "Under active development". + - Relative link `docs/README.md`. + - Keep the 3D-models section and fix its link to `3D_models/`. + - **`docs/README.md`:** title "HA Controller documentation", one bullet per doc (`architecture.md` for now) and a link to the design spec under `superpowers/specs/`. + - **`docs/architecture.md`:** spec §3 rewritten for contributors. Include the diagram, the subsystems and the repository layout table, plus one paragraph each on: + - the hello → layout/states handshake; + - controls → service calls; + - firmware updates. + - **`.claude/CLAUDE.md`:** + - Title "HA Controller — guidance for Claude Code" and a two-line purpose. + - `## Rules`: + - English only. + - One version for the whole repo; change it only with `python .github/scripts/versioning.py bump X.Y.Z` (added in plan 5). + - The protocol is defined in `docs/protocol/README.md` and pinned by `docs/protocol/fixtures/`. + - TDD. + - Never commit `esphome/secrets.yaml`. + - Specs and plans live in `docs/superpowers/`. + - `## Repository map`: the spec §3 table. + - `## Commands`: `pytest .github/scripts/tests`, `ruff check .github/scripts`. + - `## Skills and agents`: empty list. + - **`.gitignore`:** keep `.DS_Store`. Add `__pycache__/`, `.pytest_cache/`, `.ruff_cache/`, `.venv*/`, `node_modules/`, `custom_components/ha_controller/frontend/coverage/`, `.superpowers/`, `esphome/.esphome/`, `esphome/secrets.yaml`, `build/`, `dist/`, `site/`. + +- [ ] **Step 4: Run the tests and lint** + +Run: `pytest .github/scripts/tests -v && ruff check .github/scripts` +Expected: PASS, no lint findings. + +- [ ] **Step 5: Add CI.** In `.github/workflows/ci.yml`, workflow `CI`: + - Triggers: `push` to `main` and `pull_request`. + - Job `repo-checks` on `ubuntu-latest`: `actions/checkout@v4`, `actions/setup-python@v5` with `python-version: "3.14"`, `pip install -r .github/scripts/requirements.txt`, `ruff check .github/scripts`, `pytest .github/scripts/tests`. + +- [ ] **Step 6: Commit** + +```bash +git add README.md .claude/CLAUDE.md docs/README.md docs/architecture.md .github/scripts .gitignore .github/workflows/ci.yml +git commit -m "chore: add repository conventions, docs skeleton and CI" +``` + +--- + +### Task 2: Protocol contract — protocol doc, emoji list, fixtures and Claude guidance + +**Files:** +- Create: + - `docs/protocol/README.md`, `docs/protocol/README.md`, `custom_components/ha_controller/emoji.json` + - `docs/protocol/fixtures/**` (see the tables below) + - `.github/scripts/tests/__init__.py`, `.github/scripts/tests/test_protocol_fixtures.py` + - `.claude/skills/protocol-change/SKILL.md`, `.claude/agents/protocol-guardian.md` +- Modify: `docs/README.md` (link `protocol.md`), `.claude/CLAUDE.md` (skills and agents list) + +**Interfaces:** +- Produces (consumed by plans 2, 3 and 4). All fixture files are UTF-8 JSON without a BOM. + - `custom_components/ha_controller/emoji.json`: a JSON array of the 64 strings below, in this order: + `💡 🔥 ❄ 🌡 💧 🌬 ☀ 🌙 ⭐ ☁ ⛅ 🌧 ⚡ 🔋 🔌 🏠 🛋 🛏 🛁 🚿 🍳 🍽 ☕ 🍷 🧺 🪴 🚪 🪟 🔒 🔓 🔑 🔔 🔕 🔊 🔇 🎵 📺 🎮 💻 📱 ⏰ 📅 🚗 🚲 🐶 🐱 👶 👋 👍 ❤ 😀 😴 🎉 🎄 ✅ ❌ ⚠ ℹ ▶ ⏸ ♻ 🌀 🧊 🏡` + - `docs/protocol/fixtures/layouts/valid/.json`: a stored layout. + - `docs/protocol/fixtures/layouts/invalid/.json`: `{"expect": {"code": str, "ref": str | null}, "layout": {...}}`. The stem equals `code` or starts with `code-`. + - `docs/protocol/fixtures/payloads/valid/.json`: `{"layout": "", "payload": {...}}`. + - `docs/protocol/fixtures/payloads/invalid/.json`: `{"expect": "bad_json" | "unsupported_version" | "invalid_payload", "text": ""}`. + - `docs/protocol/fixtures/states/.json`: + + ```json + { + "layout": "reference", + "unit": "°C", + "entity_ids": ["…"] | null, + "hass_states": {"": {"state": "…", "attributes": {}}}, + "registry_options": {"": {}}, + "updates": [] + } + ``` + + `registry_options` is optional; `updates` lists the expected update objects. + - `docs/protocol/fixtures/controls/.json`: `{"layout": "reference", "hass_states": {...}, "event": {"block", "item", "op", "value"}, "expect_call": {"domain", "service", "data"} | null}`. + - `docs/protocol/fixtures/colors.json`: `[{"bg": "#RRGGBB", "text": "#000000" | "#FFFFFF"}]`. + +- [ ] **Step 1: Write the failing tests** in `.github/scripts/tests/test_protocol_fixtures.py`. Local helpers: `canonical_rev(payload) -> str` and `luminance(hex) -> float` (spec §5.5/§7.3). + +```python +def test_emoji_list_is_well_formed(): + emoji = json.loads(EMOJI.read_text("utf-8")) + assert len(emoji) == 64 and len(set(emoji)) == 64 + assert all(len(e) == 1 for e in emoji) # one code point each + assert "️" not in "".join(emoji) + assert {"💡", "🔋", "⚡", "☀", "👋"} <= set(emoji) and "🦄" not in emoji + +def test_all_fixtures_are_utf8_json(): ... # every docs/protocol/fixtures/**/*.json: no BOM, json.loads ok + +def test_invalid_layout_fixtures_declare_known_codes(): + # expect.code in the 18 codes of spec §6 except payload_too_large + # expect.ref is str or None; stem == code or stem.startswith(code + "-") + +def test_payload_revisions_match_canonical_hash(): + revs = {p.stem: json.loads(p.read_text("utf-8"))["payload"]["rev"] for p in VALID_PAYLOADS} + assert revs == {"empty": "c4aad3fa", "reference": "90538742", "emoji-variation": "5387d4ea"} + # and canonical_rev(payload) == payload["rev"] for each file + +def test_fixtures_reference_existing_layouts(): ... # "layout" fields of payloads/states/controls exist in layouts/valid + +def test_color_fixture_matches_luminance_rule(): + for case in COLORS: + assert case["text"] == ("#000000" if luminance(case["bg"]) > 0.30 else "#FFFFFF") +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `pytest .github/scripts/tests -v` +Expected: FAIL (the files are missing). + +- [ ] **Step 3: Write `emoji.json` and the fixtures.** + +**Valid layouts:** +- **`empty.json`:** `{"version": 1, "start": null, "settings": {"sleep_timeout": 20}, "blocks": []}`. +- **`reference.json`:** the JSON of spec §6, verbatim (it includes `"settings": {"sleep_timeout": 20}`). +- **`single.json`:** `{"version": 1, "start": "b1", "settings": {"sleep_timeout": 0}, "blocks": [{"id": "b1", "x": 3, "y": -2, "name": "Solo", "background": "#000000", "font_size": "s", "type": "custom", "items": []}]}`. +- **`emoji-variation.json`:** `{"version": 1, "start": "b1", "settings": {"sleep_timeout": 3600}, "blocks": [{"id": "b1", "x": 0, "y": 0, "name": "Snow", "background": "#FFFFFF", "font_size": "xl", "type": "custom", "items": [{"id": "i1", "kind": "emoji", "emoji": "❄️", "font_size": null}]}]}`. The emoji is U+2744 followed by U+FE0F. + +**Invalid layouts.** Each is a single mutation of the base layout: + +| File | Base | Mutation | expect | +|---|---|---|---| +| `invalid_structure.json` | reference | `"blocks": {}` | `invalid_structure`, `null` | +| `invalid_structure-version.json` | reference | `"version": 2` | `invalid_structure`, `null` | +| `invalid_structure-settings.json` | reference | `"settings": 20` | `invalid_structure`, `null` | +| `too_many_blocks.json` | — | 33 blocks: block N is `{"id": "bN", "x": N-1, "y": 0, "name": "Block N", "background": "#000000", "font_size": "m", "type": "custom", "items": []}` for N = 1…33, start `b1`, `"settings": {"sleep_timeout": 20}` | `too_many_blocks`, `null` | +| `invalid_sleep_timeout.json` | reference | `"settings": {"sleep_timeout": 3}` | `invalid_sleep_timeout`, `null` | +| `invalid_id.json` | reference | b4 id → `"B4"` | `invalid_id`, `"B4"` | +| `duplicate_id.json` | reference | item i5 id → `"b1"` | `duplicate_id`, `"b1"` | +| `coordinate_out_of_range.json` | single | b1 `x: 33` | `coordinate_out_of_range`, `"b1"` | +| `duplicate_position.json` | reference | b4 → `x: 0, y: 0` | `duplicate_position`, `"b4"` | +| `invalid_start.json` | reference | `"start": "zz"` | `invalid_start`, `null` | +| `invalid_start-empty.json` | empty | `"start": "b1"` | `invalid_start`, `null` | +| `disconnected.json` | reference | b4 → `y: 2` | `disconnected`, `"b4"` | +| `invalid_name.json` | reference | b2 name → `" "` | `invalid_name`, `"b2"` | +| `invalid_background.json` | reference | b2 background → `"red"` | `invalid_background`, `"b2"` | +| `invalid_font_size.json` | reference | b2 font_size → `"xxl"` | `invalid_font_size`, `"b2"` | +| `invalid_font_size-item.json` | reference | i1 font_size → `"huge"` | `invalid_font_size`, `"i1"` | +| `invalid_type.json` | reference | b2 type → `"gauge"` | `invalid_type`, `"b2"` | +| `invalid_entity.json` | reference | b1 entity_id → `"switch.kettle"` | `invalid_entity`, `"b1"` | +| `invalid_entity-item.json` | reference | i3 entity_id → `"not an entity"` | `invalid_entity`, `"i3"` | +| `too_many_items.json` | reference | b3 items + `{"id": "i6", "kind": "text", "text": "A", "font_size": null}`, `{"id": "i7", …"B"…}` | `too_many_items`, `"b3"` | +| `invalid_item.json` | reference | i4 kind → `"image"` | `invalid_item`, `"i4"` | +| `invalid_text.json` | reference | i1 text → 65 × `"a"` | `invalid_text`, `"i1"` | +| `unsupported_emoji.json` | reference | i2 emoji → `"🦄"` | `unsupported_emoji`, `"i2"` | + +**Valid payloads.** Write each `payload` by hand from spec §7.3: +- **`empty.json`:** layout `empty`, payload `{"v": 1, "rev": "c4aad3fa", "start": null, "sleep": 20, "blocks": []}`. +- **`reference.json`:** layout `reference`, payload: + +```json +{"v": 1, "rev": "90538742", "start": "b1", "sleep": 20, "blocks": [ + {"id": "b1", "x": 0, "y": 0, "name": "Kitchen", "bg": "5B9E4D", "font": "m", "widget": "light"}, + {"id": "b2", "x": 0, "y": -1, "name": "Lights", "bg": "C94F3D", "font": "m", "widget": "light"}, + {"id": "b3", "x": -1, "y": 0, "name": "Hello World", "bg": "4F86DD", "font": "l", "widget": "custom", "items": [ + {"id": "i1", "kind": "text", "text": "Hello World", "font": "l"}, + {"id": "i2", "kind": "emoji", "text": "👋", "font": "xl"}, + {"id": "i3", "kind": "entity", "font": "s"}, + {"id": "i4", "kind": "battery", "font": "s"}, + {"id": "i5", "kind": "brightness", "font": "l"}]}, + {"id": "b4", "x": -1, "y": 1, "name": "Bedroom", "bg": "7B2FA0", "font": "m", "widget": "climate"}]} +``` + +- **`emoji-variation.json`:** layout `emoji-variation`, payload `{"v": 1, "rev": "5387d4ea", "start": "b1", "sleep": 3600, "blocks": [{"id": "b1", "x": 0, "y": 0, "name": "Snow", "bg": "FFFFFF", "font": "xl", "widget": "custom", "items": [{"id": "i1", "kind": "emoji", "text": "❄", "font": "xl"}]}]}`. + +**Invalid payloads** (`text` values): + +| File | text | expect | +|---|---|---| +| `bad_json.json` | `{"v":1,` | `bad_json` | +| `bad_json-array.json` | `[1,2]` | `bad_json` | +| `unsupported_version.json` | `{"v":2,"rev":"x","start":null,"blocks":[]}` | `unsupported_version` | +| `invalid_payload.json` | `{"v":1,"rev":"x","start":"b1","blocks":[{"id":"b1"}]}` | `invalid_payload` | +| `invalid_payload-widget.json` | `{"v":1,"rev":"x","start":"b1","sleep":20,"blocks":[{"id":"b1","x":0,"y":0,"name":"A","bg":"000000","font":"m","widget":"gauge"}]}` | `invalid_payload` | +| `invalid_payload-sleep.json` | `{"v":1,"rev":"x","start":null,"sleep":-1,"blocks":[]}` | `invalid_payload` | + +**States.** All use layout `reference` and unit `°C`: + +| File | entity_ids | hass_states | updates | +|---|---|---|---| +| `light-dimmable-on.json` | `["light.kitchen"]` | `light.kitchen`: `on`, `{"brightness": 128, "supported_color_modes": ["brightness"]}` | `[{"id": "b1", "available": true, "on": true, "brightness": 50}]` | +| `light-dimmable-off.json` | `["light.living_room"]` | `light.living_room`: `off`, `{"supported_color_modes": ["color_temp"]}` | `[{"id": "b2", "available": true, "on": false, "brightness": 0}]` | +| `light-onoff.json` | `["light.kitchen"]` | `on`, `{"supported_color_modes": ["onoff"]}` | `[{"id": "b1", "available": true, "on": true, "brightness": null}]` | +| `light-unavailable.json` | `["light.kitchen"]` | `unavailable`, `{}` | `[{"id": "b1", "available": false}]` | +| `climate-heating.json` | `["climate.bedroom"]` | `heat`, `{"temperature": 20.5, "current_temperature": 19.8, "min_temp": 7, "max_temp": 35, "target_temp_step": 0.5, "hvac_action": "heating"}` | `[{"id": "b4", "available": true, "target": 20.5, "min": 7, "max": 35, "step": 0.5, "unit": "°C", "current": "19.8 °C", "action": "Heating"}]` | +| `climate-defaults.json` | `["climate.bedroom"]` | `off`, `{"temperature": null, "current_temperature": null}` | `[{"id": "b4", "available": true, "target": null, "min": 7, "max": 35, "step": 0.5, "unit": "°C", "current": "—", "action": "Off"}]` | +| `entity-precision.json` | `["sensor.outdoor_temperature"]` | `"12.345"`, `{"unit_of_measurement": "°C"}`; registry_options `{"sensor.outdoor_temperature": {"sensor": {"display_precision": 1}}}` | `[{"id": "i3", "text": "12.3 °C"}]` | +| `entity-missing.json` | `["sensor.outdoor_temperature"]` | `{}` | `[{"id": "i3", "text": "—"}]` | +| `all-missing.json` | `null` | `{}` | `[{"id": "b1", "available": false}, {"id": "b2", "available": false}, {"id": "i3", "text": "—"}, {"id": "b4", "available": false}]` | + +**Controls.** All use layout `reference`. `item` is `""` everywhere: + +| File | hass_states | event (block, op, value) | expect_call | +|---|---|---|---| +| `light-toggle.json` | `{}` | `b1`, `toggle`, `"0.00"` | `light.toggle` `{"entity_id": "light.kitchen"}` | +| `light-set.json` | `{}` | `b1`, `set`, `"42.40"` | `light.turn_on` `{"entity_id": "light.kitchen", "brightness_pct": 42}` | +| `light-set-zero.json` | `{}` | `b1`, `set`, `"0.00"` | `light.turn_off` `{"entity_id": "light.kitchen"}` | +| `light-set-over.json` | `{}` | `b2`, `set`, `"150"` | `light.turn_on` `{"entity_id": "light.living_room", "brightness_pct": 100}` | +| `climate-set.json` | `climate.bedroom`: `heat`, `{"min_temp": 7, "max_temp": 35}` | `b4`, `set`, `"21.50"` | `climate.set_temperature` `{"entity_id": "climate.bedroom", "temperature": 21.5}` | +| `climate-clamp.json` | same as above | `b4`, `set`, `"50.00"` | `climate.set_temperature` `{"entity_id": "climate.bedroom", "temperature": 35}` | +| `ignored-unknown-block.json` | `{}` | `zz`, `set`, `"1"` | `null` | +| `ignored-custom-block.json` | `{}` | `b3`, `set`, `"1"` | `null` | +| `ignored-bad-value.json` | `{}` | `b1`, `set`, `"abc"` | `null` | +| `ignored-climate-toggle.json` | `{}` | `b4`, `toggle`, `"0.00"` | `null` | + +**`colors.json`:** + +| bg | text | +|---|---| +| `#FFFFFF` | `#000000` | +| `#000000` | `#FFFFFF` | +| `#5B9E4D` | `#FFFFFF` | +| `#4F86DD` | `#FFFFFF` | +| `#C94F3D` | `#FFFFFF` | +| `#7B2FA0` | `#FFFFFF` | +| `#F1C40F` | `#000000` | +| `#9E9E9E` | `#000000` | +| `#8C8C8C` | `#FFFFFF` | + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `pytest .github/scripts/tests -v` +Expected: PASS. + +- [ ] **Step 5: Write the protocol doc and guidance** + - **`docs/protocol/README.md`:** spec §6 and §7, verbatim, under the heading "Device protocol v1". Add a closing "Fixtures" section with the relative link `../protocol/README.md`. + - **`docs/protocol/README.md`:** + - Who reads each fixture folder: pytest in `custom_components/ha_controller/tests`, vitest in `custom_components/ha_controller/frontend/test`, doctest in `esphome/tests`. + - The rule "one broken rule per invalid fixture". + - The canonical-revision snippet: + + ```python + hashlib.sha256(json.dumps(p, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()).hexdigest()[:8] + ``` + - **`.claude/skills/protocol-change/SKILL.md`:** + - Frontmatter `name: protocol-change`. + - `description:` "Use when changing anything that crosses the Home Assistant ↔ screen boundary: layout fields, validation rules, payload keys, state update fields, events, actions, emoji list or limits." + - Body, a numbered checklist: + 1. Classify the change. The C++ parser rejects unknown `widget`/`kind`/`font` values, so any new value is breaking: bump `PROTOCOL_VERSION` in `custom_components/ha_controller/const.py` and in the firmware's `ha_controller.h`. + 2. Edit `docs/protocol/README.md` first. + 3. Update `docs/protocol/fixtures/`, keeping one rule per invalid fixture and regenerating golden `rev` values with the snippet. + 4. Update the Python code (`layout.py`, `compiler.py`, `states.py`, `controls.py`), the TypeScript model (`custom_components/ha_controller/frontend/src/model/`), the C++ parsers (`esphome/components/ha_controller/layout.*`, `states.*`) and the renderers (`widgets.*`, panel editor). + 5. Run `pytest custom_components/ha_controller/tests`, `pytest .github/scripts/tests`, `npm --prefix custom_components/ha_controller/frontend test`, the host C++ tests and `esphome compile`. + 6. Ask the `protocol-guardian` agent to review. + - **`.claude/agents/protocol-guardian.md`:** + - Frontmatter `name: protocol-guardian`, `tools: Read, Grep, Glob, Bash`. + - `description:` "Reviews a diff for consistency of the HA ↔ screen protocol across docs/protocol/README.md, docs/protocol/fixtures, the integration (Python), the panel model (TypeScript) and the firmware parsers (C++). Use after any protocol-related change and before merging." + - Body: + - A checklist: field names, error codes, limits and constants identical in all places; fixtures updated; golden revs recomputed; `PROTOCOL_VERSION` bumped on breaking changes; docs updated. + - Output: a list of `file:line — inconsistency — fix`, or "Protocol consistent". + - **`docs/README.md`:** add a `protocol.md` bullet. + - **`.claude/CLAUDE.md`:** list the skill and the agent under `## Skills and agents`. + +- [ ] **Step 6: Run the whole suite** + +Run: `pytest .github/scripts/tests -v && ruff check .github/scripts` +Expected: PASS. + +- [ ] **Step 7: Commit** + +```bash +git add docs/protocol docs/README.md custom_components/ha_controller/emoji.json .github/scripts/tests .claude .claude/CLAUDE.md +git commit -m "feat(protocol): add protocol v1 contract, shared fixtures and guidance" +``` diff --git a/docs/superpowers/plans/2026-11-16-ha-controller-2-integration.md b/docs/superpowers/plans/2026-11-16-ha-controller-2-integration.md new file mode 100644 index 0000000..9ddbedb --- /dev/null +++ b/docs/superpowers/plans/2026-11-16-ha-controller-2-integration.md @@ -0,0 +1,596 @@ +# HA Controller — Plan 2: Home Assistant Integration + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Build the `ha_controller` custom integration: config flow, layout validation and compilation, state builders, the sync engine that talks to the screen through ESPHome actions and events, control mapping, the websocket API and the sidebar panel registration. + +**Architecture:** +- **Pure modules:** `layout.py`, `compiler.py`, `states.py` and `controls.py` hold the protocol logic. They are tested against `docs/protocol/fixtures/`. +- **`ScreenController`:** one per config entry. It wires those modules to Home Assistant: storage, event listeners filtered by `device_id`, entity tracking, and calls to the screen's `esphome._` services. +- **`websocket.py` and `panel.py`:** expose the controller to the panel built in plan 3. + +**Tech Stack:** Python 3.14, Home Assistant ≥ 2026.10, `pytest-homeassistant-custom-component==0.13.375` (pins Home Assistant 2026.10.4), ruff, Pillow (brand icon script only). + +**Spec:** `docs/superpowers/specs/2026-11-16-ha-controller-design.md` (§6–§8, §15) + +## Global Constraints + +- Domain `ha_controller`, name "HA Controller", `MANUFACTURER = "pyxel-dev"`, `MODEL = "ha-controller"`. +- Minimum Home Assistant 2026.10.0. Python 3.14. +- **Python environment:** the integration has its own venv `custom_components/.venv`. Create it with `python3.14 -m venv custom_components/.venv`, install `custom_components/requirements_test.txt`, and run pytest and ruff from it. The repository checks keep their own venv, `.github/scripts/.venv`. +- Protocol v1 and constants exactly as spec §6, §7 and §15, defined once in `const.py`. +- Events: `esphome.ha_controller_hello` and `esphome.ha_controller_control`. Services: `esphome._`. The integration never registers its own services. +- No blocking I/O in the event loop. Read `emoji.json` with `hass.async_add_executor_job`. +- Time comparisons use `homeassistant.util.dt.utcnow()`, so tests can drive them with `freezer`. +- All user-facing strings are in English. + +## Review Focus + +1. **Screen reboot, Home Assistant restart or Wi-Fi drop.** The layout and states resync with no user action: hello `connected` → states; revision `none` → layout + states. A screen that keeps rejecting a layout gets at most one push per 300 s. Owner: Task 5 tests. +2. **An entity that is missing, unavailable or renamed.** Updates mark it unavailable, controls for it are ignored, and a failing service call never raises. Owner: Task 4 fixtures, Task 6 `test_service_error_is_swallowed`. +3. **Several screens configured.** A hello or control from one screen never affects another. Owner: Task 5 `test_hello_from_other_device_is_ignored`, Task 6 `test_control_from_other_device_is_ignored`. +4. **Saving while the screen is offline.** The save succeeds with `pushed: false` and no exception, and the next hello delivers the layout. Owner: Task 5 `test_save_layout_offline_returns_not_pushed`. +5. **A stored layout that no longer validates** (hand-edited storage, future downgrade). Setup must not fail; the controller uses an empty layout and logs a warning. Owner: Task 5 `test_invalid_stored_layout_falls_back_to_empty`. + +--- + +### Task 1: Integration skeleton and config flow + +**Files:** +- Create: + - `custom_components/ha_controller/`: `__init__.py`, `const.py`, `config_flow.py`, `manifest.json`, `strings.json`, `translations/en.json`, `brand/icon.png`, `brand/icon@2x.png` + - `.github/scripts/make_brand_icon.py`, `hacs.json` + - `custom_components/ha_controller/tests/conftest.py`, `custom_components/ha_controller/tests/__init__.py`, `custom_components/ha_controller/tests/helpers.py`, `custom_components/ha_controller/tests/test_config_flow.py` + - `.github/workflows/validate.yml` + - `custom_components/pyproject.toml`, `custom_components/requirements_test.txt`, `custom_components/__init__.py` (empty) +- Modify: `.github/scripts/requirements.txt` (add `pillow`), `.github/workflows/ci.yml` (job `integration`), `.claude/CLAUDE.md` (commands) + +**Interfaces:** +- Produces: + - **`const.py`:** + - Identity and limits: `DOMAIN`, `MANUFACTURER`, `MODEL`, `CONF_DEVICE_ID = "device_id"`, `CONF_AUTO_UPDATE = "auto_update"`, `PROTOCOL_VERSION = 1`. + - Events and actions: `EVENT_HELLO = "esphome.ha_controller_hello"`, `EVENT_CONTROL = "esphome.ha_controller_control"`, `ACTION_SET_LAYOUT = "set_layout"`, `ACTION_SET_STATES = "set_states"`, `ACTION_INSTALL_FIRMWARE = "install_firmware"`. + - Layout limits: `MAX_BLOCKS = 32`, `MAX_ITEMS = 6`, `MAX_NAME_LEN = 32`, `MAX_TEXT_LEN = 64`, `COORD_LIMIT = 32`, `MAX_PAYLOAD_BYTES = 24576`, `STATE_CHUNK_BYTES = 8192`. + - Allowed values: `FONT_SIZES = ("s", "m", "l", "xl")`, `ENTITY_BLOCK_DOMAINS = ("light", "climate")`, `ITEM_KINDS = ("text", "emoji", "entity", "battery", "brightness")`. + - Screen sleep (seconds, `0` = never): `DEFAULT_SLEEP_TIMEOUT = 20`, `MIN_SLEEP_TIMEOUT = 5`, `MAX_SLEEP_TIMEOUT = 3600`. + - Timings: `ONLINE_TIMEOUT = timedelta(seconds=150)`, `PUSH_RETRY = timedelta(seconds=300)`, `STATE_COALESCE_SECONDS = 0.2`, `INSTALL_TIMEOUT = 300`, `AUTO_UPDATE_RETRY = timedelta(seconds=3600)`. + - Panel: `PANEL_URL_PATH = "ha-controller"`, `PANEL_COMPONENT = "ha-controller-panel"`, `PANEL_TITLE = "HA Controller"`, `PANEL_ICON = "mdi:remote"`, `STATIC_URL = "/ha_controller_static"`. + - Release URLs: `FIRMWARE_BASE_URL = "https://pyxel-dev.github.io/HA-controller/firmware"`, `RELEASE_URL = "https://github.com/pyxel-dev/HA-controller/releases/tag/v{version}"`. + - **`custom_components/ha_controller/tests/helpers.py`:** + - `async def register_screen(hass, *, name="HA Controller", manufacturer=MANUFACTURER, model=MODEL, mac="aa:bb:cc:dd:ee:ff") -> dr.DeviceEntry`. It adds an `esphome` `MockConfigEntry` and a device with `connections={(dr.CONNECTION_NETWORK_MAC, mac)}`. + - `async def setup_screen(hass, device) -> MockConfigEntry`. It adds the `ha_controller` entry with `data={"device_id": device.id}` and `unique_id=device.id`, sets it up, and waits. + - `NODE = "ha-controller-aabbcc"`. + - `def hello(device, **overrides) -> dict`: a default hello for `NODE`, version `"0.1.0"`, protocol `"1"`, revision `"none"`, reason `"connected"`. + - `def load_fixture(*parts) -> Any`: reads `docs/protocol/fixtures/...`. + +- [ ] **Step 1: Write the failing tests** in `custom_components/ha_controller/tests/test_config_flow.py`, plus `custom_components/ha_controller/tests/conftest.py` with an autouse `auto_enable_custom_integrations(enable_custom_integrations)` fixture. + +```python +async def test_user_step_shows_device_selector(hass): ... # form, step_id "user", errors {} +async def test_user_step_creates_entry(hass): + device = await register_screen(hass) + result = await start_flow_and_submit(hass, {"device_id": device.id}) + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["title"] == "HA Controller" and result["data"] == {"device_id": device.id} + assert result["result"].unique_id == device.id +async def test_user_step_rejects_other_device(hass): # model="other" → errors {"base": "not_ha_controller"} +async def test_user_step_aborts_when_already_configured(hass): # reason "already_configured" +async def test_setup_and_unload_entry(hass): # LOADED, then NOT_LOADED +async def test_strings_match_english_translation(): # strings.json == translations/en.json +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `pip install -r custom_components/requirements_test.txt && pytest custom_components/ha_controller/tests/test_config_flow.py -v` +Expected: FAIL (`ModuleNotFoundError` / integration not found). + +- [ ] **Step 3: Implement the skeleton.** + - **`custom_components/requirements_test.txt`:** `pytest-homeassistant-custom-component==0.13.375`, `ruff`. + - **`custom_components/pyproject.toml`:** + - `[tool.pytest.ini_options]`: `testpaths = ["ha_controller/tests"]`, `pythonpath = [".."]`, `asyncio_mode = "auto"`, `asyncio_default_fixture_loop_scope = "function"`. + - `[tool.ruff]`: `target-version = "py314"`, `line-length = 100`, lint rules `E,F,I,UP,B`. + - **`custom_components/__init__.py`:** empty. pytest then imports the tests as `custom_components.ha_controller.tests.*`, so the integration is never imported a second time under the name `ha_controller`. Tests import the integration only as `custom_components.ha_controller`. + - **`.github/scripts/requirements.txt`:** add `pillow`, for the brand icon script. + - **`manifest.json`**, keys in hassfest order: + + ```json + { + "domain": "ha_controller", + "name": "HA Controller", + "after_dependencies": ["esphome"], + "codeowners": ["@pyxel-dev"], + "config_flow": true, + "dependencies": ["frontend", "http", "panel_custom", "websocket_api"], + "documentation": "https://github.com/pyxel-dev/HA-controller/tree/main/docs", + "integration_type": "device", + "iot_class": "local_push", + "issue_tracker": "https://github.com/pyxel-dev/HA-controller/issues", + "requirements": [], + "version": "0.1.0" + } + ``` + + - **`__init__.py`:** + - `CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN)`. + - `async_setup` returns `True`. + - `async_setup_entry` and `async_unload_entry` return `True`; they are filled in Task 5. + - **`config_flow.py`:** `HaControllerConfigFlow(ConfigFlow, domain=DOMAIN)`, `VERSION = 1`, with step `user`: + - The schema has one field, `vol.Required(CONF_DEVICE_ID)`: + + ```python + selector.DeviceSelector(selector.DeviceSelectorConfig(filter=[ + selector.DeviceFilterSelectorConfig(integration="esphome", manufacturer=MANUFACTURER, model=MODEL) + ])) + ``` + + - On submit, accept the device only if it exists, belongs to a config entry of domain `esphome`, and has `manufacturer == MANUFACTURER` and `model == MODEL`. Otherwise set error `not_ha_controller`. + - Then `async_set_unique_id(device.id)`, `_abort_if_unique_id_configured()`, and create the entry with title `device.name_by_user or device.name`. + - **`strings.json` = `translations/en.json`:** + - User step: title "Add an HA Controller screen"; description "Pick the screen. It must already be added to Home Assistant with the ESPHome integration."; field `device_id` "Screen". + - Error: `not_ha_controller` "This device is not an HA Controller screen." + - Abort: `already_configured` "This screen is already set up." + - **`hacs.json`:** `{"name": "HA Controller", "homeassistant": "2026.10.0"}`. + - **`.github/scripts/make_brand_icon.py`:** a Pillow script that writes `brand/icon.png` (256×256) and `brand/icon@2x.png` (512×512), scaled from a 512 design: + - transparent background; + - a filled circle `#111827` with radius 240; + - a ring `#374151`, width 36, radius 170; + - an arc `#F59E0B`, width 36, radius 170, from 135° to 315°; + - a centre dot `#F9FAFB` with radius 40. + + Run it once and commit both PNGs. + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `pytest custom_components/ha_controller/tests/test_config_flow.py -v && ruff check custom_components` +Expected: PASS. + +- [ ] **Step 5: Add CI.** + - Add job `integration` to `.github/workflows/ci.yml`: setup-python 3.14, `pip install -r custom_components/requirements_test.txt`, `ruff check custom_components`, `pytest custom_components/ha_controller/tests`. + - Create `.github/workflows/validate.yml`: + - Triggers: `push`, `pull_request`, `schedule` (`cron: "0 0 * * *"`) and `workflow_dispatch`. + - Job `hassfest`: checkout, then `home-assistant/actions/hassfest@master`. + - Job `hacs`: `hacs/action@main` with `category: integration`. + - If HACS reports the repository description or topics checks, the owner sets them once on GitHub. Description: "Home Assistant remote on the Waveshare ESP32-S3 1.75\" round AMOLED". Topics: `home-assistant`, `hacs`, `esphome`, `integration`. + - Add to the `.claude/CLAUDE.md` commands: `pytest custom_components/ha_controller/tests` and `python .github/scripts/make_brand_icon.py`. + +- [ ] **Step 6: Commit** + +```bash +git add custom_components/ha_controller .github/scripts/make_brand_icon.py hacs.json custom_components/requirements_test.txt custom_components/pyproject.toml custom_components/__init__.py .github/scripts/requirements.txt .github/workflows/ci.yml .github/workflows/validate.yml .claude/CLAUDE.md +git commit -m "feat(integration): add integration skeleton and config flow" +``` + +--- + +### Task 2: Layout validation + +**Files:** +- Create: `custom_components/ha_controller/layout.py`, `custom_components/ha_controller/tests/test_layout.py` + +**Interfaces:** +- Produces: + - `class LayoutError(NamedTuple): code: str; ref: str | None` + - `def validate_layout(layout: Any, emoji: frozenset[str]) -> list[LayoutError]` + - `def empty_layout() -> dict[str, Any]`, which returns `{"version": 1, "start": None, "settings": {"sleep_timeout": DEFAULT_SLEEP_TIMEOUT}, "blocks": []}` + - `def normalize_emoji(text: str) -> str`, which removes U+FE0F + - `def bound_entities(layout: dict) -> dict[str, list[str]]`: entity_id → binding ids (block ids for entity blocks, item ids for entity items), in layout order + - `def load_emoji_file(path: Path) -> frozenset[str]` (sync) and `async def async_load_emoji(hass) -> frozenset[str]` + +- [ ] **Step 1: Write the failing tests** + +```python +@pytest.mark.parametrize("path", sorted(VALID_LAYOUTS), ids=stem) +def test_valid_fixtures(path): assert validate_layout(load(path), EMOJI) == [] + +@pytest.mark.parametrize("path", sorted(INVALID_LAYOUTS), ids=stem) +def test_invalid_fixtures(path): + case = load(path) + assert validate_layout(case["layout"], EMOJI) == [LayoutError(case["expect"]["code"], case["expect"]["ref"])] + +def test_connectivity_is_skipped_when_fields_are_invalid(): ... # disconnected block + bad name → only invalid_name +def test_normalize_emoji_strips_variation_selector(): assert normalize_emoji("❄️") == "❄" +def test_bound_entities_reference(): + assert bound_entities(load_layout("reference")) == { + "light.kitchen": ["b1"], "light.living_room": ["b2"], + "sensor.outdoor_temperature": ["i3"], "climate.bedroom": ["b4"]} +def test_bool_is_not_a_coordinate(): ... # x = True → coordinate_out_of_range +@pytest.mark.parametrize("value,ok", [(0, True), (5, True), (3600, True), (4, False), (3601, False), (True, False), ("20", False)]) +def test_sleep_timeout_bounds(value, ok): ... # reference with settings.sleep_timeout = value → [] or [LayoutError("invalid_sleep_timeout", None)] +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `pytest custom_components/ha_controller/tests/test_layout.py -v` +Expected: FAIL (`ImportError`). + +- [ ] **Step 3: Implement `validate_layout`.** It runs in three phases, following spec §6. + - **Phase 1 — containers only.** Stop at the first error. The checks: + - the layout is a dict; + - `version == 1`; + - `settings` is a dict; + - `blocks` is a list of dicts; + - every block with `type == "custom"` has `items` as a list of dicts. + + Each failure produces `invalid_structure` with ref `None`. + - **Phase 2 — per field, all errors collected.** The checks run in this order: + 1. `too_many_blocks`, then `invalid_sleep_timeout`. `settings.sleep_timeout` must be an `int` that is not a `bool`, either `0` or within 5–3600. + 2. For each block: `invalid_id`, `duplicate_id`, `coordinate_out_of_range` (an `int` that is not a `bool`, within ±32), `duplicate_position`, `invalid_name`, `invalid_background`, `invalid_font_size`, `invalid_type`, then the type-specific checks. The type-specific checks are skipped when the type is invalid: + - entity blocks: `invalid_entity`; + - custom blocks: `too_many_items`, then for each item `invalid_id`, `duplicate_id`, `invalid_item`, `invalid_font_size`, and the kind-specific check (`invalid_text`, `unsupported_emoji` or `invalid_entity`). + 3. `invalid_start`, last. + + A field of the wrong JSON type yields that field's code. + - **Phase 3 — connectivity.** Runs only when phases 1–2 found nothing: a BFS from `start` over 4-neighbour cells. Each unreachable block yields `disconnected`, in layout order. + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `pytest custom_components/ha_controller/tests/test_layout.py -v` +Expected: PASS (all 4 valid and 23 invalid fixtures, plus the unit tests). + +- [ ] **Step 5: Commit** + +```bash +git add custom_components/ha_controller/layout.py custom_components/ha_controller/tests/test_layout.py +git commit -m "feat(integration): validate layouts against protocol rules" +``` + +--- + +### Task 3: Layout compiler + +**Files:** +- Create: `custom_components/ha_controller/compiler.py`, `custom_components/ha_controller/tests/test_compiler.py` + +**Interfaces:** +- Consumes: `normalize_emoji` (Task 2). +- Produces: + - `def compile_layout(layout: dict) -> dict`. It expects a valid layout and returns the payload with `rev` (spec §7.3). Names are trimmed. + - `def payload_revision(payload: dict) -> str`. It ignores any `rev` key. + - `def encode_payload(payload: dict) -> str`. Compact output, with `ensure_ascii=False`. + +- [ ] **Step 1: Write the failing tests** + +```python +@pytest.mark.parametrize("path", sorted(VALID_PAYLOADS), ids=stem) +def test_golden_payloads(path): + case = load(path) + assert compile_layout(load_layout(case["layout"])) == case["payload"] + +def test_revision_ignores_rev_key(): + assert payload_revision({"v": 1, "rev": "zzz", "start": None, "sleep": 20, "blocks": []}) == "c4aad3fa" +def test_encode_payload_is_compact_utf8(): + text = encode_payload(compile_layout(load_layout("reference"))) + assert ", " not in text and ": " not in text and "👋" in text +def test_huge_layout_exceeds_payload_limit(): + # 32 custom blocks in a row, each with 6 text items of 64 × "é" + assert len(encode_payload(compile_layout(huge)).encode()) > MAX_PAYLOAD_BYTES +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `pytest custom_components/ha_controller/tests/test_compiler.py -v` +Expected: FAIL. + +- [ ] **Step 3: Implement the three functions in `compiler.py`, following spec §7.3.** + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `pytest custom_components/ha_controller/tests/test_compiler.py -v` +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add custom_components/ha_controller/compiler.py custom_components/ha_controller/tests/test_compiler.py +git commit -m "feat(integration): compile layouts into device payloads" +``` + +--- + +### Task 4: State builders + +**Files:** +- Create: `custom_components/ha_controller/states.py`, `custom_components/ha_controller/tests/test_states.py` + +**Interfaces:** +- Produces: + - `def build_updates(hass, layout: dict, entity_ids: Collection[str] | None = None) -> list[dict]`. Returns updates in layout order (spec §7.4, §7.7); `None` means all bound entities. + - `def format_entity_text(hass, entity_id: str, attribute: str | None) -> str` + - `def chunk_updates(updates: list[dict], max_bytes: int = STATE_CHUNK_BYTES) -> list[str]`. Each chunk is an encoded JSON array of at most `max_bytes` bytes, unless a single update is larger; in that case it is sent alone. + +- [ ] **Step 1: Write the failing tests** + +```python +@pytest.mark.parametrize("path", sorted(STATE_FIXTURES), ids=stem) +async def test_state_fixtures(hass, path): + case = load(path) + hass.config.units = METRIC_SYSTEM + for entity_id, s in case["hass_states"].items(): + hass.states.async_set(entity_id, s["state"], s["attributes"]) + registry = er.async_get(hass) + for entity_id, options in case.get("registry_options", {}).items(): + domain, object_id = entity_id.split(".", 1) + entry = registry.async_get_or_create(domain, "test", object_id, suggested_object_id=object_id) + assert entry.entity_id == entity_id + for option_domain, value in options.items(): + registry.async_update_entity_options(entity_id, option_domain, value) + assert build_updates(hass, load_layout(case["layout"]), case["entity_ids"]) == case["updates"] + +async def test_entity_text_truncated_to_64(hass): ... # 100-char state → len == 64 +async def test_entity_text_uses_attribute(hass): ... # attribute "battery" = 80 → "80" +def test_chunk_updates_splits_by_size(): ... # 300 updates, max 8192 → every chunk ≤ 8192 and the union equals the input +def test_chunk_updates_keeps_oversize_update_alone(): ... +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `pytest custom_components/ha_controller/tests/test_states.py -v` +Expected: FAIL. + +- [ ] **Step 3: Implement the builders in `states.py`, following spec §7.7.** `—` is U+2014. The climate unit is `hass.config.units.temperature_unit`. + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `pytest custom_components/ha_controller/tests/test_states.py -v` +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add custom_components/ha_controller/states.py custom_components/ha_controller/tests/test_states.py +git commit -m "feat(integration): build screen state updates" +``` + +--- + +### Task 5: Layout store and ScreenController sync engine + +**Files:** +- Create: `custom_components/ha_controller/store.py`, `custom_components/ha_controller/controller.py`, `custom_components/ha_controller/tests/test_controller.py` +- Modify: `custom_components/ha_controller/__init__.py` + +**Interfaces:** +- Consumes: Tasks 2–4. +- Produces: + - **`class LayoutStore`:** `__init__(hass, entry_id)` with Home Assistant `Store` version 1 and key `f"{DOMAIN}.layout.{entry_id}"`, plus `async_load() -> dict | None`, `async_save(layout) -> None` and `async_remove() -> None`. + - **`@dataclass class DeviceStatus`:** fields `node`, `version`, `revision` (`str | None`), `protocol: int | None`, `last_seen: datetime | None`, and `def online(self) -> bool`, which compares `last_seen` with `utcnow()` and `ONLINE_TIMEOUT`. + - **`class InvalidLayout(HomeAssistantError)`:** attribute `errors: list[LayoutError]`. + - **`class ScreenController`:** + - `__init__(hass, entry, store, emoji: frozenset[str], integration_version: str)` + - properties: `device_id`, `layout`, `revision`, `device: DeviceStatus`, `integration_version` + - lifecycle: `async_start()` (load the layout, subscribe to the hello event, the control event and entity tracking) and `async_stop()` + - layout: `async_save_layout(layout) -> tuple[str, bool]`, returning `(revision, pushed)` + - sync: `async_handle_hello(data) -> None`, `async_push_layout() -> bool`, `async_push_states(entity_ids: Collection[str] | None = None) -> bool` + - `async_call_device(action: str, data: dict) -> bool` + - `status() -> dict`, shaped like one `ha_controller/screens` item (spec §8) + - `@callback async_add_listener(cb) -> CALLBACK_TYPE`, which notifies on every device status change + - **`__init__.py`:** `type HaControllerConfigEntry = ConfigEntry[ScreenController]`. `async_setup_entry` builds and starts the controller and stores it in `entry.runtime_data`. `async_unload_entry` stops it. `async_remove_entry` calls `LayoutStore.async_remove()`. + +- [ ] **Step 1: Write the failing tests.** Mock the screen's services with `async_mock_service(hass, "esphome", "ha_controller_aabbcc_set_layout")` and `async_mock_service(hass, "esphome", "ha_controller_aabbcc_set_states")`. Drive time with `freezer`, `async_fire_time_changed` and `async_block_till_done`. + +```python +async def test_hello_with_unknown_revision_pushes_layout_and_states(hass): ... + # saved reference layout, hello(revision="none", reason="heartbeat") + # → one set_layout call (json.loads(layout)["rev"] == "90538742"), then ≥1 set_states call +async def test_hello_connected_with_current_revision_pushes_states_only(hass): ... +async def test_heartbeat_with_current_revision_pushes_nothing(hass): ... +async def test_stale_revision_is_retried_at_most_every_300s(hass, freezer): ... + # heartbeat ×2 within 299 s → 1 push; after +301 s → 2 pushes; reason "connected" always pushes +async def test_hello_with_other_protocol_pushes_nothing(hass): ... # protocol "2" +async def test_hello_from_other_device_is_ignored(hass): ... # second screen registered; its hello leaves screen 1 untouched +async def test_state_changes_are_coalesced(hass): ... # 2 changes < 200 ms → one set_states with b1 and b2 +async def test_state_change_not_pushed_when_offline(hass, freezer): ... # last hello 151 s ago → no call +async def test_save_layout_pushes_when_online(hass): ... # returns ("90538742", True) +async def test_save_layout_offline_returns_not_pushed(hass): ... # no hello yet → ("90538742", False); still persisted +async def test_save_invalid_layout_raises(hass): ... # InvalidLayout, errors == [LayoutError("invalid_name", "b2")] +async def test_save_too_large_layout_raises_payload_too_large(hass): ... # errors == [LayoutError("payload_too_large", None)] +async def test_push_failure_is_logged_not_raised(hass, caplog): ... # set_layout service raises HomeAssistantError → False +async def test_invalid_stored_layout_falls_back_to_empty(hass, hass_storage): ... +async def test_layout_survives_reload(hass): ... +async def test_status_reports_device(hass): ... # status() fields after a hello +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `pytest custom_components/ha_controller/tests/test_controller.py -v` +Expected: FAIL. + +- [ ] **Step 3: Implement the controller, following spec §7.5.** + - **Hello and control events:** `hass.bus.async_listen(EVENT_…, handler, event_filter=…)`. The filter is a `@callback` that compares `event_data.get("device_id")` with the configured device id. + - **Entity tracking:** `async_track_state_change_event` over `bound_entities(layout)`. It is re-subscribed when the layout changes. + - **State coalescing:** a pending entity-id set, flushed by `async_call_later(hass, STATE_COALESCE_SECONDS, …)`. + - **Device calls:** `hass.services.async_call("esphome", f"{node.replace('-', '_')}_{action}", data, blocking=True)`. On `HomeAssistantError`, log a warning and return `False`. Return `False` when the node is unknown. + - **Push retry:** remember `(revision, utcnow())` of the last layout push. Skip a non-`connected` push of the same revision within `PUSH_RETRY`. + - **Saving a layout:** + 1. Validate, then compile and encode. If the encoded size exceeds `MAX_PAYLOAD_BYTES`, raise `InvalidLayout([LayoutError("payload_too_large", None)])`. + 2. Store the layout and re-track entities. + 3. Push if the screen is online with protocol 1, bypassing the retry limit. + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `pytest custom_components/ha_controller/tests -v` +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add custom_components/ha_controller custom_components/ha_controller/tests/test_controller.py +git commit -m "feat(integration): sync layouts and states with the screen" +``` + +--- + +### Task 6: Control events + +**Files:** +- Create: `custom_components/ha_controller/controls.py`, `custom_components/ha_controller/tests/test_controls.py` +- Modify: `custom_components/ha_controller/controller.py` + +**Interfaces:** +- Produces: + - `class ControlCall(NamedTuple): domain: str; service: str; data: dict` + - `def resolve_control(layout: dict, hass, data: Mapping[str, Any]) -> ControlCall | None` (spec §7.6). A non-finite or unparsable value returns `None`. + - `ScreenController.async_handle_control(data) -> None`, subscribed to `EVENT_CONTROL` in `async_start`. It calls the service with `blocking=True` and logs a `HomeAssistantError` instead of raising it. + +- [ ] **Step 1: Write the failing tests** + +```python +@pytest.mark.parametrize("path", sorted(CONTROL_FIXTURES), ids=stem) +async def test_control_fixtures(hass, path): + case = load(path) # set hass_states, then: + call = resolve_control(load_layout(case["layout"]), hass, case["event"]) + assert (call and call._asdict()) == case["expect_call"] # None ↔ null + +async def test_control_event_calls_service(hass): ... # fire EVENT_CONTROL with device_id → light.toggle mock receives entity_id light.kitchen +async def test_control_from_other_device_is_ignored(hass): ... +async def test_service_error_is_swallowed(hass, caplog): ... # registered light.turn_on raises HomeAssistantError → no exception, warning logged +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `pytest custom_components/ha_controller/tests/test_controls.py -v` +Expected: FAIL. + +- [ ] **Step 3: Implement `resolve_control` and the controller handler.** + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `pytest custom_components/ha_controller/tests -v` +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add custom_components/ha_controller custom_components/ha_controller/tests/test_controls.py +git commit -m "feat(integration): map screen controls to service calls" +``` + +--- + +### Task 7: Websocket API + +**Files:** +- Create: `custom_components/ha_controller/websocket.py`, `custom_components/ha_controller/tests/test_websocket.py` +- Modify: `custom_components/ha_controller/__init__.py` (call `async_register_websocket(hass)` in `async_setup`) + +**Interfaces:** +- Consumes: `ScreenController.status`, `.layout` and `.async_save_layout` (Task 5). +- Produces (used by plan 3): + - `ha_controller/screens` → `{"screens": [status, …]}`, covering loaded entries in title order. + - `ha_controller/layout/get` `{entry_id}` → `{"layout": layout}`. + - `ha_controller/layout/save` `{entry_id, layout}` → `{"revision": str, "pushed": bool}`. + - Errors: `not_found`, which happens when the entry is missing or not loaded; and `invalid_layout`, whose message is the `", "`-joined `f"{code}@{ref or ''}"` list. + - All three commands are admin-only: `@websocket_api.websocket_command`, then `@websocket_api.require_admin`, then `@websocket_api.async_response` for the save command or `@callback` for the others. + +- [ ] **Step 1: Write the failing tests** with `hass_ws_client` and `hass_admin_user`. + +```python +async def test_screens_lists_entries(hass, hass_ws_client): ... +async def test_layout_get_returns_stored_layout(hass, hass_ws_client): ... +async def test_layout_get_unknown_entry_returns_not_found(hass, hass_ws_client): ... +async def test_layout_save_valid(hass, hass_ws_client): ... # result {"revision": "90538742", "pushed": False} +async def test_layout_save_invalid(hass, hass_ws_client): ... # error code "invalid_layout", message "invalid_name@b2" +async def test_commands_require_admin(hass, hass_ws_client, hass_admin_user): ... # remove the admin group → error code "unauthorized" +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `pytest custom_components/ha_controller/tests/test_websocket.py -v` +Expected: FAIL. + +- [ ] **Step 3: Implement `websocket.py`.** + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `pytest custom_components/ha_controller/tests -v` +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add custom_components/ha_controller custom_components/ha_controller/tests/test_websocket.py +git commit -m "feat(integration): add websocket API for the panel" +``` + +--- + +### Task 8: Sidebar panel registration, developer docs and reviewer agent + +**Files:** +- Create: + - `custom_components/ha_controller/panel.py` + - `custom_components/ha_controller/tests/test_panel.py` + - `docs/development.md`, `.claude/agents/ha-integration-reviewer.md` +- Modify: `custom_components/ha_controller/__init__.py`, `docs/README.md`, `.claude/CLAUDE.md` + +**Interfaces:** +- Consumes: the plan 3 bundle path `custom_components/ha_controller/frontend/dist/ha-controller-panel.js`. +- Produces: + - `async def async_register_panel(hass, version: str) -> None`. It registers `StaticPathConfig(f"{STATIC_URL}/ha-controller-panel.js", /frontend/dist/ha-controller-panel.js, True)` once per Home Assistant run, guarded by a `hass.data` flag. This is a file route, so a missing bundle never breaks setup. If `PANEL_URL_PATH` is not already in `hass.data[frontend.DATA_PANELS]`, it registers the panel with: + + ```python + await panel_custom.async_register_panel( + hass, + frontend_url_path=PANEL_URL_PATH, + webcomponent_name=PANEL_COMPONENT, + sidebar_title=PANEL_TITLE, + sidebar_icon=PANEL_ICON, + module_url=f"{STATIC_URL}/ha-controller-panel.js?v={version}", + require_admin=True, + config={}, + ) + ``` + + It logs a warning when the bundle file is missing. + - `@callback def async_unregister_panel(hass) -> None`, which calls `frontend.async_remove_panel(hass, PANEL_URL_PATH, warn_if_unknown=False)`. `async_unload_entry` calls it only when no other `ha_controller` entry is still loaded. + +- [ ] **Step 1: Write the failing tests** + +```python +async def test_panel_registered_on_setup(hass): ... # "ha-controller" in hass.data[frontend.DATA_PANELS], require_admin True +async def test_panel_kept_while_another_entry_is_loaded(hass): ... +async def test_panel_removed_when_last_entry_unloaded(hass): ... +async def test_static_path_registered_once(hass): ... # patch hass.http.async_register_static_paths → awaited once for two entries +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `pytest custom_components/ha_controller/tests/test_panel.py -v` +Expected: FAIL. + +- [ ] **Step 3: Implement `panel.py` and wire it into `async_setup_entry` / `async_unload_entry`.** + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `pytest custom_components/ha_controller/tests -v && ruff check custom_components` +Expected: PASS. + +- [ ] **Step 5: Write the docs and the reviewer agent.** + - **`docs/development.md`:** create it with sections "Prerequisites" (Python 3.14, Node 24, ESPHome; the later plans fill these in) and "Home Assistant integration". The integration section covers: + - venv setup and `pip install -r custom_components/requirements_test.txt`; + - `pytest custom_components/ha_controller/tests`; + - running a development Home Assistant, by symlinking `custom_components/ha_controller` into `/custom_components/`; + - how hello / set_layout traffic shows up under Developer tools › Events (`esphome.ha_controller_hello`). + - **`docs/README.md`:** link the new doc. + - **`.claude/agents/ha-integration-reviewer.md`:** + - Frontmatter `name: ha-integration-reviewer`, `tools: Read, Grep, Glob, Bash`. + - `description:` "Reviews changes under custom_components/ha_controller and custom_components/ha_controller/tests against Home Assistant development rules. Use before merging integration changes." + - Checklist: + - async only, with no blocking I/O in the loop; + - `entry.runtime_data`, with no new `hass.data` globals beyond the panel flags; + - listeners and timers removed on unload; + - event filters by `device_id`; + - service errors caught; + - constants come from `const.py`; + - English strings in `strings.json` and `translations/en.json`; + - every branch tested; + - protocol changes routed to the `protocol-change` skill. + - Output: findings as `file:line — issue — fix`. + - **`.claude/CLAUDE.md`:** list the agent. + +- [ ] **Step 6: Commit** + +```bash +git add custom_components/ha_controller custom_components/ha_controller/tests/test_panel.py docs .claude .claude/CLAUDE.md +git commit -m "feat(integration): register the sidebar panel" +``` diff --git a/docs/superpowers/plans/2026-11-16-ha-controller-3-panel.md b/docs/superpowers/plans/2026-11-16-ha-controller-3-panel.md new file mode 100644 index 0000000..e929817 --- /dev/null +++ b/docs/superpowers/plans/2026-11-16-ha-controller-3-panel.md @@ -0,0 +1,433 @@ +# HA Controller — Plan 3: Sidebar Panel (Block Map Editor) + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Build the Home Assistant sidebar panel where the user edits each screen's block map. The map is laid out exactly the way navigation works on the screen ([reference screenshot](../specs/assets/editor-reference.png)). + +**Architecture:** A Lit + TypeScript web component bundled by Vite into one ES module. Vite writes it to `custom_components/ha_controller/frontend/dist/ha-controller-panel.js`, which plan 2's `panel.py` serves. +- **Model:** pure functions in `src/model/` hold all editing logic (grid, validation, edits, colours, emoji). Vitest tests them against `docs/protocol/fixtures/`. +- **Components:** they only render and emit events. +- **Websocket:** the panel talks to the integration through plan 2's commands. +- **Dev harness:** `npm run dev` runs the panel against an in-memory mock `hass`. + +**Tech Stack:** Node 24, TypeScript 5 (strict), Lit 3, Vite, Vitest with happy-dom. Use the current stable releases of the build and test tools, and commit `package-lock.json`. + +**Spec:** `docs/superpowers/specs/2026-11-16-ha-controller-design.md` (§5.1, §5.5, §6, §9) + +## Global Constraints + +- **Rules and codes:** the validation rules and error codes are identical to plan 2 (spec §6). Both suites read the same fixtures. +- **Orientation:** grid `x` grows to the right and `y` grows downwards, matching the screen. +- **No Home Assistant internals:** use no HA-internal custom elements except `ha-menu-button` (optional, narrow mode). Entity pickers are built from `hass.states`. +- **Theme:** use Home Assistant theme variables with fallbacks: + - `--primary-color` (fallback `#03a9f4`) + - `--primary-text-color` (fallback `#212121`) + - `--secondary-text-color` (fallback `#727272`) + - `--card-background-color` (fallback `#fff`) + - `--divider-color` (fallback `rgba(0,0,0,.12)`) + - `--error-color` (fallback `#db4437`) +- **Strings:** all UI strings are in English and live in `src/messages.ts`. +- **Versioning:** `custom_components/ha_controller/frontend/package.json` `version` is `0.1.0`; plan 5's versioning script keeps it in sync. + +## Review Focus + +1. **Deleting a block that would strand others**, e.g. deleting "Hello World" in the reference layout strands "Bedroom". Expected: refused, with the reason shown. Owner: Task 1 `canDelete` tests, Task 4 editor test. +2. **Map with a start block away from `(0,0)`, negative coordinates, or one row/column.** The map must still render every block at the right relative place, and placeholders must stay inside ±32. Owner: Task 1 placeholder tests on `single.json`, Task 3 grid test. +3. **Websocket save rejected** (`invalid_layout`, connection lost). The working copy must be kept and the error shown, never silently dropped. Owner: Task 5 `test_save_error_keeps_changes`. +4. **Emoji typed or pasted with U+FE0F.** It must be normalised so local validation and the screen agree. Owner: Task 2 `normalizeEmoji` and Task 4 emoji picker test. +5. **`hass` updates arriving every few seconds** while the user edits. Unsaved edits must never be overwritten by a refresh. Owner: Task 5 `test_refresh_does_not_reset_working_copy`. + +--- + +### Task 1: Tooling, types, grid model and validation + +**Files:** +- Create: + - `custom_components/ha_controller/frontend/package.json`, `custom_components/ha_controller/frontend/package-lock.json`, `custom_components/ha_controller/frontend/tsconfig.json`, `custom_components/ha_controller/frontend/vite.config.ts` + - `custom_components/ha_controller/frontend/src/types.ts`, `custom_components/ha_controller/frontend/src/model/grid.ts`, `custom_components/ha_controller/frontend/src/model/validate.ts`, `custom_components/ha_controller/frontend/src/model/emoji.ts` + - `custom_components/ha_controller/frontend/test/fixtures.ts`, `custom_components/ha_controller/frontend/test/grid.test.ts`, `custom_components/ha_controller/frontend/test/validate.test.ts` +- Modify: `.github/workflows/ci.yml` (job `frontend`), `.claude/CLAUDE.md` (commands) + +**Interfaces:** +- Produces: + - **`types.ts`:** + - `FontSize = "s" | "m" | "l" | "xl"` + - `ItemKind = "text" | "emoji" | "entity" | "battery" | "brightness"` + - `Item {id, kind, font_size: FontSize | null, text?, emoji?, entity_id?, attribute?: string | null}` + - `Block {id, x, y, name, background, font_size, type: "entity" | "custom", entity_id?, items?: Item[]}` + - `Layout {version: 1, start: string | null, settings: {sleep_timeout: number}, blocks: Block[]}` + - `LayoutError {code: string, ref: string | null}` + - `Cell {x, y}` + - `ScreenInfo`: the spec §8 fields + - `HassEntity {entity_id, state, attributes}` + - `Hass {states: Record, callWS(msg): Promise}` + - **`model/grid.ts`:** + - `placeholders(layout: Layout): Cell[]`, sorted by `y` then `x` + - `reachable(blocks: Block[], start: string | null): Set` + - `canDelete(layout, id): {ok: true} | {ok: false, reason: "start" | "disconnects"}` + - `gridBounds(cells: Cell[]): {minX, maxX, minY, maxY}` + - **`model/validate.ts`:** `validateLayout(layout: unknown, emoji: ReadonlySet): LayoutError[]`. Same phases and order as plan 2 Task 2. Lengths count code points (`Array.from(text).length`, never `.length`), and names use `trim()`. + - **`model/emoji.ts`:** `SUPPORTED_EMOJI: readonly string[]` imported from `../../../emoji.json` (relative to `src/model/`), `EMOJI_SET`, `normalizeEmoji(text): string`. + - **`test/fixtures.ts`:** `validLayouts`, `invalidLayouts` and `colors`, loaded with `import.meta.glob("../../../../docs/protocol/fixtures/…", {eager: true, import: "default"})`. + +- [ ] **Step 1: Scaffold the tooling.** + - **`package.json`:** `"type": "module"`, `"private": true`, `"version": "0.1.0"`. + - Scripts: `dev` (`vite --open dev/index.html`), `build` (`tsc --noEmit && vite build`), `test` (`vitest run`), `typecheck` (`tsc --noEmit`). + - Dependency: `lit`. Dev dependencies: `typescript`, `vite`, `vitest`, `happy-dom`. + - **`tsconfig.json`:** `strict`, `target` and `lib` ES2022 + DOM, `module: ESNext`, `moduleResolution: Bundler`, `experimentalDecorators: true`, `useDefineForClassFields: false`, `resolveJsonModule: true`, `noEmit: true`. + - **`vite.config.ts`:** + - Library mode: entry `src/ha-controller-panel.ts`, format `es`, file name `ha-controller-panel.js`. + - `outDir: "dist"`, `emptyOutDir: true`, `target: "es2022"`, with `lit` bundled. + - `server.fs.allow: ["../../.."]` (the repository root, for the fixtures and `emoji.json`). + - `test.environment: "happy-dom"`. + + Run `npm install`. + +- [ ] **Step 2: Write the failing tests** + +```ts +// grid.test.ts +expect(placeholders(validLayouts.empty)).toEqual([{x: 0, y: 0}]); +expect(placeholders(validLayouts.reference)).toEqual([ + {x: 0, y: -2}, {x: -1, y: -1}, {x: 1, y: -1}, {x: -2, y: 0}, + {x: 1, y: 0}, {x: -2, y: 1}, {x: 0, y: 1}, {x: -1, y: 2}]); // the 8 "+" of the screenshot +expect(placeholders(rowOf32Blocks)).toEqual([]); +expect(placeholders(blockAt(32, 0))).not.toContainEqual({x: 33, y: 0}); +expect(canDelete(validLayouts.reference, "b1")).toEqual({ok: false, reason: "start"}); +expect(canDelete(validLayouts.reference, "b3")).toEqual({ok: false, reason: "disconnects"}); +expect(canDelete(validLayouts.reference, "b2")).toEqual({ok: true}); +expect(canDelete(validLayouts.single, "b1")).toEqual({ok: true}); +expect(gridBounds(cellsOf(validLayouts.single))).toEqual({minX: 3, maxX: 3, minY: -2, maxY: -2}); + +// validate.test.ts +for (const [name, layout] of Object.entries(validLayouts)) expect(validateLayout(layout, EMOJI_SET), name).toEqual([]); +for (const [name, c] of Object.entries(invalidLayouts)) expect(validateLayout(c.layout, EMOJI_SET), name).toEqual([c.expect]); +``` + +- [ ] **Step 3: Run the tests to verify they fail** + +Run: `npm --prefix custom_components/ha_controller/frontend test` +Expected: FAIL (modules missing). + +- [ ] **Step 4: Implement `types.ts`, `grid.ts`, `validate.ts` and `emoji.ts`.** + - `placeholders` collects the empty 4-neighbours of every block within ±32, deduplicated. With no blocks it returns `[(0,0)]`; with 32 blocks it returns `[]`. + - `canDelete` refuses the start block of a multi-block layout. It also refuses any block whose removal leaves another block unreachable from the start block. + +- [ ] **Step 5: Run the tests to verify they pass** + +Run: `npm --prefix custom_components/ha_controller/frontend test && npm --prefix custom_components/ha_controller/frontend run typecheck` +Expected: PASS. + +- [ ] **Step 6: Add the CI job.** Add job `frontend` to `.github/workflows/ci.yml`: + - `actions/setup-node@v4` with `node-version: 24`, `cache: npm`, `cache-dependency-path: custom_components/ha_controller/frontend/package-lock.json`. + - Working directory `custom_components/ha_controller/frontend`: `npm ci`, `npm test`, `npm run build`. + + Add the `npm --prefix custom_components/ha_controller/frontend …` commands to `.claude/CLAUDE.md`. + +- [ ] **Step 7: Commit** + +```bash +git add custom_components/ha_controller/frontend .github/workflows/ci.yml .claude/CLAUDE.md +git commit -m "feat(panel): add panel tooling, grid model and validation" +``` + +--- + +### Task 2: Edit operations, colours and emoji + +**Files:** +- Create: `custom_components/ha_controller/frontend/src/model/edit.ts`, `custom_components/ha_controller/frontend/src/model/color.ts`, `custom_components/ha_controller/frontend/test/edit.test.ts`, `custom_components/ha_controller/frontend/test/color.test.ts`, `custom_components/ha_controller/frontend/test/emoji.test.ts` + +**Interfaces:** +- Consumes: `canDelete` (Task 1). +- Produces. Every function is pure and returns a new `Layout` without mutating its input. + - `PALETTE = ["#C94F3D", "#4F86DD", "#5B9E4D", "#7B2FA0", "#E08A2E", "#2E9E8F", "#D2477A", "#5C6BC0"]` + - `nextId(layout, prefix: "b" | "i"): string`: one plus the highest numeric suffix among block and item ids with that prefix. + - `addBlock(layout, cell): {layout, id}`. The new block gets name `Block ` (n = the numeric part of its id), background `PALETTE[blocks.length % 8]`, font `m`, type `custom` and `items: []`. If `start` was null, it becomes the start block. + - `deleteBlock(layout, id)`. Throws if `canDelete` refuses. Deleting the last block sets `start` to `null`. + - `setStart(layout, id)` and `updateBlock(layout, id, patch: Partial)`. + - `setSleepTimeout(layout, seconds: number)`: replaces `settings.sleep_timeout`. + - `addItem(layout, blockId, kind): {layout, id}`. Defaults: text `{text: "Text"}`, emoji `{emoji: "💡"}`, entity `{entity_id: "", attribute: null}`. Every kind gets `font_size: null`. + - `updateItem(layout, blockId, itemId, patch)`, `removeItem(layout, blockId, itemId)` and `moveItem(layout, blockId, itemId, delta: -1 | 1)`. `moveItem` is a no-op at either end. + - `textColorFor(bg: string): "#000000" | "#FFFFFF"`: `#000000` if WCAG relative luminance > 0.30 (spec §5.5). + +- [ ] **Step 1: Write the failing tests** + +```ts +const r = addBlock(validLayouts.reference, {x: 1, y: 0}); +expect(r.id).toBe("b5"); +expect(r.layout.blocks.at(-1)).toMatchObject({name: "Block 5", background: "#E08A2E", font_size: "m", type: "custom", items: []}); +expect(r.layout.start).toBe("b1"); +expect(addBlock(validLayouts.empty, {x: 0, y: 0}).layout).toMatchObject({start: "b1", blocks: [{id: "b1", background: "#C94F3D"}]}); +expect(nextId(validLayouts.reference, "i")).toBe("i6"); +expect(deleteBlock(validLayouts.single, "b1")).toEqual({version: 1, start: null, settings: {sleep_timeout: 0}, blocks: []}); +expect(setSleepTimeout(validLayouts.reference, 45).settings).toEqual({sleep_timeout: 45}); +expect(() => deleteBlock(validLayouts.reference, "b3")).toThrow(); +expect(itemIds(moveItem(validLayouts.reference, "b3", "i1", 1), "b3")).toEqual(["i2", "i1", "i3", "i4", "i5"]); +expect(itemIds(moveItem(validLayouts.reference, "b3", "i1", -1), "b3")).toEqual(["i1", "i2", "i3", "i4", "i5"]); +const copy = structuredClone(validLayouts.reference); updateBlock(copy, "b2", {name: "X"}); expect(copy).toEqual(validLayouts.reference); +for (const c of colors) expect(textColorFor(c.bg)).toBe(c.text); +expect(SUPPORTED_EMOJI).toHaveLength(64); expect(normalizeEmoji("❄️")).toBe("❄"); +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `npm --prefix custom_components/ha_controller/frontend test` +Expected: FAIL. + +- [ ] **Step 3: Implement `edit.ts` and `color.ts`.** + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `npm --prefix custom_components/ha_controller/frontend test` +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add custom_components/ha_controller/frontend/src/model custom_components/ha_controller/frontend/test +git commit -m "feat(panel): add pure layout edit operations" +``` + +--- + +### Task 3: Block map component (`hc-grid`) + +**Files:** +- Create: `custom_components/ha_controller/frontend/src/components/hc-grid.ts`, `custom_components/ha_controller/frontend/test/hc-grid.test.ts` + +**Interfaces:** +- Consumes: `placeholders`, `gridBounds` and `textColorFor`. +- Produces: a `` element. + - **Properties:** `layout: Layout`, `selectedId: string | null`, `errorRefs: ReadonlySet`. + - **Rendering:** a CSS grid with 96 px cells, a 12 px gap and a 16 px radius. Each cell is placed with `grid-column: x - minX + 1` and `grid-row: y - minY + 1`. + - Blocks: `button.block[data-id]`, filled with their background, showing the name in `textColorFor(background)`. + - The start block carries a 3 px outline and a `span.start-badge` with the text `start`. + - Placeholders: `button.placeholder[data-x][data-y]`, with a 2 px dashed `--divider-color` border and a `+`. + - State classes: `.selected` (ring in `--primary-color`) and `.has-error` (ring in `--error-color`). + - **Events:** `hc-add-block` `{detail: {x, y}}` and `hc-select-block` `{detail: {id}}`. Both bubble and are composed. + +- [ ] **Step 1: Write the failing tests** + +```ts +const el = await mount(html``); +expect(all(el, ".block")).toHaveLength(4); +expect(all(el, ".placeholder")).toHaveLength(8); +expect(one(el, '.block[data-id="b1"] .start-badge')?.textContent).toBe("start"); +expect(one(el, '.block[data-id="b4"]')!.classList.contains("has-error")).toBe(true); +const added = nextEvent(el, "hc-add-block"); one(el, '.placeholder[data-x="1"][data-y="0"]')!.click(); +expect((await added).detail).toEqual({x: 1, y: 0}); +// grid placement: b3 (-1, 0) → column 2, row 3 with bounds minX -2, minY -2 +expect(one(el, '.block[data-id="b3"]')!.style.gridColumn).toBe("2"); expect(one(el, '.block[data-id="b3"]')!.style.gridRow).toBe("3"); +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `npm --prefix custom_components/ha_controller/frontend test` +Expected: FAIL. + +- [ ] **Step 3: Implement `hc-grid.ts`.** + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `npm --prefix custom_components/ha_controller/frontend test` +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add custom_components/ha_controller/frontend/src/components/hc-grid.ts custom_components/ha_controller/frontend/test/hc-grid.test.ts +git commit -m "feat(panel): render the block map" +``` + +--- + +### Task 4: Block editor components + +**Files:** +- Create: + - `custom_components/ha_controller/frontend/src/messages.ts` + - `custom_components/ha_controller/frontend/src/components/`: `hc-block-editor.ts`, `hc-item-editor.ts`, `hc-entity-input.ts`, `hc-emoji-picker.ts`, `hc-preview.ts` + - `custom_components/ha_controller/frontend/test/hc-block-editor.test.ts`, `custom_components/ha_controller/frontend/test/hc-item-editor.test.ts` + +**Interfaces:** +- Consumes: the Task 2 edit operations and `canDelete`. +- Produces: + - **`messages.ts`:** + - `errorMessage(code: string): string`, keyed by error code: + + | code | Message | + |---|---| + | `invalid_structure` | "The layout is malformed." | + | `too_many_blocks` | "A screen holds at most 32 blocks." | + | `invalid_id` | "Invalid identifier." | + | `duplicate_id` | "Duplicate identifier." | + | `coordinate_out_of_range` | "This block is too far from the centre of the map." | + | `duplicate_position` | "Two blocks share the same cell." | + | `invalid_start` | "Choose a start block." | + | `disconnected` | "This block can't be reached from the start block." | + | `invalid_name` | "Names need 1 to 32 characters." | + | `invalid_background` | "Pick a background colour." | + | `invalid_font_size` | "Pick a font size." | + | `invalid_type` | "Pick a block type." | + | `invalid_entity` | "Pick a valid entity." | + | `too_many_items` | "A custom block holds at most 6 items." | + | `invalid_item` | "Unknown item type." | + | `invalid_text` | "Text needs 1 to 64 characters." | + | `unsupported_emoji` | "This emoji is not available on the screen." | + | `payload_too_large` | "The layout is too large for the screen. Remove blocks or shorten texts." | + | `invalid_sleep_timeout` | "The sleep delay must be 0 (never) or between 5 and 3600 seconds." | + | any other code | "Invalid layout." | + + - `deleteReason`: `start` → "Choose another start block first."; `disconnects` → "Other blocks would become unreachable." + - **``:** properties `hass`, `layout` and `blockId`. It emits `hc-layout-change` `{detail: {layout}}` and contains: + - a name input and a background colour input with 8 palette swatches; + - font size buttons `S M L XL`; + - a type select (`Entity` / `Custom`) that switches with `updateBlock` and keeps the other type's fields; + - for entity blocks, ``; + - for custom blocks, the item list with an "Add item" select (Text, Emoji, Entity state, Battery, Screen brightness); + - a `Set as start block` button, disabled for the start block; + - a `Delete block` button, disabled with `deleteReason` text when `canDelete` refuses; + - ``. + - **``:** + - Properties: `hass`, `item`, `index` and `count`. + - Kind-specific fields: + - text: an input; + - emoji: ``; + - entity: `` (all domains) plus an optional attribute input. + - A font size select (Inherit/S/M/L/XL) and up/down/remove buttons. + - Events: `hc-item-change {patch}`, `hc-item-move {delta}` and `hc-item-remove`. + - **``:** properties `hass`, `value` and `domains?: string[]`. It renders an `` with a `` of matching entity ids, sorted, labelled by `friendly_name`, and emits `hc-value-change {value}`. + - **``:** property `value`. It renders 64 `button.emoji` elements and emits `hc-value-change {value: normalizeEmoji(...)}`. + - **``:** properties `block` and `hass`. It renders a 220 px circle in the block background with contrast text, showing the name and a content summary: + - entity blocks: the entity's state; + - custom blocks: one line per item. + +- [ ] **Step 1: Write the failing tests** + +```ts +// hc-block-editor +const changed = nextEvent(el, "hc-layout-change"); type(one(el, "input[name=name]")!, "Kitchen 2"); +expect((await changed).detail.layout.blocks[0].name).toBe("Kitchen 2"); +expect(options(el, "hc-entity-input datalist option")).toEqual(["climate.bedroom", "light.kitchen", "light.living_room"]); // hass has sensor.* too +expect(one(el, "button.delete")!.hasAttribute("disabled")).toBe(true); // start block of the reference layout +expect(el.shadowRoot!.textContent).toContain("Choose another start block first."); +// switching b1 to Custom keeps entity_id, adds items [] +// hc-item-editor / emoji picker +expect(all(picker, "button.emoji")).toHaveLength(64); +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `npm --prefix custom_components/ha_controller/frontend test` +Expected: FAIL. + +- [ ] **Step 3: Implement the five components and `messages.ts`.** + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `npm --prefix custom_components/ha_controller/frontend test && npm --prefix custom_components/ha_controller/frontend run typecheck` +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add custom_components/ha_controller/frontend/src custom_components/ha_controller/frontend/test +git commit -m "feat(panel): add block and item editors" +``` + +--- + +### Task 5: Panel root, websocket API, dev harness, build and docs + +**Files:** +- Create: + - `custom_components/ha_controller/frontend/src/ha-controller-panel.ts`, `custom_components/ha_controller/frontend/src/api.ts` + - `custom_components/ha_controller/frontend/dev/index.html`, `custom_components/ha_controller/frontend/dev/mock-hass.ts` + - `custom_components/ha_controller/frontend/test/panel.test.ts` + - `docs/configuration.md` +- Modify: `docs/README.md`, `docs/development.md` ("Panel" section), `.claude/CLAUDE.md` + +**Interfaces:** +- Consumes: plan 2's websocket commands `ha_controller/screens`, `ha_controller/layout/get` and `ha_controller/layout/save`; Tasks 1–4. +- Produces: + - **`api.ts`:** `listScreens(hass): Promise`, `getLayout(hass, entryId): Promise` and `saveLayout(hass, entryId, layout): Promise<{revision: string, pushed: boolean}>`. + - **``:** + - Properties: `hass`, `narrow`, `panel`, `route`. + - Internal state: `screens`, `entryId`, `saved`, `layout` (working copy), `selectedId`, `notice`, `saving`. + - Lifecycle: + - On the first `hass` assignment, load the screens and select the first one. A user selection is kept. + - Refresh only `screens` every 10 s (an interval started in `connectedCallback` and cleared in `disconnectedCallback`). + - Later `hass` changes never reload the layout. + - Header: + - `ha-menu-button` when `narrow`; + - the title "HA Controller"; + - a screen select, shown when there is more than one screen; + - the status line, one of: + - `Offline` + - `Online · firmware — update available`, when the firmware differs from the integration version + - `Online · firmware · in sync`, when `revision == device_revision` + - `Online · firmware · syncing…` + - `Revert` and `Save` buttons, disabled when `layout` deep-equals `saved` or when local validation returns errors. + - Body: `` plus `` side by side, stacked when narrow. Local errors are listed under the map as `errorMessage(code)` plus the block name, and `errorRefs` is passed to the grid. + - Screen settings: a "Screen" section under the map, with a number input "Sleep after (seconds)" wired through `setSleepTimeout` and the helper text "0 keeps the screen on." + - Save: + - Success: `Saved — sent to the screen.` when `pushed`, else `Saved — the screen is offline and will update when it reconnects.` + - On rejection, keep the working copy. If `code == "invalid_layout"`, show the parsed error messages; otherwise show `err.message`. + - **`dev/mock-hass.ts`:** `createMockHass()` returns a `Hass` with: + - states for `light.kitchen`, `light.living_room`, `climate.bedroom` and `sensor.outdoor_temperature`; + - `callWS` that serves one screen and keeps the layout in memory, starting from the reference fixture. + + Tests and `dev/index.html` both use it. + +- [ ] **Step 1: Write the failing tests** in `panel.test.ts`, using `createMockHass` with `callWS` wrapped in `vi.fn`. + +```ts +test("loads the first screen and renders its map", ...) // 4 .block inside hc-grid +test("save is disabled until something changes", ...) +test("adding a block and saving sends the new layout", ...) // callWS called with {type: "ha_controller/layout/save", entry_id, layout: 5 blocks}; notice "Saved — sent to the screen." +test("save error keeps changes", ...) // callWS rejects {code: "invalid_layout", message: "invalid_name@b2"} → "Names need 1 to 32 characters." shown, 5 blocks still rendered +test("refresh does not reset working copy", ...) // edit, advance fake timers 10 s, assign a new hass → edit still present +test("changing the sleep delay enables Save and sends it", ...) // 20 → 45; saved layout.settings.sleep_timeout === 45 +test("status line reports update available", ...) // firmware_version 0.0.9 vs integration 0.1.0 +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `npm --prefix custom_components/ha_controller/frontend test` +Expected: FAIL. + +- [ ] **Step 3: Implement `api.ts`, `ha-controller-panel.ts` (with `customElements.define` guarded against double definition), `dev/mock-hass.ts` and `dev/index.html`.** + +- [ ] **Step 4: Run the tests and the build** + +Run: `npm --prefix custom_components/ha_controller/frontend test && npm --prefix custom_components/ha_controller/frontend run build && test -f custom_components/ha_controller/frontend/dist/ha-controller-panel.js` +Expected: PASS, and the bundle exists. + +- [ ] **Step 5: Manual check.** Run `npm --prefix custom_components/ha_controller/frontend run dev`. Expected: + - the reference map looks like the screenshot, with 4 blocks and 8 "+"; + - clicking "+" right of Kitchen adds "Block 5"; + - deleting Hello World is refused with "Other blocks would become unreachable."; + - Save shows the notice. + + The end-to-end check inside Home Assistant happens in plan 4, Task 5. + +- [ ] **Step 6: Write the docs.** + - **`docs/configuration.md`** (user guide): + - opening the panel (sidebar › HA Controller, admin only); + - the map: start block, adding a block with "+"; + - how swiping on the screen follows the map: put a finger on the right edge and slide left to open the block on the right, and the same for every edge; + - block types (Light, Thermostat, Custom) and custom items; + - font sizes S/M/L/XL and backgrounds (text colour is automatic); + - screen settings: the sleep delay (default 20 s; `0` keeps the screen on); + - saving and the status line; + - limits (32 blocks, 6 items, 32-char names, 64-char texts, 64 emoji). + - **`docs/development.md`**, "Panel" section: `npm ci`, `npm test`, `npm run dev` (mock harness), and `npm run build -- --watch` while testing in Home Assistant. + - **`docs/README.md`:** link `configuration.md`. + +- [ ] **Step 7: Commit** + +```bash +git add custom_components/ha_controller/frontend docs .claude/CLAUDE.md +git commit -m "feat(panel): add panel root with save, status and dev harness" +``` diff --git a/docs/superpowers/plans/2026-11-16-ha-controller-4-firmware.md b/docs/superpowers/plans/2026-11-16-ha-controller-4-firmware.md new file mode 100644 index 0000000..0e9a0b0 --- /dev/null +++ b/docs/superpowers/plans/2026-11-16-ha-controller-4-firmware.md @@ -0,0 +1,875 @@ +# HA Controller — Plan 4: ESPHome Firmware + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Build the screen firmware: an ESPHome config for the Waveshare ESP32-S3-Touch-AMOLED-1.75 plus a desktop simulator. It renders the layout pushed by the integration, navigates between blocks with edge swipes and smooth slides, drives the light/climate knobs and custom items, sleeps after the configured delay and wakes on touch, reports controls and hellos to Home Assistant, and installs firmware over the air on request. + +**Architecture:** Two local external components. +- `ha_controller`: + - **Pure C++17 modules** with no ESPHome or LVGL headers, unit-tested on the host against `docs/protocol/fixtures/`: `layout`, `states`, `knob`, `format`, `gesture`, `color`, `hold`. + - **LVGL 9.5 modules:** `pager` (gestures, animation, edge hints) and `widgets` (block views). + - **`HaController`:** the ESPHome component that glues them to the native API actions and events declared in YAML. +- `axp2101_battery`: reads the PMU. + +YAML is split into `packages/board-waveshare-amoled-175.yaml` (hardware) and `packages/ui.yaml` (UI, API actions, hello). The device config and `simulator.yaml` (ESPHome `host` + SDL) both include them. + +**Tech Stack:** ESPHome 2026.10.2, ESP-IDF, LVGL 9.5 (bundled by ESPHome), ArduinoJson 7, C++17, CMake ≥ 3.20, doctest 2.4.12, Python 3.13 (ESPHome CLI), SDL2 (simulator). + +**Spec:** `docs/superpowers/specs/2026-11-16-ha-controller-design.md` (§4, §5, §7, §15) + +## Global Constraints + +- **ESPHome:** `esphome==2026.10.2` in `esphome/requirements.txt`, `min_version: 2026.10.0`, framework `esp-idf`. ESPHome project `pyxel-dev.ha-controller`, version `${project_version}` from `esphome/version.yaml`. +- **Hardware:** all pins, addresses, transforms and registers exactly as spec §4. The touch component `cst9217` comes from `https://github.com/shelson/esphome-cst9217`, pinned to the commit SHA current at implementation time. +- **LVGL 9.5 API names:** + - screens and objects: `lv_screen_load`, `lv_layer_top`, `lv_obj_delete`, `lv_obj_remove_flag`; + - animations: `lv_anim_set_duration`, `lv_anim_set_completed_cb`, `lv_anim_delete`, `lv_anim_path_ease_out`; + - input and events: `lv_indev_active`, `lv_indev_get_point`, `lv_event_get_target_obj`, `lv_event_get_hit_test_info`; + - rendering and activity: `lv_refr_now`, `lv_display_get_inactive_time`, `lv_display_trigger_activity`. + + Every LVGL call runs on the ESPHome main loop: `setup`, `loop`, API actions or LVGL event callbacks. +- **Pure modules:** `layout.*`, `states.*`, `knob.h`, `format.h`, `gesture.*`, `color.h`, `hold.h` and `axp2101_regs.h` include only the standard library and ``. They compile on the host in C++17. All component sources stay flat in their component directory. +- **Protocol and constants:** protocol v1 (spec §7) and constants (spec §15). `PROTOCOL_VERSION = 1` lives in `layout.h`. +- **ESPHome callbacks:** views never register ESPHome sensor or number callbacks. `HaController` subscribes once in `setup()` and forwards to the live views, because callbacks cannot be removed when the layout is rebuilt. +- **Secrets:** no Wi-Fi credentials or secrets in any committed YAML. + +## Review Focus + +1. **A layout or state push arriving mid-swipe.** The pager must cancel the animation, reset the tracker and show the right page, with no dangling pointers. Owner: Task 3 `SwipeTracker reset` test, plus the Task 6 manual check "push a layout while dragging". +2. **Malformed or hostile payloads:** wrong types, huge numbers, missing `items`, deep nesting. The parser must return `invalid_payload` and leave the current UI untouched. Owner: Task 1 extra parser cases. +3. **Touches exactly on the ring boundary, on the diagonal, outside the visible circle, or arriving as several points.** Classification must stay deterministic. Owner: Task 3 boundary and tie tests. +4. **Battery absent or PMU not answering.** The sensors publish NaN, battery rows show `— %`, and nothing crashes. Owner: Task 2 `format_percent(NAN)`, Task 4 decode tests, Task 7 manual check with the battery unplugged. +5. **The touch that wakes a sleeping screen.** It must never toggle a light or move a knob, and the screen must not fall straight back asleep. Owner: Task 8 `should_sleep` tests and the Task 8 manual wake checks. The `millis()` wraparound cases remain covered by the Task 2 and Task 3 tests. + +--- + +### Task 1: Host test harness, layout parser and colours + +**Files:** +- Create: + - `esphome/components/ha_controller/layout.h`, `layout.cpp`, `color.h` + - `esphome/tests/CMakeLists.txt`, `esphome/tests/test_main.cpp`, `esphome/tests/fixtures.h` + - `esphome/tests/test_layout.cpp`, `esphome/tests/test_color.cpp` + +**Interfaces:** +- Produces (namespace `esphome::ha_controller`): + +```cpp +constexpr int PROTOCOL_VERSION = 1; +enum class FontSize : uint8_t { S, M, L, XL }; +enum class Widget : uint8_t { LIGHT, CLIMATE, CUSTOM }; +enum class ItemKind : uint8_t { TEXT, EMOJI, ENTITY, BATTERY, BRIGHTNESS }; +enum class ParseError : uint8_t { NONE, BAD_JSON, UNSUPPORTED_VERSION, INVALID_PAYLOAD }; +struct Item { std::string id; ItemKind kind; FontSize font; std::string text; }; +struct Block { std::string id; int x; int y; std::string name; uint32_t bg; FontSize font; Widget widget; std::vector items; }; +struct Layout { + std::string rev; std::string start; // start is "" when null + uint32_t sleep_s{20}; // payload "sleep"; 0 = never + std::vector blocks; + const Block *find(const std::string &id) const; + const Block *find_at(int x, int y) const; +}; +ParseError parse_layout(const std::string &json, Layout &out); // `out` is replaced only on NONE +const char *parse_error_code(ParseError e); // "none", "bad_json", "unsupported_version", "invalid_payload" +// color.h +bool parse_hex_rgb(const std::string &hex, uint32_t &out); // "RRGGBB" or "#RRGGBB" +float relative_luminance(uint32_t rgb); +uint32_t text_color_for(uint32_t rgb); // 0x000000 if luminance > 0.30 else 0xFFFFFF +``` + + Test helpers in `fixtures.h`: `std::string read_fixture(const std::string &relative)`, which reads from the `FIXTURES_DIR` compile definition, and `std::string json_field(const std::string &file, const char *key)`, which re-serialises one top-level field. + +- [ ] **Step 1: Set up the host harness** in `esphome/tests/CMakeLists.txt`: + - CMake ≥ 3.20, C++17. + - `FetchContent` doctest `v2.4.12` (GIT_TAG) and ArduinoJson `v7.4.2` (GIT_TAG; same major as ESPHome's bundled 7.x). + - Target `unit_tests`: every `test_*.cpp` plus the pure `.cpp` files from `../components/ha_controller/`. + - Include path `../components`. + - `FIXTURES_DIR="${CMAKE_CURRENT_SOURCE_DIR}/../../docs/protocol/fixtures"`. + - `add_test(unit_tests …)`. + +- [ ] **Step 2: Write the failing tests** + +```cpp +TEST_CASE("parses the reference payload") { + Layout l; REQUIRE(parse_layout(json_field("payloads/valid/reference.json", "payload"), l) == ParseError::NONE); + CHECK(l.rev == "90538742"); CHECK(l.start == "b1"); CHECK(l.sleep_s == 20); CHECK(l.blocks.size() == 4); + CHECK(l.find("b3")->widget == Widget::CUSTOM); CHECK(l.find("b3")->items.size() == 5); + CHECK(l.find("b3")->items[1].kind == ItemKind::EMOJI); CHECK(l.find("b3")->items[1].text == "👋"); + CHECK(l.find("b3")->items[1].font == FontSize::XL); CHECK(l.find("b3")->items[2].font == FontSize::S); + CHECK(l.find("b4")->widget == Widget::CLIMATE); CHECK(l.find("b1")->bg == 0x5B9E4D); + CHECK(l.find_at(0, -1)->id == "b2"); CHECK(l.find_at(5, 5) == nullptr); +} +TEST_CASE("parses the empty payload") { /* start == "" and blocks empty */ } +TEST_CASE("strips U+FE0F from emoji text") { /* {"…","kind":"emoji","text":"❄️",…} → "❄" */ } +TEST_CASE("rejects every invalid payload fixture") { + // for each payloads/invalid/*.json: parse_layout(text, l) returns the expected code; a pre-filled `l` is unchanged +} +TEST_CASE("rejects hostile payloads") { + // "x": 1e40 · "x": "1" · "name": 5 · custom block without "items" · "font": "xxl" · "bg": "GGGGGG" · "sleep": -1 · "sleep": 4000 · no "sleep" · nested 64-deep arrays → INVALID_PAYLOAD or BAD_JSON +} +TEST_CASE("text colour follows colors.json") { /* every entry: text_color_for(bg) == text */ } +``` + +- [ ] **Step 3: Run the tests to verify they fail** + +Run: `cmake -S esphome/tests -B esphome/tests/build && cmake --build esphome/tests/build` +Expected: FAIL (`layout.h` not found). + +- [ ] **Step 4: Implement `layout.cpp` and `color.h`.** + - Use `JsonDocument doc; deserializeJson(doc, json)`. An error or non-object gives `BAD_JSON`. + - `v` must be the integer 1; otherwise `UNSUPPORTED_VERSION`. + - Every required field from spec §7.3 must be present with its JSON type, `x`/`y` must fit `int`, and `sleep` must be an integer from 0 to 3600. Otherwise `INVALID_PAYLOAD`. + - Remove the UTF-8 bytes `EF B8 8F` from `text`. + +- [ ] **Step 5: Run the tests to verify they pass** + +Run: `cmake --build esphome/tests/build && ctest --test-dir esphome/tests/build --output-on-failure` +Expected: PASS. + +- [ ] **Step 6: Commit** + +```bash +git add esphome/components/ha_controller esphome/tests +git commit -m "feat(firmware): parse layout payloads on the screen" +``` + +--- + +### Task 2: State parser, knob scale, formatting and interaction hold + +**Files:** +- Create: + - `esphome/components/ha_controller/states.h`, `states.cpp`, `knob.h`, `format.h`, `hold.h` + - `esphome/tests/test_states.cpp`, `test_knob.cpp`, `test_format.cpp`, `test_hold.cpp` + +**Interfaces:** +- Produces: + +```cpp +struct StateUpdate { + std::string id; bool available{true}; + std::optional on; std::optional brightness; // light (nullopt brightness = on/off only) + std::optional target; float min{7}, max{35}, step{0.5f}; // climate + std::string unit, current, action; // climate + std::optional text; // entity item +}; +bool parse_states(const std::string &json, std::vector &out); // false on bad JSON / not an array; elements without a string id are skipped +struct KnobScale { + float min, max, step; + int steps() const; // round((max-min)/step); step <= 0 counts as 1; 0 when max <= min + int index_of(float value) const; // clamped to [0, steps()] + float value_at(int index) const; // min + index*step, clamped to [min, max] +}; +std::string format_value(float value, float step); // 1 decimal if step < 1, else none +std::string format_percent(float pct); // "87 %", NaN → "— %" +class InteractionHold { public: explicit InteractionHold(uint32_t window_ms = 1500); + void touch(uint32_t now_ms); bool active(uint32_t now_ms) const; }; // active iff touched and (now - last) < window, unsigned +``` + +- [ ] **Step 1: Write the failing tests** + +```cpp +// states: parse json_field("states/.json", "updates") for each fixture +CHECK(u.on == true); CHECK(u.brightness == 50); // light-dimmable-on +CHECK(!u.brightness.has_value()); // light-onoff +CHECK(u.available == false); // light-unavailable +CHECK(*u.target == doctest::Approx(20.5)); CHECK(u.step == doctest::Approx(0.5)); +CHECK(u.unit == "°C"); CHECK(u.current == "19.8 °C"); CHECK(u.action == "Heating"); // climate-heating +CHECK(!u.target.has_value()); CHECK(u.current == "—"); // climate-defaults +CHECK(*u.text == "12.3 °C"); // entity-precision +CHECK_FALSE(parse_states("{\"id\":1}", out)); +// knob +CHECK(KnobScale{0, 100, 1}.steps() == 100); CHECK(KnobScale{7, 35, 0.5f}.steps() == 56); +CHECK(KnobScale{7, 35, 0.5f}.index_of(20.5f) == 27); CHECK(KnobScale{7, 35, 0.5f}.value_at(27) == doctest::Approx(20.5)); +CHECK(KnobScale{7, 35, 0.5f}.index_of(100) == 56); CHECK(KnobScale{7, 35, 0.5f}.index_of(-5) == 0); +CHECK(KnobScale{10, 10, 0.5f}.steps() == 0); CHECK(KnobScale{7, 35, 0}.steps() == 28); +// format +CHECK(format_value(20.5f, 0.5f) == "20.5"); CHECK(format_value(21, 1) == "21"); CHECK(format_value(21, 0.5f) == "21.0"); +CHECK(format_percent(87.4f) == "87 %"); CHECK(format_percent(NAN) == "— %"); +// hold +InteractionHold h; CHECK_FALSE(h.active(0)); h.touch(1000); CHECK(h.active(2499)); CHECK_FALSE(h.active(2500)); +h.touch(0xFFFFFF00u); CHECK(h.active(0x00000100u)); // wraparound +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `cmake --build esphome/tests/build` +Expected: FAIL. + +- [ ] **Step 3: Implement the five headers and `states.cpp`.** + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `cmake --build esphome/tests/build && ctest --test-dir esphome/tests/build --output-on-failure` +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add esphome/components/ha_controller esphome/tests +git commit -m "feat(firmware): parse state updates and add knob helpers" +``` + +--- + +### Task 3: Edge-swipe gesture model + +**Files:** +- Create: `esphome/components/ha_controller/gesture.h`, `gesture.cpp`, `esphome/tests/test_gesture.cpp` + +**Interfaces:** +- Produces (spec §5.2–§5.3): + +```cpp +enum class Edge : uint8_t { NONE, LEFT, RIGHT, TOP, BOTTOM }; +struct GridStep { int dx; int dy; }; +Edge classify_edge(int x, int y, int size, int edge_width); // centre = size/2.0f; ring iff r >= size/2.0f - edge_width (inclusive); |dx| >= |dy| → horizontal +GridStep step_for(Edge edge); // RIGHT {1,0} · LEFT {-1,0} · TOP {0,-1} · BOTTOM {0,1} · NONE {0,0} +struct SwipeConfig { int size = 466; float commit_ratio = 0.25f; float flick_velocity = 0.6f; + int flick_min_px = 24; float rubber_factor = 0.3f; int rubber_max_px = 48; uint32_t velocity_window_ms = 100; }; +class SwipeTracker { + public: + explicit SwipeTracker(SwipeConfig cfg = {}); + void begin(Edge edge, bool has_target, int x, int y, uint32_t t_ms); + int update(int x, int y, uint32_t t_ms); // visual offset (px) along the navigation axis + bool release(uint32_t t_ms); // true = commit; tracker becomes inactive + void reset(); // abort without decision + bool active() const; Edge edge() const; int progress() const; +}; +uint32_t settle_duration_ms(int remaining_px, int size); // clamp(220 * remaining / size, 80, 220) +``` + +- [ ] **Step 1: Write the failing tests** + +```cpp +CHECK(classify_edge(233, 233, 466, 36) == Edge::NONE); CHECK(classify_edge(460, 233, 466, 36) == Edge::RIGHT); +CHECK(classify_edge(5, 233, 466, 36) == Edge::LEFT); CHECK(classify_edge(233, 4, 466, 36) == Edge::TOP); +CHECK(classify_edge(233, 462, 466, 36) == Edge::BOTTOM); CHECK(classify_edge(430, 233, 466, 36) == Edge::RIGHT); // r = 197, boundary +CHECK(classify_edge(429, 233, 466, 36) == Edge::NONE); CHECK(classify_edge(10, 10, 466, 36) == Edge::LEFT); // diagonal tie → horizontal +CHECK(classify_edge(456, 10, 466, 36) == Edge::RIGHT); // outside the visible circle still classifies +SwipeTracker t; +t.begin(Edge::RIGHT, true, 460, 233, 0); CHECK(t.update(400, 233, 50) == 60); CHECK(t.update(300, 240, 300) == 160); CHECK(t.release(400)); +t.begin(Edge::RIGHT, true, 460, 233, 0); CHECK(t.update(420, 233, 500) == 40); CHECK_FALSE(t.release(600)); // slow and short +t.begin(Edge::LEFT, true, 5, 233, 0); t.update(25, 233, 10); CHECK(t.update(65, 233, 40) == 60); CHECK(t.release(45)); // flick +t.begin(Edge::RIGHT, true, 460, 233, 0); CHECK(t.update(470, 233, 50) == 0); // outward ignored +t.begin(Edge::TOP, false, 233, 4, 0); CHECK(t.update(233, 204, 100) == 48); CHECK_FALSE(t.release(150)); // rubber band +t.begin(Edge::BOTTOM, true, 233, 462, 0); CHECK(t.update(233, -600, 50) == 466); // clamp to size +t.begin(Edge::LEFT, true, 5, 233, 0xFFFFFFF0u); t.update(65, 233, 0x00000020u); CHECK(t.release(0x00000020u)); // wraparound flick +t.begin(Edge::LEFT, true, 5, 233, 0); t.update(300, 233, 10); t.reset(); CHECK_FALSE(t.active()); CHECK_FALSE(t.release(20)); +CHECK(settle_duration_ms(466, 466) == 220); CHECK(settle_duration_ms(0, 466) == 80); CHECK(settle_duration_ms(233, 466) == 110); +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `cmake --build esphome/tests/build` +Expected: FAIL. + +- [ ] **Step 3: Implement `gesture.cpp`.** Keep a small ring buffer of `(t, progress)` samples, including the `begin` sample. On release, velocity = `(progress_now − progress_old) / (t_now − t_old)`, where `old` is the oldest sample inside `velocity_window_ms`. Use unsigned time differences. + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `cmake --build esphome/tests/build && ctest --test-dir esphome/tests/build --output-on-failure` +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add esphome/components/ha_controller esphome/tests +git commit -m "feat(firmware): model edge swipes" +``` + +--- + +### Task 4: Hardware bring-up — board package, AXP2101 battery, boot page, firmware CI + +**Files:** +- Create: + - `esphome/requirements.txt`, `esphome/version.yaml`, `esphome/ha-controller.yaml` + - `esphome/packages/board-waveshare-amoled-175.yaml`, `esphome/packages/ui.yaml` + - `esphome/components/axp2101_battery/__init__.py`, `axp2101_battery.h`, `axp2101_battery.cpp`, `axp2101_regs.h` + - `esphome/tests/test_axp2101.cpp` + - `.github/workflows/firmware.yml` +- Modify: `esphome/tests/CMakeLists.txt` (include path for `axp2101_battery`), `.claude/CLAUDE.md` (commands) + +**Interfaces:** +- Produces: + - **`axp2101_regs.h`** (namespace `esphome::axp2101_battery`): + - register constants `REG_STATUS1 = 0x00`, `REG_STATUS2 = 0x01`, `REG_ADC_CTRL = 0x30`, `REG_VBAT_H = 0x34`, `REG_VBAT_L = 0x35`, `REG_BAT_DET = 0x68`, `REG_BAT_PERCENT = 0xA4`; + - `bool battery_present(uint8_t status1)` (bit 3); + - `bool is_charging(uint8_t status2)`: `(status2 >> 5) == 0x01`; + - `uint16_t battery_millivolts(uint8_t hi, uint8_t lo)`: `((hi & 0x1F) << 8) | lo`; + - `float battery_percent(uint8_t raw)`: capped at 100. + - **The `axp2101_battery:` YAML component:** `PollingComponent` + `i2c::I2CDevice`, default address `0x34`, `update_interval` default 30 s. It has optional sub-entities: + - `battery_level`: sensor, %, device_class `battery`, accuracy 0; + - `battery_voltage`: sensor, V, device_class `voltage`, accuracy 2; + - `charging`: binary sensor, device_class `battery_charging`. + + `setup()` sets bit 0 of `0x30` and bit 0 of `0x68` (read-modify-write) and calls `mark_failed()` on an I²C error. `update()` publishes NaN for level and voltage when no battery is present. + - **YAML ids used by later tasks:** `amoled` (display), `touch`, `bus_a`, `battery_level`, `battery_charging`, `screen_brightness`. The fonts are `font_s|m|l|xl`, `value_s|m|l|xl` and `emoji_s|m|l|xl`. + +- [ ] **Step 1: Write the failing tests** in `test_axp2101.cpp`. + +```cpp +CHECK(battery_present(0x08)); CHECK_FALSE(battery_present(0xF7)); +CHECK(is_charging(0x20)); CHECK(is_charging(0x3F)); CHECK_FALSE(is_charging(0x40)); CHECK_FALSE(is_charging(0x00)); CHECK_FALSE(is_charging(0xA0)); +CHECK(battery_millivolts(0x0F, 0xA0) == 4000); CHECK(battery_millivolts(0xFF, 0xFF) == 0x1FFF); +CHECK(battery_percent(87) == 87.0f); CHECK(battery_percent(150) == 100.0f); +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `cmake --build esphome/tests/build` +Expected: FAIL (`axp2101_regs.h` not found). + +- [ ] **Step 3: Implement `axp2101_regs.h`, the `axp2101_battery` component (`__init__.py`, `.h`, `.cpp`) and the CMake include path** + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `cmake --build esphome/tests/build && ctest --test-dir esphome/tests/build --output-on-failure` +Expected: PASS. + +- [ ] **Step 5: Write the YAML.** + - **`esphome/requirements.txt`:** `esphome==2026.10.2`. + - **`esphome/version.yaml`:** `substitutions: {project_version: "0.1.0"}`. + - **`esphome/packages/board-waveshare-amoled-175.yaml`**, verbatim apart from the SHA: + +```yaml +esphome: + platformio_options: + board_build.flash_mode: dio + board_build.f_flash: 80000000L + board_build.f_cpu: 240000000L +esp32: + variant: esp32s3 + flash_size: 16MB + framework: + type: esp-idf +psram: + mode: octal + speed: 80MHz +external_components: + - source: + type: git + url: https://github.com/shelson/esphome-cst9217 + ref: + components: [cst9217] +i2c: + - id: bus_a + sda: GPIO15 + scl: GPIO14 + frequency: 400kHz +spi: + - id: display_qspi + type: quad + clk_pin: GPIO38 + data_pins: [GPIO4, GPIO5, GPIO6, GPIO7] +display: + - platform: mipi_spi + id: amoled + model: CO5300 + bus_mode: quad + reset_pin: GPIO39 + cs_pin: GPIO12 + dimensions: {width: 466, height: 466} + auto_clear_enabled: false + update_interval: never +touchscreen: + - platform: cst9217 + id: touch + display: amoled + interrupt_pin: GPIO11 + reset_pin: GPIO40 + transform: {mirror_x: true, mirror_y: true} + on_touch: + - logger.log: {level: DEBUG, format: "touch x=%d y=%d", args: [touch.x, touch.y]} +axp2101_battery: + i2c_id: bus_a + battery_level: {id: battery_level, name: Battery} + battery_voltage: {name: Battery voltage} + charging: {id: battery_charging, name: Charging} +number: + - platform: template + id: screen_brightness + name: Screen brightness + icon: mdi:brightness-6 + entity_category: config + unit_of_measurement: "%" + min_value: 5 + max_value: 100 + step: 1 + initial_value: 80 + restore_value: true + optimistic: true + on_value: + - lambda: id(amoled).set_brightness((uint8_t) lroundf(x * 2.55f)); +``` + + - **`esphome/packages/ui.yaml`:** + - The 12 fonts of spec §4.2: + - text: `file: {type: gfonts, family: Inter, weight: 600}`, `bpp: 4`, `glyphsets: [GF_Latin_Core]`; + - value: same file, `glyphs: " 0123456789.,-+%°CFOfn—"`; + - emoji: `file: {type: gfonts, family: Noto Emoji}`, `bpp: 4`, `glyphs: !include ../../custom_components/ha_controller/emoji.json`. + - `lvgl:` with `displays: [amoled]`, `touchscreens: [touch]`, `buffer_size: 25%`, `bg_color: 0x000000` and page `boot_page` holding: + - label `HA Controller` (`font_m`, white, centre, y −40); + - label `v${project_version}` (`font_s`, `0x9CA3AF`, y 10); + - label `💡` (`emoji_m`, y 70); + - a hidden `arc` (`keep_arc`) and a hidden `slider` (`keep_slider`), so that ESPHome compiles those LVGL widgets for the runtime code. + - **`esphome/ha-controller.yaml`:** + - Substitutions `name: ha-controller` and `friendly_name: HA Controller`. + - `packages`: `version`, `board`, `ui`. + - `esphome:` with name, friendly_name, `name_add_mac_suffix: true`, `min_version: 2026.10.0` and `project: {name: pyxel-dev.ha-controller, version: ${project_version}}`. + - `logger:`, `api:`, `ota: [{platform: esphome}]`. + - `wifi: {ap: {ssid: HA Controller}}`, `captive_portal:`, `improv_serial:`. + - `external_components: [{source: {type: local, path: components}}]`. + +- [ ] **Step 6: Compile** + +Run: `python3.13 -m venv esphome/.venv && esphome/.venv/bin/pip install -r esphome/requirements.txt && esphome/.venv/bin/esphome compile esphome/ha-controller.yaml` +Expected: `SUCCESS`, and the image fits the app partition (ESPHome sizes it for 16 MB). If a font option is rejected (e.g. `glyphsets`), replace it with an explicit `glyphs:` string covering U+0020–U+007E, U+00A0–U+017F and `°—…’“”€`. Record the change in `docs/hardware.md` in Task 9. + +- [ ] **Step 7: Hardware check.** Flash over USB-C with `esphome/.venv/bin/esphome run esphome/ha-controller.yaml`. Expected: + - the round display shows "HA Controller", the version and 💡, centred; + - tapping near the top/right/bottom/left edges logs about `(233,5)` / `(460,233)` / `(233,460)` / `(5,233)`. If not, fix `transform` (`mirror_x`, `mirror_y`, `swap_xy`) and repeat; + - with a battery: `Battery` reads 0–100 %, `Battery voltage` 3.3–4.3 V, and `Charging` turns on when USB is plugged in; + - without a battery: level and voltage are unknown (NaN) and there are no errors; + - the `Screen brightness` number dims the panel; + - Wi-Fi provisioning works through the `HA Controller` access point and its captive portal. + +- [ ] **Step 8: Add the firmware CI.** In `.github/workflows/firmware.yml`, workflow `Firmware`: + - Triggers: `push` to `main` and `pull_request`, on paths `esphome/**`, `docs/protocol/**`, `custom_components/ha_controller/emoji.json` and `.github/workflows/firmware.yml`. + - Job `host-tests`: `cmake -S esphome/tests -B esphome/tests/build`, `cmake --build esphome/tests/build`, `ctest --test-dir esphome/tests/build --output-on-failure`. + - Job `compile`: + - `actions/setup-python@v5` with Python 3.13; + - `actions/cache@v4` on `~/.platformio` and `esphome/.esphome`, keyed on `hashFiles('esphome/requirements.txt', 'esphome/**/*.yaml')`; + - `pip install -r esphome/requirements.txt`; + - `esphome compile esphome/ha-controller.yaml`. + + Add the host-test and compile commands to `.claude/CLAUDE.md`. + +- [ ] **Step 9: Commit** + +```bash +git add esphome .github/workflows/firmware.yml .claude/CLAUDE.md +git commit -m "feat(firmware): bring up the Waveshare AMOLED 1.75 board" +``` + +--- + +### Task 5: `ha_controller` component, API actions, hello and simulator + +**Files:** +- Create: + - `esphome/components/ha_controller/__init__.py`, `ha_controller.h`, `ha_controller.cpp` + - `esphome/components/ha_controller/widgets.h`, `widgets.cpp` (placeholder views in this task) + - `esphome/simulator.yaml` +- Modify: `esphome/packages/ui.yaml`, `.github/workflows/firmware.yml` (simulator compile), `.claude/CLAUDE.md` + +**Interfaces:** +- Consumes: Tasks 1–2 (parsers), plan 2 (hello handling, `set_layout`/`set_states` callers). +- Produces: + - **The `ha_controller:` YAML component** (`DEPENDENCIES = ["lvgl"]`, `AUTO_LOAD = ["json"]`): + - Keys: `id`, `size` (default 466), `edge_width` (default 36). + - Fonts: `text_fonts`, `value_fonts`, `emoji_fonts`, each a mapping `{s, m, l, xl}` → `font` id. + - Optional local sources: `battery_level` (sensor id), `battery_charging` (binary_sensor id), `screen_brightness` (number id). + - Trigger `on_control`, with variables `block`, `item`, `op` (`std::string`) and `value` (`float`). + - **The component class:** + +```cpp +enum class FontRole : uint8_t { TEXT, VALUE, EMOJI }; +class ControlSink { public: virtual void on_control(const std::string &block, const std::string &item, const char *op, float value) = 0; }; +class HaController : public Component, public ControlSink { + public: + void setup() override; void loop() override; float get_setup_priority() const override; // setup_priority::LATE + void set_geometry(int size, int edge_width); + void set_font(FontRole role, FontSize size, font::Font *font); // wraps with lvgl::FontEngine → const lv_font_t* + void set_battery_sensor(sensor::Sensor *s); void set_charging_sensor(binary_sensor::BinarySensor *s); + void set_brightness_number(number::Number *n); + void add_on_control_callback(std::function &&cb); + void set_layout(const std::string &json); // parse; on NONE rebuild views (keep current block id if still present, else start) + void set_states(const std::string &json); // dispatch each update to the view that owns its id + void show_message(const std::string &title, const std::string &detail); // full-screen overlay + lv_refr_now(nullptr) + void hide_message(); // back to what the current mode requires + std::string get_revision() const; // "none" until a layout is applied + void on_control(const std::string &block, const std::string &item, const char *op, float value) override; +}; +class ControlTrigger : public Trigger { public: explicit ControlTrigger(HaController *parent); }; +// widgets.h (completed in Task 7) +struct Theme { const lv_font_t *text[4]; const lv_font_t *value[4]; const lv_font_t *emoji[4]; int size; int edge_width; }; +struct LocalSources { sensor::Sensor *battery{}; binary_sensor::BinarySensor *charging{}; number::Number *brightness{}; }; +class BlockView { public: virtual ~BlockView(); + lv_obj_t *root() const; const std::string &id() const; + virtual bool owns(const std::string &id) const; + virtual void apply(const StateUpdate &u, uint32_t now_ms); + virtual void on_local_update(); // battery / charging / brightness changed + virtual void loop(uint32_t now_ms); }; +std::unique_ptr make_block_view(lv_obj_t *parent, const Block &block, const Theme &theme, ControlSink &sink, const LocalSources &local); +``` + + - **Messages** (spec §5.9): the "no layout" detail is `App.get_name() + " · v" + ESPHOME_PROJECT_VERSION`. + - **`ui.yaml` additions:** + - the `ha_controller:` block wired to the Task 4 ids; + - `on_control` → `homeassistant.event` `esphome.ha_controller_control`, with data `block`, `item`, `op` and `value: !lambda 'return str_sprintf("%.2f", value);'`; + - `api: on_client_connected: [delay: 5s, script.execute: {id: send_hello, reason: connected}]`; + - API actions `set_layout` (`layout: string`), which calls `id(ui).set_layout(layout)` then `script.execute {id: send_hello, reason: applied}`, and `set_states` (`states: string`); + - script `send_hello` (`parameters: {reason: string}`, `mode: queued`) firing `esphome.ha_controller_hello` with data `node` (`App.get_name()`), `version: ${project_version}`, `protocol: "1"`, `revision` (`id(ui).get_revision()`) and `reason`; + - `interval: 60s`, which runs the script with reason `heartbeat` when `api.connected`. + - **Fallback for event data:** if ESPHome rejects lambdas in `homeassistant.event` `data:`, use `variables:` + `data_template:` with the same keys. + +- [ ] **Step 1: Implement the codegen and the C++ component.** + - In this task, `make_block_view` returns a basic view: a full-screen object with the block background and its name centred in `text_fonts[block.font]` and `text_color_for(bg)`. + - The component builds its own screen (`lv_obj_create(nullptr)` + `lv_screen_load`) in `setup()`. It shows "Waiting for Home Assistant" until a layout arrives, and in this task it shows only the current block. + - `setup()` registers the battery/charging/brightness state callbacks once, and they forward to `view->on_local_update()`. + +- [ ] **Step 2: Write `esphome/simulator.yaml`**: + - `packages`: `version` and `ui`. + - `esphome:`: name `ha-controller-sim`, friendly name `HA Controller Simulator`, the same `project`. + - `host:`, `logger:`, `api:`. + - `display: [{platform: sdl, id: amoled, dimensions: {width: 466, height: 466}, auto_clear_enabled: false, update_interval: never}]` and `touchscreen: [{platform: sdl, id: touch, display: amoled}]`. + - Template stand-ins: `sensor` `battery_level` (constant 76, unit %), `binary_sensor` `battery_charging` (false), and `number` `screen_brightness` (5–100, optimistic, no `on_value`). + - `external_components` (local). + +- [ ] **Step 3: Compile both configs** + +Run: `esphome/.venv/bin/esphome compile esphome/ha-controller.yaml && esphome/.venv/bin/esphome compile esphome/simulator.yaml` +Expected: both `SUCCESS`. The simulator needs SDL2: `brew install sdl2` or `apt install libsdl2-dev`. + +- [ ] **Step 4: End-to-end check with Home Assistant**, using plan 2's integration and plan 3's built panel. + 1. Run `esphome/.venv/bin/esphome run esphome/simulator.yaml`. The window shows "Waiting for Home Assistant". + 2. In Home Assistant, add an ESPHome device on `:6053`, then add the HA Controller integration and pick "HA Controller Simulator". + 3. Within 5 s of the connection, the simulator shows "No blocks yet". Developer tools › Events shows `esphome.ha_controller_hello` with reasons `connected` and then `applied`. + 4. In the panel, add three blocks and save. The simulator shows the start block's name on its background. + 5. Heartbeat hellos arrive every 60 s with a revision equal to the panel's. + +- [ ] **Step 5: Extend CI and the docs.** In `firmware.yml` `compile`, add `sudo apt-get install -y libsdl2-dev` and `esphome compile esphome/simulator.yaml`. Add the simulator commands to `.claude/CLAUDE.md`. + +- [ ] **Step 6: Commit** + +```bash +git add esphome .github/workflows/firmware.yml .claude/CLAUDE.md +git commit -m "feat(firmware): receive layouts and talk to Home Assistant" +``` + +--- + +### Task 6: Pager — edge swipes, slide animation, edge hints + +**Files:** +- Create: `esphome/components/ha_controller/pager.h`, `pager.cpp` +- Modify: `esphome/components/ha_controller/ha_controller.h`, `ha_controller.cpp` + +**Interfaces:** +- Consumes: `classify_edge`, `step_for`, `SwipeTracker` and `settle_duration_ms` (Task 3); `Layout::find_at` (Task 1). +- Produces: + +```cpp +struct PageRef { std::string id; int x; int y; lv_obj_t *obj; }; +class Pager { + public: + void attach(lv_obj_t *screen, int size, int edge_width); // creates viewport, edge overlay on lv_layer_top(), 4 hint arcs + lv_obj_t *viewport() const; // parent for page objects + void set_pages(std::vector pages, const std::string &show_id); // cancels animations, resets tracker, shows one page + void set_enabled(bool enabled); // false while a message is shown + const std::string ¤t_id() const; +}; +``` + +- **Edge overlay:** a transparent full-screen object with `LV_OBJ_FLAG_CLICKABLE | LV_OBJ_FLAG_ADV_HITTEST`. On `LV_EVENT_HIT_TEST` it sets `res` to `classify_edge(point) != NONE`. + - `PRESSED` begins the tracker. The target is `find_at(current + step_for(edge))`. A present target page is unhidden at its offset. + - `PRESSING` updates the tracker and positions the pages: current at `(-dx·offset, -dy·offset)`, target at `(dx·(size−offset), dy·(size−offset))`. + - `RELEASED` and `PRESS_LOST` release the tracker and animate with `lv_anim_path_ease_out` over `settle_duration_ms(remaining, size)`. On completion, commit (the target becomes current, the old page is hidden, the hints are refreshed) or cancel (the target is hidden). + - Presses during an animation are ignored. +- **Hints:** four non-clickable arcs on the top layer: + - RIGHT 350°→10°, BOTTOM 80°→100°, LEFT 170°→190°, TOP 260°→280°; + - size 458 px, width 6, white at `LV_OPA_60`, indicator and knob hidden; + - visible only where `find_at` has a neighbour. + +- [ ] **Step 1: Implement `Pager` and use it from `HaController`.** `set_layout` builds the views under `pager.viewport()`, then calls `set_pages`. + +- [ ] **Step 2: Compile both configs** + +Run: `esphome/.venv/bin/esphome compile esphome/ha-controller.yaml && esphome/.venv/bin/esphome compile esphome/simulator.yaml` +Expected: `SUCCESS`. + +- [ ] **Step 3: Simulator check.** Build the reference map in the panel: Kitchen start, Lights above, Hello World left, Bedroom below Hello World. Expected: + - From Kitchen, a mouse-drag from the left edge to the right slides to Hello World. + - From the top edge downwards, it slides to Lights. + - From the right edge leftwards, it rubber-bands by at most 48 px and returns. + - From Hello World, the bottom edge upwards slides to Bedroom. + - A drag starting in the centre does nothing. + - A short slow drag snaps back; a quick flick commits. + - The hints match the neighbours. + - Saving a layout from the panel while holding a drag shows the new layout cleanly, with no stuck half-page. + +- [ ] **Step 4: Device check.** Flash and repeat Step 3 with a finger. The slides look smooth (no visible stutter at ~30 fps or better). If they don't, try in order and keep the best: + 1. `lvgl: buffer_size: 100%`; + 2. `esp32: framework: sdkconfig_options: {CONFIG_ESP32S3_DATA_CACHE_64KB: "y", CONFIG_ESP32S3_DATA_CACHE_LINE_64B: "y"}`; + 3. `lvgl: buffer_size: 12%`. + + Note the result for `docs/hardware.md`. + +- [ ] **Step 5: Commit** + +```bash +git add esphome/components/ha_controller esphome/packages +git commit -m "feat(firmware): navigate between blocks with edge swipes" +``` + +--- + +### Task 7: Block views — light knob, climate knob, custom items + +**Files:** +- Modify: `esphome/components/ha_controller/widgets.h`, `widgets.cpp`, `ha_controller.cpp` + +**Interfaces:** +- Consumes: `KnobScale`, `format_value`, `format_percent`, `InteractionHold`, `StateUpdate`, `text_color_for` and `ControlSink` (Tasks 2, 5). +- Produces: `LightView`, `ClimateView` and `CustomView` behind `make_block_view`, following spec §5.5–§5.8 and §5.10. + - **Geometry:** knob arc 370 px, width 28, background angles 135°→45°, `LV_OBJ_FLAG_ADV_HITTEST` so only the ring takes touches. The name sits 96 px from the top. + - **Controls:** + - Arc `LV_EVENT_VALUE_CHANGED` updates the centre label only. + - Arc `LV_EVENT_RELEASED` → `sink.on_control(block, "", "set", value)`. + - A centre tap on a dimmable light → `"toggle"`. The toggle button on an on/off-only light → `"toggle"`. + - Every interaction calls `hold.touch(millis())`. + - **`apply()`:** while the hold is active, store the update as pending. `loop()` applies the pending update once the hold has expired. + - **Unavailable entity:** the centre shows `—` with a small `Unavailable` label, and the arc or button gets `LV_STATE_DISABLED`. + - **Custom items:** + - `text`, `emoji`, `entity` → labels, with `entity` text from `StateUpdate::text`. + - `battery` → a row with `🔋` (or `⚡` while charging) and `format_percent(level)`. + - `brightness` → a row with `☀` and a 220 px slider (5–100). It calls `brightness->make_call().set_value(v).perform()` at most every 100 ms while dragging and always on release, and follows the number's state in `on_local_update()`. + - A custom block without items shows its name centred. + +- [ ] **Step 1: Implement the three views.** + +- [ ] **Step 2: Compile both configs** + +Run: `esphome/.venv/bin/esphome compile esphome/ha-controller.yaml && esphome/.venv/bin/esphome compile esphome/simulator.yaml` +Expected: `SUCCESS`. + +- [ ] **Step 3: Simulator + Home Assistant check.** Use the reference map with real or template entities. Expected: + 1. **Light:** + - The knob shows Home Assistant's brightness. + - Dragging to about 30 % and releasing sets the light to 30 % (logbook). + - A centre tap toggles it. + - A brightness change in Home Assistant moves the knob within 1 s. + - While dragging, incoming updates do not move the knob. + 2. **On/off-only light:** a toggle button. + 3. **Climate:** steps of 0.5 °C; release updates the target; `Now …` and the action are shown. + 4. **Custom block:** + - text, emoji and the outdoor temperature are shown, and the temperature follows sensor changes; + - the battery row shows `🔋 76 %`; + - the brightness slider changes `number.*_screen_brightness`. + 5. **Renamed entity:** renaming one bound entity in Home Assistant shows `—` + `Unavailable` and disables its control. + +- [ ] **Step 4: Device check.** + - Repeat checks 1, 3 and 4 on hardware. + - The battery row shows the real level. + - The brightness slider dims the panel smoothly. + - With the battery unplugged, the row shows `🔋 — %` and nothing crashes. + +- [ ] **Step 5: Commit** + +```bash +git add esphome/components/ha_controller +git commit -m "feat(firmware): render light, climate and custom blocks" +``` + +--- + +### Task 8: Screen sleep and wake + +**Files:** +- Create: `esphome/components/ha_controller/sleep.h`, `esphome/tests/test_sleep.cpp` +- Modify: + - `esphome/components/ha_controller/__init__.py`, `ha_controller.h`, `ha_controller.cpp` + - `esphome/packages/ui.yaml`, `esphome/packages/board-waveshare-amoled-175.yaml` + - `esphome/simulator.yaml` + +**Interfaces:** +- Consumes: `Layout::sleep_s` (Task 1); spec §5.11. +- Produces: + +```cpp +// sleep.h (pure) +constexpr uint32_t DEFAULT_SLEEP_S = 20; +bool should_sleep(uint32_t inactive_ms, uint32_t timeout_s); // false when timeout_s == 0; true iff inactive_ms >= timeout_s * 1000 +// HaController additions +void set_sleep_timeout(uint32_t seconds); // set_layout passes layout.sleep_s; DEFAULT_SLEEP_S until the first layout +bool is_sleeping() const; +void wake(); // no-op when awake; otherwise fire on_wake, then lv_display_trigger_activity(nullptr) +``` + + - **`ha_controller:` additions:** + - Required `touchscreen` (id). The component registers a `touchscreen::TouchListener` whose `release()` calls `wake()` while sleeping. + - Triggers `on_sleep` and `on_wake` (no variables). + - **`loop()`:** while awake, when `should_sleep(lv_display_get_inactive_time(nullptr), timeout)` holds, mark the screen as sleeping and fire `on_sleep`. + - **`show_message()`:** calls `wake()` first. + - **YAML wiring:** + - **Board package:** script `screen_on` runs `id(amoled).set_brightness((uint8_t) lroundf(id(screen_brightness).state * 2.55f));`, and script `screen_off` runs `id(amoled).set_brightness(0);`. The `screen_brightness` `on_value` becomes "if `!id(ui).is_sleeping()` then `script.execute: screen_on`". + - **Simulator:** scripts `screen_on` and `screen_off` that only log. + - **`ui.yaml`:** + - `ha_controller:` gets `touchscreen: touch`; + - `on_sleep: [script.execute: screen_off, lvgl.pause]`; + - `on_wake: [lvgl.resume, lvgl.widget.redraw, script.execute: screen_on]`. + +- [ ] **Step 1: Write the failing tests** in `test_sleep.cpp`. + +```cpp +CHECK(DEFAULT_SLEEP_S == 20); +CHECK_FALSE(should_sleep(10'000'000, 0)); // 0 = never +CHECK_FALSE(should_sleep(19'999, 20)); CHECK(should_sleep(20'000, 20)); +CHECK_FALSE(should_sleep(3'599'999, 3600)); CHECK(should_sleep(3'600'000, 3600)); +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `cmake --build esphome/tests/build` +Expected: FAIL (`sleep.h` not found). + +- [ ] **Step 3: Implement `sleep.h`** + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `cmake --build esphome/tests/build && ctest --test-dir esphome/tests/build --output-on-failure` +Expected: PASS. + +- [ ] **Step 5: Implement the component additions and the YAML wiring, then compile both configs** + +Run: `esphome/.venv/bin/esphome compile esphome/ha-controller.yaml && esphome/.venv/bin/esphome compile esphome/simulator.yaml` +Expected: `SUCCESS`. + +- [ ] **Step 6: Simulator check.** Expected: + - After 20 s without input, the log shows `screen_off` and the window stops updating. + - Clicking the light knob position wakes the screen without toggling or moving anything. + - Setting the delay to 5 s in the panel makes the screen sleep after 5 s; `0` keeps it awake. + - A Home Assistant state change made while asleep is visible right after waking. + +- [ ] **Step 7: Device check.** Expected: + - The panel goes black after the delay. + - A tap on the knob area only wakes the screen, and the screen stays awake for the full delay afterwards. + - Changing `Screen brightness` from Home Assistant while asleep keeps the panel dark, and the new level shows on wake. + +- [ ] **Step 8: Commit** + +```bash +git add esphome +git commit -m "feat(firmware): sleep after the configured delay and wake on touch" +``` + +--- + +### Task 9: OTA install action, firmware docs, skills and reviewer agent + +**Files:** +- Create: + - `docs/hardware.md` + - `.claude/skills/firmware-dev/SKILL.md`, `.claude/skills/add-widget/SKILL.md` + - `.claude/agents/firmware-reviewer.md` +- Modify: `esphome/ha-controller.yaml`, `docs/development.md` ("Firmware" section), `docs/README.md`, `.claude/CLAUDE.md` + +**Interfaces:** +- Produces (used by plan 5): the device API action `install_firmware` (`url: string`, `md5_url: string`): + +```yaml +ota: + - platform: esphome + - platform: http_request +http_request: + verify_ssl: true +api: + actions: + - action: install_firmware + variables: {url: string, md5_url: string} + then: + - lambda: |- + id(ui).show_message("Updating firmware…", "Do not unplug the screen"); + - ota.http_request.flash: + url: !lambda return url; + md5_url: !lambda return md5_url; + - lambda: |- + id(ui).show_message("Update failed", "Check the screen's internet access"); + - delay: 5s + - lambda: id(ui).hide_message(); +``` + + The action lives in the device config only, because the simulator has no HTTP OTA. + +- [ ] **Step 1: Add the action, then compile** + +Run: `esphome/.venv/bin/esphome compile esphome/ha-controller.yaml` +Expected: `SUCCESS`. + +- [ ] **Step 2: OTA check on hardware.** + 1. Bump `esphome/version.yaml` locally to `0.1.1` (do not commit) and compile. + 2. Find the build output with `find esphome/.esphome/build -name firmware.ota.bin`. In that directory, create `firmware.ota.bin.md5` with `md5 -q firmware.ota.bin > firmware.ota.bin.md5` (Linux: `md5sum firmware.ota.bin | cut -d' ' -f1 > firmware.ota.bin.md5`), then serve it with `python3 -m http.server 8000 -d `. + 3. Call `esphome.ha_controller__install_firmware` from Developer tools with the LAN URLs. The screen shows "Updating firmware…", reboots, and the next hello carries `0.1.1`. Run it once while the screen sleeps: it must wake first. + 4. Repeat with a wrong `.md5`. The screen shows "Update failed" for 5 s, then the pages return. + 5. Revert `version.yaml`. + +- [ ] **Step 3: Write the docs.** + - **`docs/hardware.md`:** + - the board summary and pin table (spec §4); + - power and battery notes; + - the AXP2101 registers; + - the performance settings chosen in Task 6; + - any font fallback chosen in Task 4; + - enclosures: link `../3D_models/` (with or without a PWR button). + - **`docs/development.md`, "Firmware" section:** + - prerequisites: Python 3.13 venv with `esphome/requirements.txt`, CMake, SDL2; + - commands: host tests, compile, flash over USB, simulator; + - connecting Home Assistant to the simulator; + - the manual hardware checklist (Task 4 Step 7, Task 6 Steps 3–4, Task 7 Steps 3–4, Task 8 Steps 6–7, Task 9 Step 2). + - **`docs/README.md`:** link `hardware.md`. + +- [ ] **Step 4: Write the Claude guidance.** + - **`.claude/skills/firmware-dev/SKILL.md`:** + - `name: firmware-dev`. + - `description:` "Use when building, flashing, simulating or changing the ESPHome firmware (esphome/), including LVGL UI code." + - Body: + - commands; + - simulator loop; + - rules: + - pure logic goes in host-tested modules; + - LVGL is called on the main loop only; + - views never register ESPHome callbacks; + - call `lv_refr_now` before blocking work; + - LVGL is paused while the screen sleeps, so call `wake()` before showing anything the user must see; + - fonts are declared in `ui.yaml` and mapped in `ha_controller:`; + - new LVGL widget types need a hidden instance on `boot_page`; + - controls stay inside radius 185; + - keep the `cst9217` SHA pinned. + - **`.claude/skills/add-widget/SKILL.md`:** + - `name: add-widget`. + - `description:` "Use when adding a new block widget or custom item kind (e.g. switch, cover, fan, media volume) end-to-end." + - Body, a checklist that starts with the `protocol-change` skill: + 1. protocol doc and fixtures; + 2. `ENTITY_BLOCK_DOMAINS` / `ITEM_KINDS` in `const.py` and the panel model; + 3. state builder and control mapping; + 4. panel editor options and preview; + 5. C++ parser enum and view; + 6. `docs/configuration.md`; + 7. run all suites and both compiles. + - **`.claude/agents/firmware-reviewer.md`:** + - `name: firmware-reviewer`, `tools: Read, Grep, Glob, Bash`. + - `description:` "Reviews changes under esphome/ for ESPHome/LVGL correctness, memory and hardware safety. Use before merging firmware changes." + - Checklist: + - no blocking calls in `loop` except the OTA action; + - LVGL objects deleted with their views, with animations cancelled first; + - no ESPHome callbacks registered per view; + - JSON parsed defensively; + - pins and addresses match `docs/hardware.md`; + - host tests for new pure logic; + - both configs compile. + - Output: `file:line — issue — fix`. + - **`.claude/CLAUDE.md`:** list the skills and the agent. + +- [ ] **Step 5: Run every suite** + +Run: `pytest custom_components/ha_controller/tests && pytest .github/scripts/tests && npm --prefix custom_components/ha_controller/frontend test && ctest --test-dir esphome/tests/build --output-on-failure` +Expected: PASS. + +- [ ] **Step 6: Commit** + +```bash +git add esphome/ha-controller.yaml docs .claude .claude/CLAUDE.md +git commit -m "feat(firmware): install firmware over the air on request" +``` diff --git a/docs/superpowers/plans/2026-11-16-ha-controller-5-release.md b/docs/superpowers/plans/2026-11-16-ha-controller-5-release.md new file mode 100644 index 0000000..b2ae0ab --- /dev/null +++ b/docs/superpowers/plans/2026-11-16-ha-controller-5-release.md @@ -0,0 +1,344 @@ +# HA Controller — Plan 5: Versioning, Firmware Updates, Web Installer and Releases + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Ship the integration and the firmware as one version: +- a version check and bump script; +- a firmware update entity in Home Assistant that keeps each screen on the integration's exact version, automatically by default; +- a GitHub Pages web installer that shows the version it flashes; +- a tag-driven release workflow that publishes the HACS zip, the firmware binaries and the Pages site. + +**Architecture:** +- **Versioning:** `.github/scripts/versioning.py` owns the version rule. +- **Updates:** the integration's `update` platform asks the screen, through plan 4's `install_firmware` action, to download its OTA image for the integration version from GitHub Pages. +- **Release scripts:** three small, unit-tested scripts collect the firmware, package the integration and assemble the Pages site from GitHub release assets. +- **Workflow:** `release.yml` chains them on a `vX.Y.Z` tag. A manual run is a dry run. + +**Tech Stack:** Python 3.14 (integration, scripts, tests), Python 3.13 (ESPHome CLI in CI), GitHub Actions, `gh` CLI, ESP Web Tools 10.5.2, HACS. + +**Spec:** `docs/superpowers/specs/2026-11-16-ha-controller-design.md` (§10, §11) + +## Global Constraints + +- **Version:** one SemVer `X.Y.Z` in `custom_components/ha_controller/manifest.json`, `esphome/version.yaml`, `custom_components/ha_controller/frontend/package.json` and `custom_components/ha_controller/frontend/package-lock.json` (root `version` and `packages[""].version`). Change it only with `.github/scripts/versioning.py bump`. +- **URLs:** firmware OTA `https://pyxel-dev.github.io/HA-controller/firmware//ha-controller.ota.bin` (+ `.md5`); release notes `https://github.com/pyxel-dev/HA-controller/releases/tag/v`. +- **Release assets:** `ha_controller.zip`, `ha-controller-.factory.bin`, `ha-controller-.ota.bin`, `ha-controller-.ota.bin.md5`. The `.md5` file holds exactly 32 lowercase hex characters and no newline. +- **Timings:** install timeout 300 s; auto-update at most once per screen and version every 3600 s; auto-update only when the integration version matches `^\d+\.\d+\.\d+$`. +- **Strings:** English only. +- **Python environments:** + - release scripts and their tests: `.github/scripts/.venv`; + - integration tests: `custom_components/.venv`; + - ESPHome: `esphome/.venv`. + +## Review Focus + +1. **OTA failing repeatedly** (no internet, Pages outage). Expected: one automatic attempt per hour per version, never a storm. Owner: Task 2 `test_auto_update_installs_at_most_once_per_hour`. +2. **Screen newer than the integration** after an integration rollback. Expected: the update entity offers the integration's version and auto-update installs it. Owner: Task 2 `test_newer_firmware_is_offered_as_update`. +3. **Tag and version mismatch, or a non-SemVer tag.** Expected: the workflow fails before anything is published. Owner: Task 1 `test_check_tag_must_match`; in Task 4 the version check is the first build step. +4. **Pages rebuild dropping older OTA images.** Screens on an older integration could no longer update. Owner: Task 3 `test_build_site_keeps_every_release`. +5. **Install requested while the screen is offline or already updating.** Expected: a clear error and no second install. Owner: Task 2 `test_install_when_offline_raises`, `test_install_while_in_progress_raises`. + +--- + +### Task 1: Version check and bump + +**Files:** +- Create: `.github/scripts/versioning.py`, `.github/scripts/tests/__init__.py`, `.github/scripts/tests/test_versioning.py` +- Modify: `.github/workflows/ci.yml` (job `versions`), `.claude/CLAUDE.md` + +**Interfaces:** +- Produces: + - `VERSION_RE = re.compile(r"^\d+\.\d+\.\d+$")` + - `def read_versions(root: Path) -> dict[str, str]`, keyed by `manifest`, `esphome`, `frontend`, `frontend-lock`. The `esphome` value comes from the line `project_version: "X.Y.Z"`, and `frontend-lock` must agree in both lock positions. + - `def check_versions(root: Path, tag: str | None = None) -> list[str]`: human-readable errors, `[]` when consistent; `tag` must equal `v` + version. + - `def bump_version(root: Path, version: str) -> None`: raises `ValueError` on non-SemVer input. Rewrites JSON with 2-space indent and a trailing newline, and edits only the YAML line. + - `def main(argv: list[str] | None = None) -> int`: `check [--tag vX.Y.Z]` → 0/1, `bump X.Y.Z` → 0. + +- [ ] **Step 1: Write the failing tests.** A `repo(tmp_path)` fixture writes the four files at `0.1.0`. + +```python +def test_read_versions(repo): assert set(read_versions(repo).values()) == {"0.1.0"} +def test_check_passes_when_equal(repo): assert check_versions(repo) == [] +def test_check_reports_mismatch(repo): ... # manifest 0.2.0 → one error naming "manifest", "0.2.0" and "0.1.0" +def test_check_tag_must_match(repo): + assert check_versions(repo, "v0.1.0") == [] and check_versions(repo, "v0.1.1") and check_versions(repo, "0.1.0") +def test_check_rejects_non_semver(repo): ... # all files "0.1" → error +def test_bump_rewrites_all(repo): ... # bump 1.2.3 → all four "1.2.3"; other JSON keys and YAML lines preserved +@pytest.mark.parametrize("bad", ["1.2", "v1.2.3", "1.2.3-rc1"]) +def test_bump_rejects_invalid(repo, bad): ... +def test_repository_versions_are_consistent(): assert check_versions(REPO_ROOT) == [] +def test_main_exit_codes(repo): ... +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `pytest .github/scripts/tests/test_versioning.py -v` +Expected: FAIL. + +- [ ] **Step 3: Implement `.github/scripts/versioning.py`.** + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `pytest .github/scripts/tests -v && python .github/scripts/versioning.py check` +Expected: PASS, exit 0. + +- [ ] **Step 5: Add CI and the docs.** Add job `versions` to `ci.yml` (setup-python 3.14, `python .github/scripts/versioning.py check`). Add the commands to `.claude/CLAUDE.md`, and replace its plan-5 placeholder rule with the real command. + +- [ ] **Step 6: Commit** + +```bash +git add .github/scripts/versioning.py .github/scripts/tests .github/workflows/ci.yml .claude/CLAUDE.md +git commit -m "build: add single-version check and bump script" +``` + +--- + +### Task 2: Firmware update entity, auto-update and options flow + +**Files:** +- Create: `custom_components/ha_controller/firmware.py`, `custom_components/ha_controller/update.py`, `custom_components/ha_controller/tests/test_update.py` +- Modify: + - `custom_components/ha_controller/controller.py`, `__init__.py` (`PLATFORMS = [Platform.UPDATE]`), `config_flow.py` (options flow) + - `strings.json`, `translations/en.json` + +**Interfaces:** +- Consumes: plan 2's `ScreenController` (`device`, `integration_version`, `async_call_device`, `async_add_listener`, hello handling); plan 4's device action `install_firmware(url, md5_url)`. +- Produces: + - **`firmware.py`:** `def firmware_urls(version: str) -> tuple[str, str]`, returning the `.ota.bin` URL and its `.md5` URL, and `def is_release_version(version: str) -> bool`. + - **`ScreenController` additions:** + - `install_in_progress: bool`. + - `async def async_install_firmware(self, version: str) -> None`. It raises `HomeAssistantError`: + - "The screen is offline." when it is not online; + - "A firmware update is already running." when an install is in progress; + - when the device call fails; + - "Firmware update to {version} did not complete." when no hello with `{version}` arrives within 300 s. + + It notifies listeners when the install starts and when it ends. + - Auto-update inside `async_handle_hello`: when `entry.options.get(CONF_AUTO_UPDATE, True)`, the integration version is a release, the hello version differs from it, no install is running, and the last automatic attempt for that version is at least 3600 s old, then start `hass.async_create_background_task(...)` that installs and logs any failure. + - **`update.py`:** `FirmwareUpdateEntity(UpdateEntity)`. + - Entity setup: `has_entity_name`, `translation_key = "firmware"` ("HA Controller firmware"), `unique_id = f"{device_id}-firmware"`, `device_info = DeviceInfo(connections=.connections)`. + - Features: `INSTALL | PROGRESS`, `title = "HA Controller"`. + - Versions: `installed_version = controller.device.version` and `latest_version = controller.integration_version`. + - `release_url = RELEASE_URL.format(version=latest)` and `in_progress = controller.install_in_progress`. + - `version_is_newer(latest, installed)` returns `latest != installed`. + - `async_install(version, backup, **kwargs)` installs `latest_version`. + - `async_added_to_hass` subscribes `async_write_ha_state` to the controller. + - **Options flow:** `OptionsFlowHandler(OptionsFlow)` with step `init`: a boolean `auto_update` defaulting to the current option or `True`. `HaControllerConfigFlow.async_get_options_flow(config_entry)` returns `OptionsFlowHandler()`. + - **Strings:** + - `entity.update.firmware.name` = "HA Controller firmware". + - Options step `init`: title "HA Controller options"; `auto_update` label "Update the screen firmware automatically"; description "Installs the firmware that matches this integration's version whenever the screen reports a different one." + +- [ ] **Step 1: Write the failing tests.** Mock the `esphome.ha_controller_aabbcc_install_firmware` service and drive time with `freezer`. + +```python +async def test_unknown_before_first_hello(hass): ... # state "unknown" +async def test_update_entity_reports_versions(hass): ... # hello 0.0.9 → state "on", installed 0.0.9, latest 0.1.0, release_url …/tag/v0.1.0 +async def test_update_entity_off_when_versions_match(hass): ... +async def test_newer_firmware_is_offered_as_update(hass): ... # hello 0.2.0 → "on" +async def test_install_calls_device_and_completes_on_hello(hass): ... + # auto_update off; update.install → call data {"url": ".../firmware/0.1.0/ha-controller.ota.bin", "md5_url": "....ota.bin.md5"} + # in_progress True until hello version 0.1.0 → state "off", in_progress False +async def test_install_times_out(hass, freezer): ... # +301 s → HomeAssistantError, in_progress False +async def test_install_when_offline_raises(hass): ... +async def test_install_while_in_progress_raises(hass): ... +async def test_auto_update_installs_at_most_once_per_hour(hass, freezer): ... # hello 0.0.9 ×2 → 1 call; +3601 s → 2 calls +async def test_auto_update_disabled_by_option(hass): ... +async def test_auto_update_skipped_for_dev_versions(hass): ... # controller integration version "0.2.0.dev0" → no call +async def test_options_flow_toggles_auto_update(hass): ... +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `pytest custom_components/ha_controller/tests/test_update.py -v` +Expected: FAIL. + +- [ ] **Step 3: Implement `firmware.py`, the controller additions, `update.py` and the options flow.** + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `pytest custom_components/ha_controller/tests -v && ruff check custom_components` +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add custom_components/ha_controller custom_components/ha_controller/tests/test_update.py +git commit -m "feat(integration): keep screen firmware on the integration version" +``` + +--- + +### Task 3: Release scripts and the web installer page + +**Files:** +- Create: + - `.github/scripts/collect_firmware.py`, `.github/scripts/package_integration.py`, `.github/scripts/build_pages.py` + - `esphome/web/index.html` + - `.github/scripts/tests/test_release_scripts.py` + +**Interfaces:** +- Consumes: the plan 3 bundle `custom_components/ha_controller/frontend/dist/ha-controller-panel.js`; the ESPHome build tree (`esphome/.esphome/build/**/firmware.factory.bin`, `firmware.ota.bin`). +- Produces (each has an `argparse` CLI with the same parameters): + - **`collect(build_dir: Path, version: str, out_dir: Path) -> list[Path]`.** Requires exactly one `*.factory.bin` and one `*.ota.bin` under `build_dir`, otherwise it raises `ValueError`. It writes `ha-controller-.factory.bin`, `ha-controller-.ota.bin` and `ha-controller-.ota.bin.md5`. + - **`package(root: Path, out_file: Path) -> Path`.** Zips the contents of `custom_components/ha_controller/` at the zip root, excluding `tests/`, `__pycache__/`, `*.pyc`, and everything under `frontend/` except `frontend/dist/ha-controller-panel.js`. Raises `FileNotFoundError("Build the panel first: npm --prefix custom_components/ha_controller/frontend run build")` when the bundle is missing. + - **`build_site(web_dir: Path, releases_dir: Path, latest: str, out_dir: Path) -> None`.** `releases_dir//` holds each release's assets. It writes: + - `index.html`, with every `{{VERSION}}` replaced by `latest`; + - `.nojekyll`; + - `firmware/ha-controller.factory.bin`, copied from `latest`; + - `firmware//ha-controller.ota.bin` and `.md5` for **every** version; + - `firmware/manifest.json`: + +```json +{"name": "HA Controller", "version": "", "home_assistant_domain": "esphome", "new_install_prompt_erase": true, + "builds": [{"chipFamily": "ESP32-S3", + "parts": [{"path": "ha-controller.factory.bin", "offset": 0}], + "ota": {"path": "/ha-controller.ota.bin", "md5": "", + "release_url": "https://github.com/pyxel-dev/HA-controller/releases/tag/v"}}]} +``` + + - **`esphome/web/index.html`:** a self-contained English page with inline CSS following `prefers-color-scheme`, titled "HA Controller — Web installer". It contains: + - the subtitle "Firmware {{VERSION}}" and a release-notes link `…/releases/tag/v{{VERSION}}`; + - ``; + - `` with slots `unsupported` ("Use Chrome or Edge on a desktop computer.") and `not-allowed` ("Open this page over HTTPS."); + - five steps: + 1. connect the screen with USB-C; + 2. click Install; + 3. set up Wi-Fi when asked, or join the "HA Controller" access point; + 4. add the screen in Home Assistant (ESPHome); + 5. install the HA Controller integration **{{VERSION}}** from HACS; + - the tip "If the board is not detected, hold BOOT while plugging it in." + +- [ ] **Step 1: Write the failing tests** + +```python +def test_collect_writes_versioned_files_and_md5(tmp_path): ... # .md5 == hashlib.md5(ota).hexdigest(), 32 chars, no newline +def test_collect_requires_exactly_one_of_each(tmp_path): ... # none → ValueError; two factory bins → ValueError +def test_package_zips_integration_with_panel(tmp_path): ... # names include "manifest.json", "frontend/dist/ha-controller-panel.js"; no __pycache__, tests/, frontend/src or frontend/package.json +def test_package_requires_built_panel(tmp_path): ... +def test_build_site_manifest(tmp_path): ... # exact dict above for latest 0.2.0 +def test_build_site_keeps_every_release(tmp_path): ... # releases 0.1.0 + 0.2.0 → both firmware//ha-controller.ota.bin(.md5) +def test_build_site_renders_version(tmp_path): ... # index.html contains "Firmware 0.2.0", no "{{VERSION}}"; .nojekyll exists +def test_build_site_requires_latest_assets(tmp_path): ... +def test_web_page_template(): ... # real esphome/web/index.html: ≥ 2 "{{VERSION}}" and "esp-web-tools@10.5.2" +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `pytest .github/scripts/tests/test_release_scripts.py -v` +Expected: FAIL. + +- [ ] **Step 3: Implement the three scripts and `index.html`.** + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `pytest .github/scripts/tests -v` +Expected: PASS. + +- [ ] **Step 5: Preview locally.** + 1. Build a fake site from the scripts' test data: `python .github/scripts/build_pages.py --web esphome/web --releases --latest 0.1.0 --out site`. + 2. Serve it with `python3 -m http.server -d site`. + 3. Open it in Chrome and confirm the page shows "Firmware 0.1.0" and an Install button. + +- [ ] **Step 6: Commit** + +```bash +git add .github/scripts esphome/web +git commit -m "build: add release packaging scripts and web installer page" +``` + +--- + +### Task 4: Release workflow, HACS packaging, user docs and release skill + +**Files:** +- Create: + - `.github/workflows/release.yml` + - `docs/getting-started.md`, `docs/updates.md`, `docs/releasing.md` + - `.claude/skills/release/SKILL.md` +- Modify: `hacs.json`, `README.md`, `docs/README.md`, `.claude/CLAUDE.md` + +**Interfaces:** +- Consumes: Tasks 1–3, `esphome/requirements.txt` and the `npm` scripts. +- Produces: + - **`hacs.json`:** `{"name": "HA Controller", "homeassistant": "2026.10.0", "zip_release": true, "filename": "ha_controller.zip"}`. + - **`release.yml`.** Triggers: `push` on tags `v*` and `workflow_dispatch` (dry run). Permissions: `contents: write`, `pages: write`, `id-token: write`. Concurrency group `release`. + - **Job `build`** (`ubuntu-latest`). Steps, in order: + 1. Checkout, then setup-python 3.13 and setup-node 24 with the npm cache. + 2. Read the version from `manifest.json` into an output. + 3. `python .github/scripts/versioning.py check`, plus `--tag "$GITHUB_REF_NAME"` on tag runs. + 4. `npm --prefix custom_components/ha_controller/frontend ci` and `npm --prefix custom_components/ha_controller/frontend run build`. + 5. `python .github/scripts/package_integration.py --out dist/ha_controller.zip`. + 6. `pip install -r esphome/requirements.txt` and `esphome compile esphome/ha-controller.yaml`. + 7. `python .github/scripts/collect_firmware.py --build-dir esphome/.esphome/build --version --out dist`. + 8. `actions/upload-artifact@v4` (`dist`). + - **Job `release`** (needs `build`, tag runs only): download the artifact, then `gh release create "$GITHUB_REF_NAME" dist/* --title "$GITHUB_REF_NAME" --generate-notes --verify-tag` with `GH_TOKEN`. + - **Job `pages`** (needs `build` and `release`, tag runs only, environment `github-pages`): + 1. Checkout. + 2. For every tag from `gh release list --limit 200 --json tagName -q '.[].tagName'`, run `gh release download "$tag" -p 'ha-controller-*' -D "releases/${tag#v}"`. + 3. `python .github/scripts/build_pages.py --web esphome/web --releases releases --latest --out site`. + 4. `actions/configure-pages@v5`, `actions/upload-pages-artifact@v3` (`site`) and `actions/deploy-pages@v4`. + +- [ ] **Step 1: Write the workflow and update `hacs.json`.** + +- [ ] **Step 2: Dry run.** Push the branch, run "Release" with `workflow_dispatch`, and download the `dist` artifact. Expected: + - the `build` job is green and `release`/`pages` are skipped; + - the artifact holds `ha_controller.zip` (with `frontend/dist/ha-controller-panel.js` inside, and no `tests/` or panel sources) plus the three `ha-controller-0.1.0.*` files. + +- [ ] **Step 3: Write the user docs.** + - **`docs/getting-started.md`:** + 1. Hardware and enclosure: link `../3D_models/`. + 2. Flash from `https://pyxel-dev.github.io/HA-controller/` with Chrome or Edge. + 3. Wi-Fi via Improv or the `HA Controller` access point and captive portal. + 4. Adopt the discovered ESPHome device in Home Assistant. + 5. In HACS, add the custom repository `https://github.com/pyxel-dev/HA-controller` (type Integration), install the **same version** as shown on the installer page, and restart. + 6. Settings › Devices & services › Add integration › HA Controller, then pick the screen. + 7. Open the HA Controller panel. + + Troubleshooting: + - **The screen stays on "Waiting for Home Assistant":** check that the ESPHome device and the HA Controller entry exist. If the hello events never show up under Developer tools › Events, enable "Allow the device to perform Home Assistant actions" in the ESPHome device options. + - **"Firmware update required":** see `updates.md`. + - **`docs/updates.md`:** + - The one-version rule. + - Integration updates come through HACS. To install them automatically, create an automation that calls `update.install` on the HACS update entity. + - Firmware follows the integration automatically (the `auto_update` option, default on), or by hand from the "HA Controller firmware" update entity. + - Rolling back the integration makes the firmware follow. + - A screen without internet access must be re-flashed over USB from the installer. + - **`docs/releasing.md`:** + - One-time setup: Settings › Pages › Source "GitHub Actions"; repository description and topics for HACS. + - Steps: + 1. `python .github/scripts/versioning.py bump X.Y.Z` + 2. commit `chore: release X.Y.Z` + 3. `git tag vX.Y.Z && git push origin main vX.Y.Z` + 4. watch the "Release" workflow + 5. check the Pages page shows X.Y.Z, and that HACS offers X.Y.Z + - Dry runs use `workflow_dispatch`. + - **`README.md`:** an "Install" section with the installer URL and the HACS custom repository, and links to `docs/getting-started.md` and `docs/README.md`. + - **`docs/README.md`:** link the three new docs. + +- [ ] **Step 4: Write `.claude/skills/release/SKILL.md`** and list it in `.claude/CLAUDE.md`. + - Frontmatter `name: release`. + - `description:` "Use when cutting a release or changing the release pipeline: versions, release workflow, GitHub Pages installer, HACS packaging, firmware OTA URLs." + - Body: + - Never edit versions by hand. + - The release steps from `docs/releasing.md`. + - What each job produces. + - OTA URLs must stay stable (`firmware//ha-controller.ota.bin`), because integrations already installed depend on them. + - Check `pytest .github/scripts/tests` after any script change. + +- [ ] **Step 5: Run every suite** + +Run: `pytest custom_components/ha_controller/tests && pytest .github/scripts/tests && ruff check custom_components .github/scripts && python .github/scripts/versioning.py check && npm --prefix custom_components/ha_controller/frontend test` +Expected: PASS. + +- [ ] **Step 6: Commit** + +```bash +git add .github/workflows/release.yml hacs.json README.md docs .claude .claude/CLAUDE.md +git commit -m "ci: release integration, firmware and web installer from tags" +``` + +- [ ] **Step 7: First release (owner).** Follow `docs/releasing.md` for `0.1.0`. Expected: + - the GitHub release has 4 assets; + - `https://pyxel-dev.github.io/HA-controller/` shows "Firmware 0.1.0" and flashes a blank board; + - HACS installs 0.1.0; + - the "HA Controller firmware" entity reports `0.1.0` / `0.1.0`. diff --git a/docs/superpowers/specs/2026-11-16-ha-controller-design.md b/docs/superpowers/specs/2026-11-16-ha-controller-design.md new file mode 100644 index 0000000..1f055e3 --- /dev/null +++ b/docs/superpowers/specs/2026-11-16-ha-controller-design.md @@ -0,0 +1,470 @@ +# HA Controller — Design Spec + +| | | +|---|---| +| Date | 2026-11-16 | +| Status | Approved 2026-11-16, executed with subagent-driven development | +| Repository | https://github.com/pyxel-dev/HA-controller | +| Plans | `docs/superpowers/plans/2026-11-16-ha-controller-1-foundation.md` → `…-5-release.md` (execute in order 1, 2, 3, 4, 5) | + +## 1. Goal + +Turn the Waveshare ESP32-S3-Touch-AMOLED-1.75 into a Home Assistant remote. In a Home Assistant sidebar panel, the user draws a map of **blocks** on a grid. The screen shows one block at a time. To move to a neighbouring block, the user swipes in from the screen edge on that side. A block controls one entity with a knob (light brightness or thermostat temperature), or it shows custom content: text, emoji, entity states, the screen's battery level and a screen brightness control. + +## 2. Requirements + +| ID | Requirement (from the product owner) | +|---|---| +| R1 | Documentation lives in `/docs`. Everything in the repository is written in English. | +| R2 | `/esphome` contains everything needed to build and flash the firmware. Flashing works from an HTML page served by GitHub Pages. | +| R3 | The web page states the firmware version it installs. The firmware version always equals the integration version. | +| R4 | Home Assistant updates the screen firmware automatically. | +| R5 | Claude Code skills and agents guide future development. | +| R6 | The Home Assistant view mirrors on-screen navigation: blocks on a grid, a start block, and "+" placeholders around existing blocks ([reference screenshot](assets/editor-reference.png)). | +| R7 | Navigation: put a finger on a screen edge and slide towards the centre to move to the neighbour on that side. For example, right edge + slide left goes to the right neighbour. Transitions are smooth. | +| R8 | Entity blocks: a light with a brightness knob, a thermostat with a temperature knob. | +| R9 | Custom blocks: text, emoji, textual entity states, and screen info (battery %, screen brightness control). | +| R10 | Font size and background are configurable per block from the integration. | +| R11 | The screen sleeps after a delay set in the integration (default 20 s). A touch wakes it. | + +## 3. Architecture + +```text + Home Assistant Screen (ESPHome firmware) +┌──────────────────────────────────────────┐ ┌──────────────────────────────────────┐ +│ custom integration `ha_controller` │ ESPHome │ external component `ha_controller` │ +│ config entry per screen │ actions │ layout + state parsers (pure C++) │ +│ layout store + validation │ ─────────▶ │ pager: edge swipes, slide animation │ +│ compiler → device payload (+ revision) │ set_layout │ block views: knobs, custom items │ +│ sync engine (hello, states, controls) │ set_states │ message screen │ +│ firmware update entity + auto-update │ install_fw │ │ +│ websocket API + sidebar panel (Lit) │ ◀───────── │ board package: CO5300 display, │ +└──────────────────────────────────────────┘ events │ CST9217 touch, AXP2101 battery, │ + ▲ HACS (release zip) hello / │ screen brightness number │ + │ control └──────────────────────────────────────┘ + GitHub Releases ──────▶ GitHub Pages: web installer + firmware// ▲ OTA download / USB flash +``` + +- The screen is an ordinary ESPHome device, adopted by Home Assistant's ESPHome integration. The custom integration opens no connection of its own. It calls the device's user-defined ESPHome actions, which Home Assistant exposes as services `esphome._` (node name with `-` replaced by `_`). It also listens to the `esphome.ha_controller_*` events fired by the device. +- Home Assistant's ESPHome integration adds `device_id` to every device event. It requires the "Allow the device to perform Home Assistant actions" option for actions, but not for events (`homeassistant/components/esphome/manager.py`). The design uses events only, so that option can stay off. +- The integration is the single source of truth for both the layout and the version. The firmware is a generic renderer. + +### Repository layout + +| Path | Content | +|---|---| +The repository root holds no files except `README.md` (GitHub and HACS landing page), `hacs.json` (HACS reads it only at the root) and `.gitignore`. Everything else lives in a folder: + +| Path | Content | +|---|---| +| `docs/` | User and developer documentation. `docs/protocol/` holds the protocol doc (`README.md`) and its shared fixtures (`fixtures/`), the cross-language contract. `docs/superpowers/` holds this spec and the plans. | +| `custom_components/` | Everything for the Home Assistant integration. HACS allows a single directory here, so development files live inside it, or next to it as plain files. | +| `custom_components/ha_controller/` | The integration (Python). Also holds `emoji.json` (canonical emoji list, also read by the firmware build and the panel), `brand/`, `tests/` (pytest), and `frontend/` (panel source in TypeScript, Lit and Vite, built to `frontend/dist/`, which is git-ignored). | +| `custom_components/pyproject.toml`, `requirements_test.txt`, `__init__.py` | Python test and lint configuration for the integration. The empty `__init__.py` keeps test imports under `custom_components.ha_controller`. | +| `esphome/` | Everything for the firmware: device config, packages, simulator config, external components, C++ host tests, web installer page, `requirements.txt` (ESPHome version) and its venv (`esphome/.venv`, git-ignored) | +| `.github/workflows/` | CI, firmware CI, release | +| `.github/scripts/` | Release and repository-check tooling (versioning, packaging, GitHub Pages site builder, docs and fixture checks), with its own `pyproject.toml`, `requirements.txt` and `tests/` | +| `.claude/` | `CLAUDE.md`, Claude Code skills and agents | +| `3D_models/`, `files/` | Existing enclosure models (unchanged) | + +## 4. Hardware & firmware platform + +| Item | Value | +|---|---| +| Board | Waveshare ESP32-S3-Touch-AMOLED-1.75: ESP32-S3R8 (8 MB octal PSRAM), 16 MB flash, USB-C (native USB) | +| Display | 1.75" round AMOLED, 466×466, CO5300 over QSPI. CS GPIO12, SCLK GPIO38, D0–D3 GPIO4/5/6/7, RESET GPIO39. TE (GPIO13) is not used. | +| Touch | CST9217 (I²C 0x5A). INT GPIO11, RESET GPIO40. Transform: mirror_x + mirror_y. | +| I²C bus | SDA GPIO15, SCL GPIO14, 400 kHz. Shared by AXP2101 0x34, TCA9554 0x20, QMI8658 0x6B, PCF85063 0x51, ES8311 0x18 and ES7210 0x40. | +| PMU | AXP2101 at 0x34: battery %, voltage, charging (registers in §4.1) | +| ESPHome | 2026.10.2, pinned in `esphome/requirements.txt`. `min_version: 2026.10.0`, framework esp-idf. | +| Display driver | `display: platform: mipi_spi`, `model: CO5300`, `bus_mode: quad`. Brightness through `set_brightness(uint8_t)`. | +| Touch driver | External component `cst9217` from https://github.com/shelson/esphome-cst9217, pinned to a commit SHA | +| UI | ESPHome `lvgl:`, which bundles LVGL 9.5. The `ha_controller` external component drives it at runtime through the LVGL C API. | +| JSON | ArduinoJson 7, bundled by ESPHome's `json:` component | +| Native API | Max message size 32 768 bytes. Plaintext (no encryption key in a prebuilt binary). | + +**4.1 AXP2101 registers** (from XPowersLib): +- Enable the ADC: set bit 0 of 0x30. +- Enable battery detection: set bit 0 of 0x68. +- Battery present: bit 3 of 0x00. +- Charging: `(reg 0x01 >> 5) == 0x01`. +- Battery %: register 0xA4 (0–100). +- Battery mV: `((reg 0x34 & 0x1F) << 8) | reg 0x35`. + +The display and touch rails are powered by default, so the firmware does not touch the LDO registers. + +**4.2 Fonts** compiled into the firmware (sizes in px): + +| Size key | Text font (Inter 600, glyphset `GF_Latin_Core`) | Value font (Inter 600, glyphs `" 0123456789.,-+%°CFOfn—"`) | Emoji font (Noto Emoji, glyphs from `emoji.json`) | +|---|---|---|---| +| `s` | 20 | 40 | 32 | +| `m` | 28 | 56 | 48 | +| `l` | 40 | 72 | 64 | +| `xl` | 56 | 96 | 88 | + +A glyph missing from a font is not drawn. v1 targets Latin scripts. + +## 5. On-screen UX + +**5.1 Grid.** Blocks sit on integer cells `(x, y)`. `x` grows to the right and `y` grows **downwards**, exactly as drawn in the panel. +- The screen shows the start block after a layout is applied and after a reboot. +- When a new layout arrives, the screen stays on the current block if a block with the same id still exists. Otherwise it goes to the start block. + +**5.2 Edge swipe.** The touch point is classified on the round display, with `size = 466` and centre `c = (size/2, size/2)`: +- `r = distance(point, c)`. If `r < size/2 − 36`, there is no edge and the touch goes to the widgets. +- Otherwise the dominant axis of `(dx, dy) = point − c` picks the edge. If `|dx| ≥ |dy|`, it is RIGHT when `dx ≥ 0` and LEFT otherwise. If not, it is BOTTOM when `dy > 0` and TOP otherwise. +- Edge → target cell: RIGHT `(x+1, y)`, LEFT `(x−1, y)`, TOP `(x, y−1)`, BOTTOM `(x, y+1)`. +- Progress is the inward finger travel along the edge's axis, clamped to `[0, size]`: + - RIGHT: `start_x − x` + - LEFT: `x − start_x` + - TOP: `y − start_y` + - BOTTOM: `start_y − y` + + Outward and perpendicular motion is ignored. +- With a target, the current page and the target page follow the finger (offset = progress). Without a target, the current page rubber-bands: offset = `min(progress × 0.3, 48)`. +- On release, the navigation commits if a target exists and either `progress ≥ 0.25 × size`, or velocity ≥ 0.6 px/ms with `progress ≥ 24`. Velocity is measured over the last 100 ms. Otherwise both pages slide back. +- Edge touches are captured by a transparent full-screen object on LVGL's top layer. Its hit test only accepts points in the edge ring, so every other touch reaches the page widgets. + +**5.3 Transition.** +- After release, the pages animate to their final position with an ease-out curve. The duration is `clamp(220 × remaining_px / size, 80, 220)` ms. +- Only the current page and the target page are visible; every other page is hidden. + +**5.4 Edge hints.** A short arc (20°, 6 px, white at 60 % opacity) marks each edge of the current block that has a neighbour. + +**5.5 Common page rendering.** +- Each page is a full-screen object filled with the block background. +- Text is black (`#000000`) if the background's WCAG relative luminance is `> 0.30`, otherwise white (`#FFFFFF`). +- Interactive controls stay inside the circle of radius `233 − 36 − 12 = 185` px, so they never overlap the edge ring. + +**5.6 Light block.** The name sits at the top, in the text font of the block size. +- **Dimmable light:** a 270° arc knob (diameter 370 px, width 28 px, gap at the bottom) with range 0–100. + - The centre shows `NN%` or `Off` in the value font. + - Tapping the centre toggles the light. + - Releasing the knob sends the new brightness; 0 turns the light off. +- **On/off-only light:** a 220 px round toggle button in the centre, showing `On`/`Off`. +- **Unavailable entity:** the centre shows `—` with a small `Unavailable` label below, and the controls are disabled. + +**5.7 Climate block.** +- The name sits at the top, with an arc knob over `[min, max]` in steps of `step`. +- The centre shows the target, e.g. `21.5°`: one decimal when `step < 1`, none otherwise. +- A small label below shows `Now ` and the action, e.g. `Heating`. +- Releasing the knob sends the new target. +- If the entity is unavailable or has no single target temperature, the centre shows `—` and the knob is disabled. + +**5.8 Custom block.** Items are stacked vertically and centred with an 8 px gap. Each item has its own font size, defaulting to the block's. +- `text`: a label. +- `emoji`: a label in the emoji font. +- `entity`: a label showing the state text pushed by Home Assistant. +- `battery`: a row `🔋 87 %` (`⚡` while charging), fed by the local battery sensor. +- `brightness`: a row with `☀` and a 220 px slider (5–100 %). It drives the local screen brightness number, applied at most every 100 ms while dragging and always on release. + +A custom block with no items shows its name centred. + +**5.9 Messages.** A full-screen message (title in `m`, detail in `s`) replaces the pages when: + +| Condition | Title | Detail | +|---|---|---| +| No layout received since boot | `Waiting for Home Assistant` | ` · v` | +| Layout protocol not supported | `Firmware update required` | `Open Home Assistant to update` | +| Layout invalid | `Invalid layout` | parse error code | +| Layout has no blocks | `No blocks yet` | `Add blocks in Home Assistant › HA Controller` | +| OTA running | `Updating firmware…` | `Do not unplug the screen` | +| OTA failed (shown 5 s) | `Update failed` | `Check the screen's internet access` | + +**5.10 Interaction hold.** After a local interaction with a block (knob or toggle), incoming state updates for that block are held for 1500 ms; then the latest one is applied. This stops the knob from jumping back while Home Assistant catches up. + +**5.11 Sleep.** +- **Delay:** a per-screen setting (`sleep` in the payload). `0` means never; otherwise 5–3600 s. The default is 20 s, which also applies before the first layout arrives. +- **Going to sleep:** when LVGL has seen no touch activity for the delay, the display brightness goes to 0 and LVGL rendering is paused. Wi-Fi and the Home Assistant connection stay up. Incoming layouts and states are applied without waking the screen. +- **Waking:** releasing a touch wakes the screen. The waking touch never reaches a widget. Brightness returns to the `Screen brightness` value and the inactivity timer restarts. +- **Exceptions:** + - Firmware-update messages (§5.9) wake the screen. + - While the screen sleeps, a `Screen brightness` change is stored and applied on wake. +- **No deep sleep:** it would drop the Home Assistant connection. + +## 6. Layout model (integration and panel) + +The layout is stored per screen under the Home Assistant storage key `ha_controller.layout.` and exchanged with the panel over websocket. The reference layout `docs/protocol/fixtures/layouts/valid/reference.json` mirrors the screenshot: + +```json +{ "version": 1, "start": "b1", "settings": { "sleep_timeout": 20 }, "blocks": [ + { "id": "b1", "x": 0, "y": 0, "name": "Kitchen", "background": "#5B9E4D", "font_size": "m", + "type": "entity", "entity_id": "light.kitchen" }, + { "id": "b2", "x": 0, "y": -1, "name": "Lights", "background": "#C94F3D", "font_size": "m", + "type": "entity", "entity_id": "light.living_room" }, + { "id": "b3", "x": -1, "y": 0, "name": "Hello World", "background": "#4F86DD", "font_size": "l", + "type": "custom", "items": [ + { "id": "i1", "kind": "text", "text": "Hello World", "font_size": null }, + { "id": "i2", "kind": "emoji", "emoji": "👋", "font_size": "xl" }, + { "id": "i3", "kind": "entity", "entity_id": "sensor.outdoor_temperature", "attribute": null, "font_size": "s" }, + { "id": "i4", "kind": "battery", "font_size": "s" }, + { "id": "i5", "kind": "brightness", "font_size": null } ] }, + { "id": "b4", "x": -1, "y": 1, "name": "Bedroom", "background": "#7B2FA0", "font_size": "m", + "type": "entity", "entity_id": "climate.bedroom" } ] } +``` + +Unknown keys are ignored, so the panel can keep `entity_id` and `items` when the user switches a block's type. + +Validation returns a list of `{code, ref}`, where `ref` is the offending block or item id, or `null`. An empty list means the layout is valid. It runs in three phases: +1. **Structure.** It stops at the first error. +2. **Per-field checks.** All errors are collected. +3. **Connectivity.** Only runs if phase 2 found nothing. + +| Code | Rule | +|---|---| +| `invalid_structure` | `version` must be `1`, `settings` an object, `blocks` a list, and blocks and items objects with the expected JSON types | +| `too_many_blocks` | At most 32 blocks | +| `invalid_sleep_timeout` | `settings.sleep_timeout` is an integer (not a boolean): `0` (never) or 5–3600 seconds | +| `invalid_id` | Ids match `^[a-z][a-z0-9]{0,7}$` | +| `duplicate_id` | Ids are unique across blocks **and** items | +| `coordinate_out_of_range` | `-32 ≤ x, y ≤ 32` (integers) | +| `duplicate_position` | One block per cell (ref = the later block) | +| `invalid_start` | `start` is `null` if and only if there are no blocks; otherwise it is the id of an existing block | +| `disconnected` | Every block is reachable from `start` through 4-neighbour cells (one error per unreachable block, in layout order) | +| `invalid_name` | 1–32 characters after trimming | +| `invalid_background` | `^#[0-9A-Fa-f]{6}$` | +| `invalid_font_size` | Block: `s`/`m`/`l`/`xl`. Item: the same, or `null` (inherit). | +| `invalid_type` | `entity` or `custom` | +| `invalid_entity` | Entity block: an `entity_id` of domain `light` or `climate`. Entity item: an id matching `^[a-z0-9_]+\.[a-z0-9_]+$`, and `attribute` either `null` or 1–64 characters. | +| `too_many_items` | At most 6 items per custom block | +| `invalid_item` | `kind` is one of `text`, `emoji`, `entity`, `battery`, `brightness` | +| `invalid_text` | Text item: 1–64 characters | +| `unsupported_emoji` | Emoji item: after removing U+FE0F, the value is an entry of `emoji.json` | +| `payload_too_large` | The compiled payload (§7.3) is larger than 24 576 UTF-8 bytes. Checked by the integration only. | + +Lengths count Unicode code points (Python `len`, JavaScript `Array.from(text).length`), and names are trimmed of Unicode whitespace (`str.strip()`, `String.prototype.trim()`). The fixtures `astral-text` (valid) and `invalid_name-astral` pin this. + +Entities that do not exist (yet) are valid; the screen shows them as unavailable. + +## 7. Device protocol v1 (normative) + +`PROTOCOL_VERSION = 1`. `docs/protocol/README.md` is the living copy of this section. `docs/protocol/fixtures/` pins it with examples, used by the tests of all three implementations. + +**7.1 Actions (Home Assistant → screen).** Services `esphome._`: + +| Action | Variables | Effect | +|---|---|---| +| `set_layout` | `layout: string` (payload JSON, §7.3) | Parse it. On success, rebuild the pages and adopt `rev`. Then fire a hello with reason `applied`; this also happens after a failure, with the revision unchanged. | +| `set_states` | `states: string` (JSON array, §7.4) | Apply each update to the block or item with that id. Unknown ids are ignored. | +| `install_firmware` | `url: string`, `md5_url: string` | Show `Updating firmware…`, render it immediately, then run `ota.http_request.flash`. On failure, show `Update failed` for 5 s. | + +**7.2 Events (screen → Home Assistant).** Data values are strings, and Home Assistant adds `device_id`. + +| Event | Data | When | +|---|---|---| +| `esphome.ha_controller_hello` | `node` (ESPHome node name), `version` (firmware version), `protocol` (`"1"`), `revision` (applied `rev` or `none`), `reason` (`connected` / `heartbeat` / `applied`) | 5 s after an API client connects, every 60 s while connected, and after each `set_layout` | +| `esphome.ha_controller_control` | `block` (block id), `item` (item id or empty), `op` (`toggle` / `set`), `value` (decimal, `%.2f`) | Centre tap on a light (`toggle`), knob release (`set`) | + +**7.3 Layout payload.** The integration compiles it from the stored layout: +- **Top level:** `v` (1), `rev`, `start` (id or `null`), `sleep` (integer seconds, `0` = never), `blocks`. +- **Block:** `id`, `x`, `y`, `name`, `bg` (6 uppercase hex digits, no `#`), `font`, `widget`. + - `widget` is `light` or `climate` (taken from the entity domain), or `custom`. + - Custom blocks also carry `items` (possibly empty). Entity blocks carry no `items`. +- **Item:** `id`, `kind`, `font` (the item's size, or the block's when the item's is `null`). + - `text` items carry `text` (the text). + - `emoji` items carry `text` (the emoji without U+FE0F). + - Other kinds carry no `text`. +- No entity ids are sent to the screen. +- `rev` is the first 8 hex chars of SHA-256 over the UTF-8 bytes of `json.dumps(payload_without_rev, sort_keys=True, separators=(",", ":"), ensure_ascii=False)`. + - Golden values: empty payload (`sleep` 20) → `c4aad3fa`; `payloads/valid/reference.json` → `90538742`; `payloads/valid/emoji-variation.json` → `5387d4ea`. +- **Transport encoding:** compact JSON (`separators=(",", ":")`, `ensure_ascii=False`), at most 24 576 bytes. + +Device parse errors: +- `bad_json`: not JSON, or not an object. +- `unsupported_version`: `v != 1`. +- `invalid_payload`: a missing or mistyped field, an unknown `widget`, `kind` or `font`, or a `sleep` outside 0–3600. + +**7.4 State updates.** A JSON array. Each element has `id` (block or item id) and `available` (bool, default `true`): + +| Target | Fields | +|---|---| +| Light block | `on` (bool), `brightness` (0–100 integer; `null` for on/off-only lights; `0` when a dimmable light is off) | +| Climate block | `target` (number or `null`), `min`, `max`, `step` (numbers), `unit` (`°C`/`°F`), `current` (display string), `action` (display string, e.g. `Heating`) | +| Entity item | `text` (display string) | + +An unavailable or missing entity sends `{"id": …, "available": false}`. Entity items send `{"id": …, "text": "—"}` instead. Updates are sent in layout order, in chunks of at most 8 192 bytes. + +**7.5 Handshake and resync** (integration side): +- **On a hello from the screen's `device_id`:** record the node, version, protocol, revision and time. Then: + - If `protocol ≠ 1`, push nothing (auto-update may run, §11). + - Else, if `revision ≠` the current revision, push the layout and then all states. Push immediately when `reason = connected`. Otherwise push at most once per 300 s for the same revision. + - Else, if `reason = connected`, or this is the first hello since the integration (re)started, push all states. After an integration reload the ESPHome connection stays up, so no `connected` hello arrives. +- **Entity state changes:** coalesced for 200 ms, then pushed for the changed entities. This only happens while the screen is online (a hello within the last 150 s) and on protocol 1. +- **Saving a layout:** pushes it immediately if the screen is online. + +**7.6 Control mapping** (integration side). The entity always comes from the layout, never from the event. + +| Block | op | Service call | +|---|---|---| +| Light | `toggle` | `light.toggle` `{entity_id}` | +| Light | `set`, value ≤ 0 | `light.turn_off` `{entity_id}` | +| Light | `set`, value > 0 | `light.turn_on` `{entity_id, brightness_pct: round(clamp(value, 1, 100))}` | +| Climate | `set` | `climate.set_temperature` `{entity_id, temperature: clamp(value, min_temp, max_temp)}` (bounds from the current state, defaults 7/35) | + +Anything else is ignored: an unknown block, a custom block, an unparsable value. Service errors are logged, never raised. + +**7.7 State builders** (integration side): +- **Light:** + - Unavailable if the entity is missing, `unavailable` or `unknown`. + - Dimmable if `supported_color_modes` contains a mode other than `onoff`. + - Brightness: `round((attribute brightness or 255) × 100 / 255)` when on, `0` when off, `null` when not dimmable. +- **Climate:** + - `unit` is Home Assistant's temperature unit. + - `step` is `target_temp_step`, or else `0.5` for °C and `1` for °F. + - `min`/`max` come from `min_temp`/`max_temp` (defaults 7/35). + - `current` is `" "`, or `—`. + - `action` is `hvac_action`, or else the state, with `_` replaced by a space and the first letter capitalised. +- **Entity item:** + - `—` if the entity is missing, `unavailable` or `unknown`, or if the attribute is missing. + - A numeric value is rounded to the entity registry's `sensor.display_precision`, or else `suggested_display_precision`, or else left unchanged. + - The result is `" "` when a unit exists, truncated to 64 characters. + +## 8. Home Assistant integration + +- **Config flow:** one entry per screen. + - Step `user` shows a device selector filtered to `integration: esphome, manufacturer: pyxel-dev, model: ha-controller`. Home Assistant derives the manufacturer and model from the firmware's `project.name: pyxel-dev.ha-controller`. + - The manufacturer and model are checked server-side (error `not_ha_controller`). + - `unique_id` = device id. Title = device name. Data: `{"device_id": …}`. +- **Options flow** (plan 5): `auto_update` (bool, default `true`). +- **Runtime:** `entry.runtime_data` is a `ScreenController`. It owns the layout store, the compiled payload and revision, the device status, the event listeners (filtered by `device_id`), entity tracking, and firmware installs. +- **Websocket API** (admin only): + - `ha_controller/screens` → `{"screens": [{entry_id, title, device_id, online, firmware_version, integration_version, protocol_ok, revision, device_revision}]}` + - `ha_controller/layout/get` `{entry_id}` → `{"layout": …}` + - `ha_controller/layout/save` `{entry_id, layout}` → `{"revision": …, "pushed": bool}`. Errors: `not_found`, and `invalid_layout` with message `code@ref, …`. +- **Panel:** + - Sidebar entry "HA Controller", icon `mdi:remote`, URL `/ha-controller`, admins only. + - The module is served from `/ha_controller_static/ha-controller-panel.js?v=`. + - Registered with the first loaded entry and removed with the last. +- **Manifest:** `dependencies: ["frontend", "http", "panel_custom", "websocket_api"]`, `after_dependencies: ["esphome"]`, `integration_type: device`, `iot_class: local_push`. Brand images live in `custom_components/ha_controller/brand/`. +- **Minimum Home Assistant:** 2026.10.0 (Python 3.14). + +## 9. Panel UX + +- **Header:** + - A screen selector, when there are several screens. + - A status line: `Online · firmware 0.1.0 · in sync`, `Offline`, or `Firmware 0.0.9 — update available`. + - `Revert` and `Save` buttons, disabled when nothing changed or the layout has errors. +- **Map** (see the [reference screenshot](assets/editor-reference.png)): + - A CSS grid of 96 px square cells with 12 px gaps and a 16 px radius, covering blocks and placeholders. Columns follow `x` ascending, rows follow `y` ascending. + - Blocks are filled with their background and show their name in the contrast text colour. + - The start block has a 3 px outline and a `start` badge. + - Placeholders (2 px dashed border, `+`) appear on every empty 4-neighbour of a block. If there is no block, there is only one, at `(0, 0)`. There are none at 32 blocks, and none for cells out of range. + - The selected block has a ring in the theme's primary colour. +- **Adding a block:** clicking a placeholder adds a block there and selects it. The first block becomes the start block. Defaults: + - id `b`, name `Block `; + - background from the palette `#C94F3D #4F86DD #5B9E4D #7B2FA0 #E08A2E #2E9E8F #D2477A #5C6BC0`, picked by block count; + - font `m`, type `custom`, no items. +- **Editor** for the selected block: + - Name, background (colour input + palette swatches), font size (S/M/L/XL), type (Entity/Custom). + - An entity picker limited to `light.*`/`climate.*`. + - For custom blocks, an items list: add Text, Emoji, Entity state, Battery or Screen brightness; edit, move up/down, remove; per-item font size with "Inherit". The emoji picker shows only `emoji.json`. + - `Set as start block`. + - `Delete block`, disabled with the reason when it is the start block of a multi-block layout or when deleting it would disconnect other blocks. + - A 220 px round preview showing the background, the contrast text and the content. +- **Validation** runs locally with the same rules and codes as the integration. Errors are listed with human messages and highlighted on the map. +- **Screen settings:** a "Screen" section under the map with a "Sleep after (seconds)" input. Default 20; `0` keeps the screen on. Validated with `invalid_sleep_timeout`. +- **Refresh and save:** the screen list refreshes every 10 s. Saving reports `Saved — sent to the screen.` or `Saved — the screen is offline and will update when it reconnects.` + +## 10. Versioning & distribution + +- **One version:** a single SemVer version `X.Y.Z` for the whole repository, stored in three places: + - `custom_components/ha_controller/manifest.json` (`version`) + - `esphome/version.yaml` (`substitutions.project_version`) + - `custom_components/ha_controller/frontend/package.json` (`version`) + + `.github/scripts/versioning.py check [--tag vX.Y.Z]` fails CI on any mismatch, and `.github/scripts/versioning.py bump X.Y.Z` rewrites all three. The initial version is `0.1.0`. +- **Release:** pushing tag `vX.Y.Z` cuts a release. The release workflow: + 1. verifies the versions; + 2. builds the panel; + 3. packages `ha_controller.zip`: the contents of `custom_components/ha_controller/` without `tests/` and the panel sources, plus the built panel `frontend/dist/ha-controller-panel.js`; + 4. compiles the firmware; + 5. publishes a GitHub release with `ha_controller.zip`, `ha-controller-X.Y.Z.factory.bin`, `ha-controller-X.Y.Z.ota.bin` and `ha-controller-X.Y.Z.ota.bin.md5`. +- **GitHub Pages:** the release workflow then rebuilds `https://pyxel-dev.github.io/HA-controller/` from the release assets: + - `index.html` (web installer); + - `firmware/manifest.json` (ESP Web Tools manifest for the latest version); + - `firmware/ha-controller.factory.bin` (latest); + - `firmware//ha-controller.ota.bin` + `.md5` for every release. +- **Web installer:** an ESP Web Tools 10.5.2 install button. The page prints "Firmware X.Y.Z" (substituted at build time) and links to the release notes. It explains: + - USB-C with Chrome or Edge; + - Wi-Fi setup, through Improv serial or the `HA Controller` access point + captive portal; + - adding the screen in Home Assistant; + - installing the integration with the **same version** through HACS. +- **HACS:** a custom repository. `hacs.json` sets `zip_release: true`, `filename: ha_controller.zip` and `homeassistant: 2026.10.0`. + +## 11. Firmware updates + +- **Update entity:** the integration creates one `update` entity per screen ("HA Controller firmware"), attached to the screen's device. + - `installed_version` is the version from the last hello. + - `latest_version` is the integration version. + - `release_url` is the release page. + - `version_is_newer` returns `latest != installed`. A firmware newer than the integration (after an integration rollback) therefore also shows as an update. +- **Install:** calls `install_firmware` with `https://pyxel-dev.github.io/HA-controller/firmware//ha-controller.ota.bin` and its `.md5`, and sets `in_progress`. It then waits up to 300 s for a hello carrying ``, and raises an error otherwise. +- **Auto-update** (option `auto_update`, default on): the integration installs automatically when all of these hold: + - a hello reports a version different from the integration version; + - the integration version is a release (`^\d+\.\d+\.\d+$`); + - no install is running. + + It makes at most one automatic attempt per screen and version every 3600 s. +- **Network requirement:** OTA requires internet access from the screen to GitHub Pages. Without it, re-flash over USB from the web installer. +- **No ESPHome `update:` entity:** the firmware does not define one of its own. + +## 12. Testing strategy + +- **Shared fixtures** in `docs/protocol/fixtures/`, read by the Python, TypeScript and C++ tests: + - `layouts/valid` + - `layouts/invalid` (expected code + ref) + - `payloads/valid` (stored layout + golden payload) + - `payloads/invalid` (raw text + expected device parse error) + - `states` (Home Assistant states + expected updates) + - `controls` (event + expected service call) + - `colors.json` (background → text colour) +- **Integration:** pytest + `pytest-homeassistant-custom-component`, ruff. hassfest and HACS validation run in CI. +- **Panel:** vitest (model, and components with happy-dom), `tsc --noEmit`, production build. +- **Firmware:** + - Host C++ tests (CMake, doctest, ArduinoJson 7) for the pure modules: layout and state parsing, knob scale, gestures, colours, AXP2101 decoding. + - `esphome compile` of the device and simulator configs. + - A manual hardware checklist in `docs/development.md`. +- **Simulator:** `esphome/simulator.yaml` runs the same UI on a desktop (ESPHome `host` platform + SDL, 466×466) and accepts Home Assistant API connections. + +## 13. Developer guidance (Claude Code) + +- `.claude/CLAUDE.md`: purpose; rules (English only, one version, protocol changes go through the protocol skill, TDD); repository map; commands. +- Skills (`.claude/skills/`): `protocol-change`, `add-widget`, `firmware-dev`, `release`. +- Agents (`.claude/agents/`): `protocol-guardian`, `ha-integration-reviewer`, `firmware-reviewer`. + +## 14. Out of scope for v1 + +- PWR button handling. +- Deep sleep. +- IMU, RTC, audio and SD card features. +- Colour emoji. +- Non-Latin scripts. +- Entity widgets other than light and climate, such as switch, cover, fan or media player. Add them with the `add-widget` skill. +- Drag-and-drop to move blocks. +- Several layouts per screen. +- Panel translations. +- OTA without internet access. +- Automatic discovery of new screens. +- API encryption in the prebuilt firmware. + +## 15. Constants + +| Name | Value | +|---|---| +| Screen size | 466 px | +| Edge ring width | 36 px | +| Commit distance / flick | 0.25 × size / 0.6 px/ms with ≥ 24 px | +| Rubber band | × 0.3, max 48 px | +| Settle animation | clamp(220 × remaining / size, 80, 220) ms, ease-out | +| Interaction hold | 1500 ms | +| Max blocks / items / name / text | 32 / 6 / 32 / 64 | +| Coordinate range | −32…32 | +| Max payload / state chunk | 24 576 / 8 192 bytes | +| Hello delay / heartbeat | 5 s / 60 s | +| Online timeout | 150 s | +| Push retry (same revision) | 300 s | +| State coalescing | 200 ms | +| Install timeout | 300 s | +| Auto-update retry | 3600 s | +| Panel status refresh | 10 s | +| Sleep delay | default 20 s; `0` = never; otherwise 5–3600 s | diff --git a/docs/superpowers/specs/assets/editor-reference.png b/docs/superpowers/specs/assets/editor-reference.png new file mode 100644 index 0000000..c524cf1 Binary files /dev/null and b/docs/superpowers/specs/assets/editor-reference.png differ diff --git a/docs/updates.md b/docs/updates.md new file mode 100644 index 0000000..12bff50 --- /dev/null +++ b/docs/updates.md @@ -0,0 +1,19 @@ +# Updates + +## One version + +The whole repository has a single version. The integration, the panel and the firmware always share it, and the integration expects the firmware of the same version on the screen. + +## Integration + +Integration updates come through HACS. To install them automatically, create an automation that calls `update.install` on the HACS update entity of HA Controller. + +## Firmware + +The firmware follows the integration automatically (the `auto_update` option, on by default). You can also update it by hand from the "HA Controller firmware" update entity. + +Rolling back the integration to an older version makes the firmware follow it. + +## Screen without internet access + +The firmware is downloaded from GitHub. A screen without internet access must be re-flashed over USB from the [installer](https://pyxel-dev.github.io/HA-controller/). diff --git a/esphome/components/axp2101_battery/__init__.py b/esphome/components/axp2101_battery/__init__.py new file mode 100644 index 0000000..9eb9373 --- /dev/null +++ b/esphome/components/axp2101_battery/__init__.py @@ -0,0 +1,66 @@ +import esphome.codegen as cg +from esphome.components import binary_sensor, i2c, sensor +import esphome.config_validation as cv +from esphome.const import ( + CONF_ID, + DEVICE_CLASS_BATTERY, + DEVICE_CLASS_BATTERY_CHARGING, + DEVICE_CLASS_VOLTAGE, + STATE_CLASS_MEASUREMENT, + UNIT_PERCENT, + UNIT_VOLT, +) + +CODEOWNERS = ["@pyxel-dev"] +DEPENDENCIES = ["i2c"] +AUTO_LOAD = ["sensor", "binary_sensor"] + +CONF_BATTERY_LEVEL = "battery_level" +CONF_BATTERY_VOLTAGE = "battery_voltage" +CONF_CHARGING = "charging" + +axp2101_battery_ns = cg.esphome_ns.namespace("axp2101_battery") +AXP2101Battery = axp2101_battery_ns.class_( + "AXP2101Battery", cg.PollingComponent, i2c.I2CDevice +) + +CONFIG_SCHEMA = ( + cv.Schema( + { + cv.GenerateID(): cv.declare_id(AXP2101Battery), + cv.Optional(CONF_BATTERY_LEVEL): sensor.sensor_schema( + unit_of_measurement=UNIT_PERCENT, + accuracy_decimals=0, + device_class=DEVICE_CLASS_BATTERY, + state_class=STATE_CLASS_MEASUREMENT, + ), + cv.Optional(CONF_BATTERY_VOLTAGE): sensor.sensor_schema( + unit_of_measurement=UNIT_VOLT, + accuracy_decimals=2, + device_class=DEVICE_CLASS_VOLTAGE, + state_class=STATE_CLASS_MEASUREMENT, + ), + cv.Optional(CONF_CHARGING): binary_sensor.binary_sensor_schema( + device_class=DEVICE_CLASS_BATTERY_CHARGING, + ), + } + ) + .extend(cv.polling_component_schema("30s")) + .extend(i2c.i2c_device_schema(0x34)) +) + + +async def to_code(config): + var = cg.new_Pvariable(config[CONF_ID]) + await cg.register_component(var, config) + await i2c.register_i2c_device(var, config) + + if CONF_BATTERY_LEVEL in config: + sens = await sensor.new_sensor(config[CONF_BATTERY_LEVEL]) + cg.add(var.set_battery_level(sens)) + if CONF_BATTERY_VOLTAGE in config: + sens = await sensor.new_sensor(config[CONF_BATTERY_VOLTAGE]) + cg.add(var.set_battery_voltage(sens)) + if CONF_CHARGING in config: + sens = await binary_sensor.new_binary_sensor(config[CONF_CHARGING]) + cg.add(var.set_charging(sens)) diff --git a/esphome/components/axp2101_battery/axp2101_battery.cpp b/esphome/components/axp2101_battery/axp2101_battery.cpp new file mode 100644 index 0000000..0d3caf3 --- /dev/null +++ b/esphome/components/axp2101_battery/axp2101_battery.cpp @@ -0,0 +1,73 @@ +#include "axp2101_battery.h" + +#include + +#include "axp2101_regs.h" +#include "esphome/core/log.h" + +namespace esphome { +namespace axp2101_battery { + +static const char *const TAG = "axp2101_battery"; + +void AXP2101Battery::setup() { + // Enable the battery voltage ADC channel and battery detection (bit 0 of each register). + for (uint8_t reg : {REG_ADC_CTRL, REG_BAT_DET}) { + uint8_t value = 0; + if (this->read_register(reg, &value, 1) != i2c::ERROR_OK) { + ESP_LOGE(TAG, "Failed to read register 0x%02X", reg); + this->mark_failed(); + return; + } + value |= 0x01; + if (this->write_register(reg, &value, 1) != i2c::ERROR_OK) { + ESP_LOGE(TAG, "Failed to write register 0x%02X", reg); + this->mark_failed(); + return; + } + } +} + +void AXP2101Battery::update() { + uint8_t status1 = 0, status2 = 0; + if (this->read_register(REG_STATUS1, &status1, 1) != i2c::ERROR_OK || + this->read_register(REG_STATUS2, &status2, 1) != i2c::ERROR_OK) { + ESP_LOGW(TAG, "Failed to read status registers"); + this->status_set_warning(); + return; + } + this->status_clear_warning(); + + const bool present = battery_present(status1); + if (this->charging_ != nullptr) + this->charging_->publish_state(is_charging(status2)); + + float level = NAN; + float volts = NAN; + if (present) { + uint8_t pct = 0, hi = 0, lo = 0; + if (this->read_register(REG_BAT_PERCENT, &pct, 1) == i2c::ERROR_OK) + level = battery_percent(pct); + if (this->read_register(REG_VBAT_H, &hi, 1) == i2c::ERROR_OK && + this->read_register(REG_VBAT_L, &lo, 1) == i2c::ERROR_OK) + volts = battery_millivolts(hi, lo) / 1000.0f; + } + if (this->battery_level_ != nullptr) + this->battery_level_->publish_state(level); + if (this->battery_voltage_ != nullptr) + this->battery_voltage_->publish_state(volts); +} + +void AXP2101Battery::dump_config() { + ESP_LOGCONFIG(TAG, "AXP2101 battery:"); + LOG_I2C_DEVICE(this); + LOG_UPDATE_INTERVAL(this); + LOG_SENSOR(" ", "Battery level", this->battery_level_); + LOG_SENSOR(" ", "Battery voltage", this->battery_voltage_); + LOG_BINARY_SENSOR(" ", "Charging", this->charging_); + if (this->is_failed()) + ESP_LOGE(TAG, "Communication with the AXP2101 failed"); +} + +} // namespace axp2101_battery +} // namespace esphome diff --git a/esphome/components/axp2101_battery/axp2101_battery.h b/esphome/components/axp2101_battery/axp2101_battery.h new file mode 100644 index 0000000..eb2fe65 --- /dev/null +++ b/esphome/components/axp2101_battery/axp2101_battery.h @@ -0,0 +1,29 @@ +#pragma once + +#include "esphome/components/binary_sensor/binary_sensor.h" +#include "esphome/components/i2c/i2c.h" +#include "esphome/components/sensor/sensor.h" +#include "esphome/core/component.h" + +namespace esphome { +namespace axp2101_battery { + +class AXP2101Battery : public PollingComponent, public i2c::I2CDevice { + public: + void setup() override; + void update() override; + void dump_config() override; + float get_setup_priority() const override { return setup_priority::DATA; } + + void set_battery_level(sensor::Sensor *s) { this->battery_level_ = s; } + void set_battery_voltage(sensor::Sensor *s) { this->battery_voltage_ = s; } + void set_charging(binary_sensor::BinarySensor *s) { this->charging_ = s; } + + protected: + sensor::Sensor *battery_level_{nullptr}; + sensor::Sensor *battery_voltage_{nullptr}; + binary_sensor::BinarySensor *charging_{nullptr}; +}; + +} // namespace axp2101_battery +} // namespace esphome diff --git a/esphome/components/axp2101_battery/axp2101_regs.h b/esphome/components/axp2101_battery/axp2101_regs.h new file mode 100644 index 0000000..d6a83df --- /dev/null +++ b/esphome/components/axp2101_battery/axp2101_regs.h @@ -0,0 +1,27 @@ +#pragma once + +#include + +namespace esphome { +namespace axp2101_battery { + +constexpr uint8_t REG_STATUS1 = 0x00; +constexpr uint8_t REG_STATUS2 = 0x01; +constexpr uint8_t REG_ADC_CTRL = 0x30; +constexpr uint8_t REG_VBAT_H = 0x34; +constexpr uint8_t REG_VBAT_L = 0x35; +constexpr uint8_t REG_BAT_DET = 0x68; +constexpr uint8_t REG_BAT_PERCENT = 0xA4; + +inline bool battery_present(uint8_t status1) { return (status1 & 0x08) != 0; } + +inline bool is_charging(uint8_t status2) { return (status2 >> 5) == 0x01; } + +inline uint16_t battery_millivolts(uint8_t hi, uint8_t lo) { + return static_cast(((hi & 0x1F) << 8) | lo); +} + +inline float battery_percent(uint8_t raw) { return raw > 100 ? 100.0f : static_cast(raw); } + +} // namespace axp2101_battery +} // namespace esphome diff --git a/esphome/components/ha_controller/__init__.py b/esphome/components/ha_controller/__init__.py new file mode 100644 index 0000000..eb19050 --- /dev/null +++ b/esphome/components/ha_controller/__init__.py @@ -0,0 +1,108 @@ +from esphome import automation +import esphome.codegen as cg +from esphome.components import binary_sensor, font, number, sensor, touchscreen +from esphome.components.lvgl.defines import add_lv_use +import esphome.config_validation as cv +from esphome.const import CONF_ID, CONF_SIZE, CONF_TRIGGER_ID + +CODEOWNERS = ["@pyxel-dev"] +DEPENDENCIES = ["lvgl"] +AUTO_LOAD = ["json"] + +CONF_EDGE_WIDTH = "edge_width" +CONF_TEXT_FONTS = "text_fonts" +CONF_VALUE_FONTS = "value_fonts" +CONF_EMOJI_FONTS = "emoji_fonts" +CONF_BATTERY_LEVEL = "battery_level" +CONF_BATTERY_CHARGING = "battery_charging" +CONF_SCREEN_BRIGHTNESS = "screen_brightness" +CONF_ON_CONTROL = "on_control" +CONF_TOUCHSCREEN = "touchscreen" +CONF_ON_SLEEP = "on_sleep" +CONF_ON_WAKE = "on_wake" + +ha_controller_ns = cg.esphome_ns.namespace("ha_controller") +HaController = ha_controller_ns.class_("HaController", cg.Component) +ControlTrigger = ha_controller_ns.class_( + "ControlTrigger", + automation.Trigger.template(cg.std_string, cg.std_string, cg.std_string, cg.float_), +) +SleepTrigger = ha_controller_ns.class_("SleepTrigger", automation.Trigger.template()) +WakeTrigger = ha_controller_ns.class_("WakeTrigger", automation.Trigger.template()) +FontRole = ha_controller_ns.enum("FontRole", is_class=True) +FontSize = ha_controller_ns.enum("FontSize", is_class=True) + +SIZES = ("s", "m", "l", "xl") +ROLES = ( + (CONF_TEXT_FONTS, "TEXT"), + (CONF_VALUE_FONTS, "VALUE"), + (CONF_EMOJI_FONTS, "EMOJI"), +) + + +def font_set_schema(): + return cv.Schema({cv.Required(s): cv.use_id(font.Font) for s in SIZES}) + + +CONFIG_SCHEMA = cv.Schema( + { + cv.GenerateID(): cv.declare_id(HaController), + cv.Optional(CONF_SIZE, default=466): cv.int_range(min=100, max=1000), + cv.Optional(CONF_EDGE_WIDTH, default=36): cv.int_range(min=8, max=120), + cv.Required(CONF_TEXT_FONTS): font_set_schema(), + cv.Required(CONF_VALUE_FONTS): font_set_schema(), + cv.Required(CONF_EMOJI_FONTS): font_set_schema(), + cv.Optional(CONF_BATTERY_LEVEL): cv.use_id(sensor.Sensor), + cv.Optional(CONF_BATTERY_CHARGING): cv.use_id(binary_sensor.BinarySensor), + cv.Optional(CONF_SCREEN_BRIGHTNESS): cv.use_id(number.Number), + cv.Required(CONF_TOUCHSCREEN): cv.use_id(touchscreen.Touchscreen), + cv.Optional(CONF_ON_SLEEP): automation.validate_automation( + {cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(SleepTrigger)} + ), + cv.Optional(CONF_ON_WAKE): automation.validate_automation( + {cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(WakeTrigger)} + ), + cv.Optional(CONF_ON_CONTROL): automation.validate_automation( + {cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(ControlTrigger)} + ), + } +).extend(cv.COMPONENT_SCHEMA) + + +async def to_code(config): + var = cg.new_Pvariable(config[CONF_ID]) + await cg.register_component(var, config) + add_lv_use("font") # makes ESPHome fonts expose their lv_font_t + + cg.add(var.set_geometry(config[CONF_SIZE], config[CONF_EDGE_WIDTH])) + for key, role in ROLES: + for size in SIZES: + fnt = await cg.get_variable(config[key][size]) + cg.add(var.set_font(getattr(FontRole, role), getattr(FontSize, size.upper()), fnt)) + + if CONF_BATTERY_LEVEL in config: + cg.add(var.set_battery_sensor(await cg.get_variable(config[CONF_BATTERY_LEVEL]))) + if CONF_BATTERY_CHARGING in config: + cg.add(var.set_charging_sensor(await cg.get_variable(config[CONF_BATTERY_CHARGING]))) + if CONF_SCREEN_BRIGHTNESS in config: + cg.add(var.set_brightness_number(await cg.get_variable(config[CONF_SCREEN_BRIGHTNESS]))) + + cg.add(var.set_touchscreen(await cg.get_variable(config[CONF_TOUCHSCREEN]))) + + for key, trigger_type in ((CONF_ON_SLEEP, SleepTrigger), (CONF_ON_WAKE, WakeTrigger)): + for conf in config.get(key, []): + trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var) + await automation.build_automation(trigger, [], conf) + + for conf in config.get(CONF_ON_CONTROL, []): + trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var) + await automation.build_automation( + trigger, + [ + (cg.std_string, "block"), + (cg.std_string, "item"), + (cg.std_string, "op"), + (cg.float_, "value"), + ], + conf, + ) diff --git a/esphome/components/ha_controller/climate_view.cpp b/esphome/components/ha_controller/climate_view.cpp new file mode 100644 index 0000000..61747fa --- /dev/null +++ b/esphome/components/ha_controller/climate_view.cpp @@ -0,0 +1,82 @@ +#include "views.h" + +#include "format.h" + +namespace esphome { +namespace ha_controller { + +namespace { + +const char *const DASH = "\xE2\x80\x94"; +const char *const DEGREE = "\xC2\xB0"; + +// Arc over [min, max] in steps of `step`. The arc value is the step index, never the temperature. +class ClimateView final : public KnobBlockView { + public: + ClimateView(lv_obj_t *parent, const Block &block, const Theme &theme, ControlSink &sink) + : KnobBlockView(parent, block, theme, sink, false), scale_{7, 35, 0.5f} { + StateUpdate none; + none.id = block.id; + none.available = false; + this->draw_(none); + } + + protected: + void render_(const StateUpdate &u) override { + this->scale_ = KnobScale{u.min, u.max, u.step}; + int steps = this->scale_.steps(); + this->available_ = u.available && u.target.has_value() && steps > 0; + this->set_disabled_(!this->available_); + lv_arc_set_range(this->arc_, 0, steps > 0 ? steps : 1); + if (!this->available_) { + lv_arc_set_value(this->arc_, 0); + lv_label_set_text(this->value_label_, DASH); + if (!u.available) { + lv_label_set_text(this->sub_label_, "Unavailable"); + lv_obj_remove_flag(this->sub_label_, LV_OBJ_FLAG_HIDDEN); + } else { + this->show_sub_(u); + } + return; + } + lv_arc_set_value(this->arc_, this->scale_.index_of(*u.target)); + this->show_target_(this->scale_.value_at(this->scale_.index_of(*u.target))); + this->show_sub_(u); + } + + void on_arc_changed_(int value) override { this->show_target_(this->scale_.value_at(value)); } + void on_arc_released_(int value) override { + this->sink_.on_control(this->id_, "", "set", this->scale_.value_at(value)); + } + + void show_target_(float value) { + std::string text = format_value(value, this->scale_.step) + DEGREE; + lv_label_set_text(this->value_label_, text.c_str()); + } + + // "Now " and the action on a second line. + void show_sub_(const StateUpdate &u) { + std::string text; + if (!u.current.empty()) + text = "Now " + u.current; + if (!u.action.empty()) + text += (text.empty() ? "" : "\n") + u.action; + lv_label_set_text(this->sub_label_, text.c_str()); + if (text.empty()) + lv_obj_add_flag(this->sub_label_, LV_OBJ_FLAG_HIDDEN); + else + lv_obj_remove_flag(this->sub_label_, LV_OBJ_FLAG_HIDDEN); + } + + KnobScale scale_; +}; + +} // namespace + +std::unique_ptr make_climate_view(lv_obj_t *parent, const Block &block, const Theme &theme, + ControlSink &sink) { + return std::make_unique(parent, block, theme, sink); +} + +} // namespace ha_controller +} // namespace esphome diff --git a/esphome/components/ha_controller/color.h b/esphome/components/ha_controller/color.h new file mode 100644 index 0000000..2e0e0e5 --- /dev/null +++ b/esphome/components/ha_controller/color.h @@ -0,0 +1,44 @@ +#pragma once +#include +#include +#include + +namespace esphome { +namespace ha_controller { + +// Parses "RRGGBB" or "#RRGGBB" (either case). `out` is untouched on failure. +inline bool parse_hex_rgb(const std::string &hex, uint32_t &out) { + size_t start = (!hex.empty() && hex[0] == '#') ? 1 : 0; + if (hex.size() - start != 6) + return false; + uint32_t v = 0; + for (size_t i = start; i < hex.size(); i++) { + char c = hex[i]; + uint32_t d; + if (c >= '0' && c <= '9') + d = c - '0'; + else if (c >= 'a' && c <= 'f') + d = c - 'a' + 10; + else if (c >= 'A' && c <= 'F') + d = c - 'A' + 10; + else + return false; + v = (v << 4) | d; + } + out = v; + return true; +} + +// WCAG 2.x relative luminance of an 0xRRGGBB colour. +inline float relative_luminance(uint32_t rgb) { + auto lin = [](uint32_t c8) { + float c = c8 / 255.0f; + return c <= 0.03928f ? c / 12.92f : std::pow((c + 0.055f) / 1.055f, 2.4f); + }; + return 0.2126f * lin((rgb >> 16) & 0xFF) + 0.7152f * lin((rgb >> 8) & 0xFF) + 0.0722f * lin(rgb & 0xFF); +} + +inline uint32_t text_color_for(uint32_t rgb) { return relative_luminance(rgb) > 0.30f ? 0x000000 : 0xFFFFFF; } + +} // namespace ha_controller +} // namespace esphome diff --git a/esphome/components/ha_controller/custom_view.cpp b/esphome/components/ha_controller/custom_view.cpp new file mode 100644 index 0000000..0eafe91 --- /dev/null +++ b/esphome/components/ha_controller/custom_view.cpp @@ -0,0 +1,251 @@ +#include "views.h" + +#include "esphome/core/hal.h" +#include "format.h" +#include "stack.h" + +namespace esphome { +namespace ha_controller { + +namespace { + +constexpr int COLUMN_WIDTH = 320; +constexpr int SLIDER_WIDTH = 220; +constexpr uint32_t BRIGHTNESS_THROTTLE_MS = 100; +constexpr uint32_t SLIDER_HOLD_MS = 600; + +const char *const DASH = "\xE2\x80\x94"; + +// Items stacked vertically and centred. Entity text arrives through apply(); battery and brightness follow +// the local sources through on_local_update(). +class CustomView final : public BlockView { + public: + CustomView(lv_obj_t *parent, const Block &block, const Theme &theme, const LocalSources &local) + : local_(local), fg_(text_color_for(block.bg)) { + this->id_ = block.id; + this->root_ = make_page_root(parent, block, theme); + + if (block.items.empty()) { + lv_obj_t *name = make_label(this->root_, theme.text[font_index(block.font)], this->fg_, block.name.c_str()); + lv_obj_set_width(name, theme.size * 7 / 10); + lv_obj_center(name); + return; + } + + for (const auto &item : block.items) + this->add_item_(this->root_, item, theme); + this->on_local_update(); + this->layout_items_(); + } + + bool owns(const std::string &id) const override { + if (id == this->id_) + return true; + for (const auto &e : this->entities_) { + if (e.id == id) + return true; + } + return false; + } + + void apply(const StateUpdate &u, uint32_t) override { + for (const auto &e : this->entities_) { + if (e.id == u.id && u.text.has_value()) + lv_label_set_text(e.label, u.text->c_str()); + } + this->layout_items_(); + } + + void on_local_update() override { + if (this->battery_label_ != nullptr) { + float level = this->local_.battery != nullptr ? this->local_.battery->state : NAN; + bool charging = this->local_.charging != nullptr && this->local_.charging->has_state() && + this->local_.charging->state; + lv_label_set_text(this->battery_icon_, charging ? "\xE2\x9A\xA1" : "\xF0\x9F\x94\x8B"); + lv_label_set_text(this->battery_label_, format_percent(level).c_str()); + } + if (this->slider_ != nullptr && this->local_.brightness != nullptr && this->local_.brightness->has_state()) { + if (lv_slider_is_dragged(this->slider_) || this->slider_hold_.active(millis())) + this->slider_stale_ = true; // applied by loop() once the interaction hold has expired + else + lv_slider_set_value(this->slider_, (int) lroundf(this->local_.brightness->state), LV_ANIM_OFF); + } + this->layout_items_(); + } + + protected: + struct Entity { + std::string id; + lv_obj_t *label; + }; + + void loop(uint32_t now_ms) override { + if (this->slider_stale_ && !this->slider_hold_.active(now_ms)) { + this->slider_stale_ = false; + this->on_local_update(); + } + } + + // Stacks the items vertically around the centre (see layout_stack): gap 8 -> 0 px, one-line text and a + // shift of the whole stack keep every control inside radius 185. + void layout_items_() { + if (this->stack_.empty()) + return; + for (auto &row : this->rows_) + layout_row(row.row, row.left, row.right, row.gap); + this->cap_labels_(false); + StackLayout l = this->compute_(this->items_geometry_()); + if (!l.fits) { + this->cap_labels_(true); + l = this->compute_(this->items_geometry_()); + } + const int cy = lv_obj_get_height(this->root_) / 2; + for (size_t i = 0; i < this->stack_.size(); i++) + lv_obj_align(this->stack_[i], LV_ALIGN_TOP_MID, 0, cy + l.top[i]); + } + + std::vector items_geometry_() { + std::vector g; + for (lv_obj_t *o : this->stack_) { + lv_obj_update_layout(o); + g.push_back({lv_obj_get_height(o), lv_obj_get_width(o) / 2, o == this->slider_row_}); + } + return g; + } + + StackLayout compute_(const std::vector &g) { return layout_stack(g, CONTROL_RADIUS, 233); } + + // Text items: natural wrapping, or a single line with dots when the stack is too tall. + void cap_labels_(bool cap) { + for (lv_obj_t *o : this->text_labels_) { + if (cap) { + lv_label_set_long_mode(o, LV_LABEL_LONG_MODE_DOTS); + const lv_font_t *font = lv_obj_get_style_text_font(o, LV_PART_MAIN); + lv_obj_set_height(o, lv_font_get_line_height(font)); + } else { + lv_label_set_long_mode(o, LV_LABEL_LONG_MODE_WRAP); + lv_obj_set_height(o, LV_SIZE_CONTENT); + } + } + } + + void add_item_(lv_obj_t *parent, const Item &item, const Theme &theme) { + const int f = font_index(item.font); + switch (item.kind) { + case ItemKind::TEXT: + case ItemKind::EMOJI: { + const lv_font_t *font = item.kind == ItemKind::TEXT ? theme.text[f] : theme.emoji[f]; + lv_obj_t *label = make_label(parent, font, this->fg_, item.text.c_str()); + lv_obj_set_width(label, COLUMN_WIDTH); + this->stack_.push_back(label); + this->text_labels_.push_back(label); + break; + } + case ItemKind::ENTITY: { + lv_obj_t *label = make_label(parent, theme.text[f], this->fg_, DASH); + lv_obj_set_width(label, COLUMN_WIDTH); + this->entities_.push_back({item.id, label}); + this->stack_.push_back(label); + this->text_labels_.push_back(label); + break; + } + case ItemKind::BATTERY: { + lv_obj_t *row = this->make_row_(parent); + this->battery_icon_ = make_label(row, theme.emoji[f], this->fg_, "\xF0\x9F\x94\x8B"); + this->battery_label_ = make_label(row, theme.text[f], this->fg_, ""); + this->rows_.push_back({row, this->battery_icon_, this->battery_label_, 12}); + break; + } + case ItemKind::BRIGHTNESS: { + lv_obj_t *row = this->make_row_(parent); + this->slider_row_ = row; + lv_obj_t *icon = make_label(row, theme.emoji[f], this->fg_, "\xE2\x98\x80"); + this->slider_ = lv_slider_create(row); + lv_obj_set_size(this->slider_, SLIDER_WIDTH, 24); + lv_slider_set_range(this->slider_, 5, 100); + lv_slider_set_value(this->slider_, 80, LV_ANIM_OFF); + lv_obj_set_ext_click_area(this->slider_, 12); + lv_obj_set_style_bg_color(this->slider_, lv_color_hex(this->fg_), LV_PART_MAIN); + lv_obj_set_style_bg_opa(this->slider_, LV_OPA_30, LV_PART_MAIN); + lv_obj_set_style_bg_color(this->slider_, lv_color_hex(this->fg_), LV_PART_INDICATOR); + lv_obj_set_style_bg_opa(this->slider_, LV_OPA_COVER, LV_PART_INDICATOR); + lv_obj_set_style_bg_color(this->slider_, lv_color_hex(this->fg_), LV_PART_KNOB); + lv_obj_set_style_bg_opa(this->slider_, LV_OPA_COVER, LV_PART_KNOB); + lv_obj_add_event_cb(this->slider_, CustomView::slider_event_, LV_EVENT_ALL, this); + this->rows_.push_back({row, icon, this->slider_, 12}); + break; + } + } + } + + lv_obj_t *make_row_(lv_obj_t *parent) { + lv_obj_t *row = lv_obj_create(parent); + lv_obj_remove_style_all(row); + lv_obj_remove_flag(row, LV_OBJ_FLAG_SCROLLABLE); + lv_obj_remove_flag(row, LV_OBJ_FLAG_CLICKABLE); + this->stack_.push_back(row); + return row; + } + + void set_brightness_(int value) { + if (this->local_.brightness != nullptr) + this->local_.brightness->make_call().set_value((float) value).perform(); + } + + // At most one call per 100 ms while dragging, and always one on release. + static void slider_event_(lv_event_t *e) { + if (lv_event_get_code(e) == LV_EVENT_DELETE) + return; + auto *self = static_cast(lv_event_get_user_data(e)); + lv_obj_t *slider = static_cast(lv_event_get_target(e)); + switch (lv_event_get_code(e)) { + case LV_EVENT_PRESSED: + self->slider_hold_.touch(millis()); + break; + case LV_EVENT_VALUE_CHANGED: { + uint32_t now = millis(); + self->slider_hold_.touch(now); + if (now - self->last_call_ms_ >= BRIGHTNESS_THROTTLE_MS) { + self->last_call_ms_ = now; + self->set_brightness_(lv_slider_get_value(slider)); + } + break; + } + case LV_EVENT_RELEASED: + self->slider_hold_.touch(millis()); + self->last_call_ms_ = millis(); + self->set_brightness_(lv_slider_get_value(slider)); + break; + default: + break; + } + } + + LocalSources local_; + uint32_t fg_; + struct Row { + lv_obj_t *row, *left, *right; + int gap; + }; + std::vector entities_; + std::vector stack_; + std::vector rows_; + lv_obj_t *battery_icon_{nullptr}; + lv_obj_t *battery_label_{nullptr}; + lv_obj_t *slider_{nullptr}; + lv_obj_t *slider_row_{nullptr}; + std::vector text_labels_; + InteractionHold slider_hold_{SLIDER_HOLD_MS}; + bool slider_stale_{false}; + uint32_t last_call_ms_{0}; +}; + +} // namespace + +std::unique_ptr make_custom_view(lv_obj_t *parent, const Block &block, const Theme &theme, + const LocalSources &local) { + return std::make_unique(parent, block, theme, local); +} + +} // namespace ha_controller +} // namespace esphome diff --git a/esphome/components/ha_controller/format.h b/esphome/components/ha_controller/format.h new file mode 100644 index 0000000..c62a7ff --- /dev/null +++ b/esphome/components/ha_controller/format.h @@ -0,0 +1,25 @@ +#pragma once +#include +#include +#include + +namespace esphome { +namespace ha_controller { + +// One decimal when step < 1, none otherwise. +inline std::string format_value(float value, float step) { + char buf[32]; + std::snprintf(buf, sizeof buf, step < 1.0f ? "%.1f" : "%.0f", (double) value); + return buf; +} + +inline std::string format_percent(float pct) { + if (std::isnan(pct)) + return "— %"; + char buf[32]; + std::snprintf(buf, sizeof buf, "%.0f %%", (double) pct); + return buf; +} + +} // namespace ha_controller +} // namespace esphome diff --git a/esphome/components/ha_controller/gesture.cpp b/esphome/components/ha_controller/gesture.cpp new file mode 100644 index 0000000..d6827f5 --- /dev/null +++ b/esphome/components/ha_controller/gesture.cpp @@ -0,0 +1,147 @@ +#include "gesture.h" + +namespace esphome { +namespace ha_controller { + +Edge classify_edge(int x, int y, int size, int edge_width) { + const float centre = size / 2.0f; + const float dx = x - centre; + const float dy = y - centre; + const float inner = size / 2.0f - edge_width; + if (inner > 0 && dx * dx + dy * dy < inner * inner) { + return Edge::NONE; + } + const float abs_dx = dx < 0 ? -dx : dx; + const float abs_dy = dy < 0 ? -dy : dy; + if (abs_dx >= abs_dy) { + return dx < 0 ? Edge::LEFT : Edge::RIGHT; + } + return dy < 0 ? Edge::TOP : Edge::BOTTOM; +} + +GridStep step_for(Edge edge) { + switch (edge) { + case Edge::RIGHT: + return {1, 0}; + case Edge::LEFT: + return {-1, 0}; + case Edge::TOP: + return {0, -1}; + case Edge::BOTTOM: + return {0, 1}; + case Edge::NONE: + default: + return {0, 0}; + } +} + +SwipeTracker::SwipeTracker(SwipeConfig cfg) : cfg_(cfg) {} + +void SwipeTracker::begin(Edge edge, bool has_target, int x, int y, uint32_t t_ms) { + edge_ = edge; + has_target_ = has_target; + start_x_ = x; + start_y_ = y; + raw_ = 0; + visual_ = 0; + sample_count_ = 0; + active_ = edge != Edge::NONE; + if (active_) { + push_sample(t_ms, 0); + } +} + +int SwipeTracker::update(int x, int y, uint32_t t_ms) { + if (!active_) { + return 0; + } + // Progress is movement towards the centre along the navigation axis; outward movement counts as zero. + const GridStep step = step_for(edge_); + int moved = -(step.dx * (x - start_x_) + step.dy * (y - start_y_)); + if (moved < 0) { + moved = 0; + } + if (moved > cfg_.size) { + moved = cfg_.size; + } + raw_ = moved; + if (has_target_) { + visual_ = raw_; + } else { + // No block in that direction: rubber band, capped. + const int banded = static_cast(raw_ * cfg_.rubber_factor + 0.5f); + visual_ = banded < cfg_.rubber_max_px ? banded : cfg_.rubber_max_px; + } + push_sample(t_ms, raw_); + return visual_; +} + +bool SwipeTracker::release(uint32_t t_ms) { + if (!active_) { + return false; + } + bool commit = false; + if (has_target_) { + const bool far_enough = raw_ >= cfg_.commit_ratio * cfg_.size; + const bool flick = velocity_at(t_ms) >= cfg_.flick_velocity && raw_ >= cfg_.flick_min_px; + commit = far_enough || flick; + } + active_ = false; + return commit; +} + +void SwipeTracker::reset() { + active_ = false; + raw_ = 0; + visual_ = 0; + sample_count_ = 0; +} + +void SwipeTracker::push_sample(uint32_t t_ms, int raw) { + if (sample_count_ == kMaxSamples) { + for (int i = 1; i < kMaxSamples; ++i) { + samples_[i - 1] = samples_[i]; + } + sample_count_ = kMaxSamples - 1; + } + samples_[sample_count_++] = Sample{t_ms, raw}; +} + +// Velocity in px per ms between the oldest sample inside the window and the latest sample. +float SwipeTracker::velocity_at(uint32_t t_ms) const { + if (sample_count_ == 0) { + return 0.0f; + } + const Sample &latest = samples_[sample_count_ - 1]; + for (int i = 0; i < sample_count_; ++i) { + const uint32_t age = t_ms - samples_[i].t_ms; // unsigned: survives millis() wraparound + if (age <= cfg_.velocity_window_ms) { + const uint32_t dt = t_ms - samples_[i].t_ms; + if (dt == 0) { + return 0.0f; + } + return static_cast(latest.raw - samples_[i].raw) / static_cast(dt); + } + } + return 0.0f; +} + +uint32_t settle_duration_ms(int remaining_px, int size) { + if (remaining_px < 0) { + remaining_px = 0; + } + if (size <= 0) { + return 220; + } + const uint32_t scaled = 220u * static_cast(remaining_px) / static_cast(size); + if (scaled < 80u) { + return 80u; + } + if (scaled > 220u) { + return 220u; + } + return scaled; +} + +} // namespace ha_controller +} // namespace esphome diff --git a/esphome/components/ha_controller/gesture.h b/esphome/components/ha_controller/gesture.h new file mode 100644 index 0000000..a714380 --- /dev/null +++ b/esphome/components/ha_controller/gesture.h @@ -0,0 +1,76 @@ +#pragma once +#include + +namespace esphome { +namespace ha_controller { + +// Edge-swipe gesture model (spec 5.2-5.3). Pure logic, no ESPHome or LVGL. +enum class Edge : uint8_t { NONE, LEFT, RIGHT, TOP, BOTTOM }; + +struct GridStep { + int dx; + int dy; +}; + +// Classifies a touch point in a size x size screen. Only points in the outer ring +// (distance from centre >= size/2 - edge_width) belong to an edge. The dominant axis wins. +Edge classify_edge(int x, int y, int size, int edge_width); + +// Grid direction of the block reached by swiping from the given edge towards the centre. +GridStep step_for(Edge edge); + +struct SwipeConfig { + int size = 466; + float commit_ratio = 0.25f; + float flick_velocity = 0.6f; // px per ms + int flick_min_px = 24; + float rubber_factor = 0.3f; + int rubber_max_px = 48; + uint32_t velocity_window_ms = 100; +}; + +class SwipeTracker { + public: + explicit SwipeTracker(SwipeConfig cfg = {}); + + // Starts a swipe. has_target is false when no block exists in that direction (rubber band only). + void begin(Edge edge, bool has_target, int x, int y, uint32_t t_ms); + // Returns the visual offset (px) along the navigation axis. + int update(int x, int y, uint32_t t_ms); + // True = commit the navigation. The tracker becomes inactive either way. + bool release(uint32_t t_ms); + // Aborts the swipe without a decision. + void reset(); + + bool active() const { return active_; } + Edge edge() const { return edge_; } + // Last visual offset (px), as returned by update(). + int progress() const { return visual_; } + + private: + struct Sample { + uint32_t t_ms; + int raw; + }; + static constexpr int kMaxSamples = 16; + + void push_sample(uint32_t t_ms, int raw); + float velocity_at(uint32_t t_ms) const; + + SwipeConfig cfg_; + bool active_{false}; + bool has_target_{false}; + Edge edge_{Edge::NONE}; + int start_x_{0}; + int start_y_{0}; + int raw_{0}; + int visual_{0}; + Sample samples_[kMaxSamples]{}; + int sample_count_{0}; +}; + +// Settle animation length: clamp(220 * remaining / size, 80, 220) ms. +uint32_t settle_duration_ms(int remaining_px, int size); + +} // namespace ha_controller +} // namespace esphome diff --git a/esphome/components/ha_controller/ha_controller.cpp b/esphome/components/ha_controller/ha_controller.cpp new file mode 100644 index 0000000..0ab0a66 --- /dev/null +++ b/esphome/components/ha_controller/ha_controller.cpp @@ -0,0 +1,194 @@ +#include "ha_controller.h" + +#include "esphome/core/application.h" +#include "esphome/core/hal.h" +#include "esphome/core/log.h" + +#include "states.h" + +namespace esphome { +namespace ha_controller { + +static const char *const TAG = "ha_controller"; + +void HaController::set_font(FontRole role, FontSize size, font::Font *font) { + const lv_font_t *f = font->get_lv_font(); + int i = static_cast(size); + switch (role) { + case FontRole::TEXT: + this->theme_.text[i] = f; + break; + case FontRole::VALUE: + this->theme_.value[i] = f; + break; + case FontRole::EMOJI: + this->theme_.emoji[i] = f; + break; + } +} + +void HaController::setup() { + this->screen_ = lv_obj_create(nullptr); + lv_obj_remove_flag(this->screen_, LV_OBJ_FLAG_SCROLLABLE); + lv_obj_set_style_bg_color(this->screen_, lv_color_black(), 0); + lv_obj_set_style_bg_opa(this->screen_, LV_OPA_COVER, 0); + lv_screen_load(this->screen_); + this->pager_.attach(this->screen_, this->theme_.size, this->theme_.edge_width); + + // Local sources are subscribed once here and forwarded to the live view. + if (this->local_.battery != nullptr) + this->local_.battery->add_on_state_callback([this](float) { this->on_local_update_(); }); + if (this->local_.charging != nullptr) + this->local_.charging->add_on_state_callback([this](bool) { this->on_local_update_(); }); + if (this->local_.brightness != nullptr) + this->local_.brightness->add_on_state_callback([this](float) { this->on_local_update_(); }); + + this->refresh_mode_(); +} + +void WakeListener::release() { this->parent_->wake(); } + +void HaController::wake() { + if (!this->sleeping_) + return; + this->sleeping_ = false; + ESP_LOGD(TAG, "Waking"); + for (auto &cb : this->wake_callbacks_) + cb(); + lv_display_trigger_activity(nullptr); // restart the inactivity timer +} + +void HaController::loop() { + if (!this->sleeping_ && should_sleep(lv_display_get_inactive_time(nullptr), this->sleep_timeout_s_)) { + this->sleeping_ = true; + ESP_LOGD(TAG, "Sleeping"); + for (auto &cb : this->sleep_callbacks_) + cb(); + } + if (this->sleeping_) + return; // LVGL is paused; layouts and states still apply through set_layout / set_states + uint32_t now = millis(); + for (auto &view : this->views_) + view->loop(now); +} + +void HaController::on_local_update_() { + for (auto &view : this->views_) + view->on_local_update(); +} + +void HaController::set_layout(const std::string &json) { + Layout parsed; + ParseError err = parse_layout(json, parsed); + if (err == ParseError::UNSUPPORTED_VERSION) { + ESP_LOGW(TAG, "Layout protocol not supported"); + this->show_message("Firmware update required", "Open Home Assistant to update"); + return; + } + if (err != ParseError::NONE) { + ESP_LOGW(TAG, "Invalid layout: %s", parse_error_code(err)); + this->show_message("Invalid layout", parse_error_code(err)); + return; + } + this->layout_ = std::move(parsed); + this->set_sleep_timeout(this->layout_.sleep_s); + this->has_layout_ = true; + ESP_LOGI(TAG, "Layout %s applied (%u blocks)", this->layout_.rev.c_str(), (unsigned) this->layout_.blocks.size()); + this->rebuild_views_(); + this->refresh_mode_(); +} + +void HaController::rebuild_views_() { + // Keep the block on screen when it still exists, else the start block, else the first one. + std::string show = this->pager_.current_id(); + if (this->layout_.find(show) == nullptr) + show = this->layout_.start; + if (this->layout_.find(show) == nullptr && !this->layout_.blocks.empty()) + show = this->layout_.blocks.front().id; + // The pager forgets the old pages (and cancels any swipe or animation) before their objects are deleted. + this->pager_.set_pages({}, ""); + this->views_.clear(); + std::vector pages; + for (const auto &block : this->layout_.blocks) { + auto view = make_block_view(this->pager_.viewport(), block, this->theme_, *this, this->local_); + pages.push_back({block.id, block.x, block.y, view->root()}); + this->views_.push_back(std::move(view)); + } + this->pager_.set_pages(std::move(pages), show); +} + +void HaController::set_states(const std::string &json) { + std::vector updates; + if (!parse_states(json, updates)) { + ESP_LOGW(TAG, "Invalid states payload"); + return; + } + // Every view receives its states, visible or not: the integration does not resend them on navigation. + uint32_t now = millis(); + for (const auto &u : updates) { + for (auto &view : this->views_) { + if (view->owns(u.id)) + view->apply(u, now); + } + } +} + +void HaController::refresh_mode_() { + if (!this->has_layout_) { + std::string detail = App.get_name(); +#ifdef ESPHOME_PROJECT_VERSION + detail += " \xC2\xB7 v" ESPHOME_PROJECT_VERSION; +#endif + this->show_message("Waiting for Home Assistant", detail); + } else if (this->layout_.blocks.empty()) { + this->show_message("No blocks yet", "Add blocks in Home Assistant \xE2\x80\xBA HA Controller"); + } else { + if (this->overlay_ != nullptr) + lv_obj_add_flag(this->overlay_, LV_OBJ_FLAG_HIDDEN); + this->pager_.set_enabled(true); + } +} + +void HaController::show_message(const std::string &title, const std::string &detail) { + this->wake(); + this->pager_.set_enabled(false); + if (this->overlay_ == nullptr) { + this->overlay_ = lv_obj_create(lv_layer_top()); + lv_obj_remove_style_all(this->overlay_); + lv_obj_set_size(this->overlay_, this->theme_.size, this->theme_.size); + lv_obj_set_pos(this->overlay_, 0, 0); + lv_obj_remove_flag(this->overlay_, LV_OBJ_FLAG_SCROLLABLE); + lv_obj_set_style_bg_color(this->overlay_, lv_color_black(), 0); + lv_obj_set_style_bg_opa(this->overlay_, LV_OPA_COVER, 0); + int width = this->theme_.size * 7 / 10; + + this->title_label_ = lv_label_create(this->overlay_); + lv_obj_set_width(this->title_label_, width); + lv_obj_set_style_text_align(this->title_label_, LV_TEXT_ALIGN_CENTER, 0); + lv_obj_set_style_text_font(this->title_label_, this->theme_.text[static_cast(FontSize::M)], 0); + lv_obj_set_style_text_color(this->title_label_, lv_color_white(), 0); + lv_obj_align(this->title_label_, LV_ALIGN_CENTER, 0, -30); + + this->detail_label_ = lv_label_create(this->overlay_); + lv_obj_set_width(this->detail_label_, width); + lv_obj_set_style_text_align(this->detail_label_, LV_TEXT_ALIGN_CENTER, 0); + lv_obj_set_style_text_font(this->detail_label_, this->theme_.text[static_cast(FontSize::S)], 0); + lv_obj_set_style_text_color(this->detail_label_, lv_color_hex(0x9CA3AF), 0); + lv_obj_align(this->detail_label_, LV_ALIGN_CENTER, 0, 40); + } + lv_label_set_text(this->title_label_, title.c_str()); + lv_label_set_text(this->detail_label_, detail.c_str()); + lv_obj_remove_flag(this->overlay_, LV_OBJ_FLAG_HIDDEN); + lv_obj_move_foreground(this->overlay_); + lv_refr_now(nullptr); +} + +void HaController::hide_message() { this->refresh_mode_(); } + +void HaController::on_control(const std::string &block, const std::string &item, const char *op, float value) { + for (auto &cb : this->control_callbacks_) + cb(block, item, op, value); +} + +} // namespace ha_controller +} // namespace esphome diff --git a/esphome/components/ha_controller/ha_controller.h b/esphome/components/ha_controller/ha_controller.h new file mode 100644 index 0000000..d141105 --- /dev/null +++ b/esphome/components/ha_controller/ha_controller.h @@ -0,0 +1,117 @@ +#pragma once +#include +#include +#include +#include + +#include "esphome/components/binary_sensor/binary_sensor.h" +#include "esphome/components/font/font.h" +#include "esphome/components/number/number.h" +#include "esphome/components/sensor/sensor.h" +#include "esphome/components/touchscreen/touchscreen.h" +#include "esphome/core/automation.h" +#include "esphome/core/component.h" + +#include "layout.h" +#include "pager.h" +#include "sleep.h" +#include "widgets.h" + +namespace esphome { +namespace ha_controller { + +enum class FontRole : uint8_t { TEXT, VALUE, EMOJI }; + +class HaController; + +// Wakes the screen when a touch is released while it sleeps. +class WakeListener : public touchscreen::TouchListener { + public: + explicit WakeListener(HaController *parent) : parent_(parent) {} + void release() override; + + protected: + HaController *parent_; +}; + +class HaController : public Component, public ControlSink { + public: + void setup() override; + void loop() override; + float get_setup_priority() const override { return setup_priority::LATE; } + + void set_geometry(int size, int edge_width) { + this->theme_.size = size; + this->theme_.edge_width = edge_width; + } + // The ESPHome font already carries the lv_font_t used by LVGL (font::Font::get_lv_font()). + void set_font(FontRole role, FontSize size, font::Font *font); + void set_battery_sensor(sensor::Sensor *s) { this->local_.battery = s; } + void set_charging_sensor(binary_sensor::BinarySensor *s) { this->local_.charging = s; } + void set_brightness_number(number::Number *n) { this->local_.brightness = n; } + void set_touchscreen(touchscreen::Touchscreen *ts) { ts->register_listener(&this->wake_listener_); } + void set_sleep_timeout(uint32_t seconds) { this->sleep_timeout_s_ = seconds; } + bool is_sleeping() const { return this->sleeping_; } + void wake(); + void add_on_sleep_callback(std::function &&cb) { this->sleep_callbacks_.push_back(std::move(cb)); } + void add_on_wake_callback(std::function &&cb) { this->wake_callbacks_.push_back(std::move(cb)); } + void add_on_control_callback(std::function &&cb) { + this->control_callbacks_.push_back(std::move(cb)); + } + + void set_layout(const std::string &json); + void set_states(const std::string &json); + void show_message(const std::string &title, const std::string &detail); + void hide_message(); + std::string get_revision() const { return this->has_layout_ ? this->layout_.rev : "none"; } + + void on_control(const std::string &block, const std::string &item, const char *op, float value) override; + + protected: + void rebuild_views_(); + void refresh_mode_(); + void on_local_update_(); + + Theme theme_{{}, {}, {}, 466, 36}; + LocalSources local_; + Layout layout_; + bool has_layout_{false}; + Pager pager_; + std::vector> views_; + lv_obj_t *screen_{nullptr}; + lv_obj_t *overlay_{nullptr}; + lv_obj_t *title_label_{nullptr}; + lv_obj_t *detail_label_{nullptr}; + std::vector> control_callbacks_; + std::vector> sleep_callbacks_; + std::vector> wake_callbacks_; + WakeListener wake_listener_{this}; + uint32_t sleep_timeout_s_{DEFAULT_SLEEP_S}; + bool sleeping_{false}; +}; + +class SleepTrigger : public Trigger<> { + public: + explicit SleepTrigger(HaController *parent) { + parent->add_on_sleep_callback([this]() { this->trigger(); }); + } +}; + +class WakeTrigger : public Trigger<> { + public: + explicit WakeTrigger(HaController *parent) { + parent->add_on_wake_callback([this]() { this->trigger(); }); + } +}; + +class ControlTrigger : public Trigger { + public: + explicit ControlTrigger(HaController *parent) { + parent->add_on_control_callback([this](std::string block, std::string item, std::string op, float value) { + this->trigger(std::move(block), std::move(item), std::move(op), value); + }); + } +}; + +} // namespace ha_controller +} // namespace esphome diff --git a/esphome/components/ha_controller/hold.h b/esphome/components/ha_controller/hold.h new file mode 100644 index 0000000..d261b85 --- /dev/null +++ b/esphome/components/ha_controller/hold.h @@ -0,0 +1,24 @@ +#pragma once +#include + +namespace esphome { +namespace ha_controller { + +// Ignores incoming state for window_ms after the last local touch. +class InteractionHold { + public: + explicit InteractionHold(uint32_t window_ms = 1500) : window_ms_(window_ms) {} + void touch(uint32_t now_ms) { + last_ = now_ms; + touched_ = true; + } + bool active(uint32_t now_ms) const { return touched_ && (uint32_t) (now_ms - last_) < window_ms_; } + + private: + uint32_t window_ms_; + uint32_t last_{0}; + bool touched_{false}; +}; + +} // namespace ha_controller +} // namespace esphome diff --git a/esphome/components/ha_controller/knob.h b/esphome/components/ha_controller/knob.h new file mode 100644 index 0000000..774bca9 --- /dev/null +++ b/esphome/components/ha_controller/knob.h @@ -0,0 +1,30 @@ +#pragma once +#include + +namespace esphome { +namespace ha_controller { + +struct KnobScale { + float min, max, step; + + int steps() const { + if (max <= min) + return 0; + float s = step > 0 ? step : 1.0f; + return (int) std::lround((max - min) / s); + } + int index_of(float value) const { + float s = step > 0 ? step : 1.0f; + int i = (int) std::lround((value - min) / s); + int n = steps(); + return i < 0 ? 0 : (i > n ? n : i); + } + float value_at(int index) const { + float s = step > 0 ? step : 1.0f; + float v = min + (float) index * s; + return v < min ? min : (v > max ? max : v); + } +}; + +} // namespace ha_controller +} // namespace esphome diff --git a/esphome/components/ha_controller/knob_view.cpp b/esphome/components/ha_controller/knob_view.cpp new file mode 100644 index 0000000..2cadab4 --- /dev/null +++ b/esphome/components/ha_controller/knob_view.cpp @@ -0,0 +1,155 @@ +#include "views.h" + +#include + +#include "esphome/core/hal.h" + +namespace esphome { +namespace ha_controller { + +KnobBlockView::KnobBlockView(lv_obj_t *parent, const Block &block, const Theme &theme, ControlSink &sink, + bool tappable_centre) + : sink_(sink), theme_(theme), fg_(text_color_for(block.bg)), bg_(block.bg) { + this->id_ = block.id; + this->root_ = make_page_root(parent, block, theme); + const int f = font_index(block.font); + + lv_obj_t *name = make_label(this->root_, theme.text[f], this->fg_, block.name.c_str()); + lv_obj_set_width(name, 180); + lv_label_set_long_mode(name, LV_LABEL_LONG_MODE_DOTS); + lv_obj_align(name, LV_ALIGN_TOP_MID, 0, NAME_TOP); + + // Centre first (below the arc) so the ring always wins the touches it covers. + this->centre_ = lv_obj_create(this->root_); + lv_obj_remove_style_all(this->centre_); + lv_obj_set_size(this->centre_, 290, 290); + lv_obj_align(this->centre_, LV_ALIGN_CENTER, 0, 0); + lv_obj_remove_flag(this->centre_, LV_OBJ_FLAG_SCROLLABLE); + lv_obj_set_style_radius(this->centre_, LV_RADIUS_CIRCLE, 0); + lv_obj_set_style_pad_all(this->centre_, 0, 0); + if (tappable_centre) { + lv_obj_add_flag(this->centre_, LV_OBJ_FLAG_CLICKABLE); + lv_obj_add_flag(this->centre_, LV_OBJ_FLAG_ADV_HITTEST); + lv_obj_add_event_cb(this->centre_, KnobBlockView::centre_event_, LV_EVENT_CLICKED, this); + } else { + lv_obj_remove_flag(this->centre_, LV_OBJ_FLAG_CLICKABLE); + } + lv_obj_set_style_opa(this->centre_, LV_OPA_40, LV_STATE_DISABLED); + + this->value_label_ = make_label(this->centre_, theme.value[f], this->fg_, "\xE2\x80\x94"); + this->sub_label_ = make_label(this->centre_, theme.text[font_index(FontSize::S)], this->fg_, ""); + lv_obj_set_width(this->sub_label_, 240); + lv_obj_add_flag(this->sub_label_, LV_OBJ_FLAG_HIDDEN); + + this->arc_ = lv_arc_create(this->root_); + lv_obj_set_size(this->arc_, KNOB_DIAMETER, KNOB_DIAMETER); + lv_obj_align(this->arc_, LV_ALIGN_CENTER, 0, 0); + lv_arc_set_rotation(this->arc_, 0); + lv_arc_set_bg_angles(this->arc_, 135, 45); + lv_arc_set_range(this->arc_, 0, 100); + lv_arc_set_value(this->arc_, 0); + lv_obj_add_flag(this->arc_, LV_OBJ_FLAG_ADV_HITTEST); + lv_obj_set_style_arc_width(this->arc_, KNOB_WIDTH, LV_PART_MAIN); + lv_obj_set_style_arc_width(this->arc_, KNOB_WIDTH, LV_PART_INDICATOR); + lv_obj_set_style_arc_color(this->arc_, lv_color_hex(this->fg_), LV_PART_MAIN); + lv_obj_set_style_arc_opa(this->arc_, LV_OPA_30, LV_PART_MAIN); + lv_obj_set_style_arc_color(this->arc_, lv_color_hex(this->fg_), LV_PART_INDICATOR); + lv_obj_set_style_arc_opa(this->arc_, LV_OPA_COVER, LV_PART_INDICATOR); + lv_obj_set_style_bg_color(this->arc_, lv_color_hex(this->fg_), LV_PART_KNOB); + lv_obj_set_style_bg_opa(this->arc_, LV_OPA_COVER, LV_PART_KNOB); + lv_obj_set_style_pad_all(this->arc_, 0, LV_PART_KNOB); + lv_obj_set_style_opa(this->arc_, LV_OPA_40, LV_STATE_DISABLED); + lv_obj_add_event_cb(this->arc_, KnobBlockView::arc_event_, LV_EVENT_ALL, this); +} + +void layout_row(lv_obj_t *row, lv_obj_t *left, lv_obj_t *right, int gap) { + lv_obj_update_layout(left); + lv_obj_update_layout(right); + int h = std::max(lv_obj_get_height(left), lv_obj_get_height(right)); + lv_obj_set_size(row, lv_obj_get_width(left) + gap + lv_obj_get_width(right), h); + lv_obj_align(left, LV_ALIGN_LEFT_MID, 0, 0); + lv_obj_align(right, LV_ALIGN_RIGHT_MID, 0, 0); +} + +void KnobBlockView::draw_(const StateUpdate &u) { + this->render_(u); + this->layout_centre_(); +} + +// Value label with the optional small label below it, as a block centred in the centre object. +void KnobBlockView::layout_centre_() { + lv_obj_update_layout(this->centre_); + const int gap = 4; + int hv = lv_obj_get_height(this->value_label_); + bool has_sub = !lv_obj_has_flag(this->sub_label_, LV_OBJ_FLAG_HIDDEN); + int hs = has_sub ? lv_obj_get_height(this->sub_label_) : 0; + int total = hv + (has_sub ? gap + hs : 0); + lv_obj_align(this->value_label_, LV_ALIGN_CENTER, 0, -total / 2 + hv / 2); + if (has_sub) + lv_obj_align(this->sub_label_, LV_ALIGN_CENTER, 0, total / 2 - hs / 2); +} + +void KnobBlockView::touch_() { this->hold_.touch(millis()); } + +void KnobBlockView::set_disabled_(bool disabled) { + lv_obj_t *targets[2] = {this->arc_, this->centre_}; + for (lv_obj_t *o : targets) { + if (disabled) + lv_obj_add_state(o, LV_STATE_DISABLED); + else + lv_obj_remove_state(o, LV_STATE_DISABLED); + } +} + +void KnobBlockView::arc_event_(lv_event_t *e) { + if (lv_event_get_code(e) == LV_EVENT_DELETE) + return; + auto *self = static_cast(lv_event_get_user_data(e)); + if (!self->available_) + return; + lv_obj_t *arc = static_cast(lv_event_get_target(e)); + switch (lv_event_get_code(e)) { + case LV_EVENT_PRESSED: + self->touch_(); + break; + case LV_EVENT_VALUE_CHANGED: + self->touch_(); + self->on_arc_changed_(lv_arc_get_value(arc)); + break; + case LV_EVENT_RELEASED: + self->touch_(); + self->on_arc_released_(lv_arc_get_value(arc)); + break; + default: + break; + } +} + +void KnobBlockView::centre_event_(lv_event_t *e) { + auto *self = static_cast(lv_event_get_user_data(e)); + if (!self->available_) + return; + self->touch_(); + self->on_centre_tap_(); +} + +// While the hold is active the latest update waits; loop() applies it once the hold has expired. +void KnobBlockView::apply(const StateUpdate &u, uint32_t now_ms) { + if (this->hold_.active(now_ms) || lv_obj_has_state(this->arc_, LV_STATE_PRESSED)) { + this->pending_ = u; + this->has_pending_ = true; + return; + } + this->has_pending_ = false; + this->draw_(u); +} + +void KnobBlockView::loop(uint32_t now_ms) { + if (this->has_pending_ && !this->hold_.active(now_ms) && !lv_obj_has_state(this->arc_, LV_STATE_PRESSED)) { + this->has_pending_ = false; + this->draw_(this->pending_); + } +} + +} // namespace ha_controller +} // namespace esphome diff --git a/esphome/components/ha_controller/layout.cpp b/esphome/components/ha_controller/layout.cpp new file mode 100644 index 0000000..fde6097 --- /dev/null +++ b/esphome/components/ha_controller/layout.cpp @@ -0,0 +1,192 @@ +#include "layout.h" + +#include + +#include + +#include "color.h" + +namespace esphome { +namespace ha_controller { + +const Block *Layout::find(const std::string &id) const { + for (const auto &b : this->blocks) + if (b.id == id) + return &b; + return nullptr; +} + +const Block *Layout::find_at(int x, int y) const { + for (const auto &b : this->blocks) + if (b.x == x && b.y == y) + return &b; + return nullptr; +} + +const char *parse_error_code(ParseError e) { + switch (e) { + case ParseError::NONE: + return "none"; + case ParseError::BAD_JSON: + return "bad_json"; + case ParseError::UNSUPPORTED_VERSION: + return "unsupported_version"; + case ParseError::INVALID_PAYLOAD: + return "invalid_payload"; + } + return "invalid_payload"; +} + +namespace { + +bool has_key(JsonVariantConst obj, const char *key) { + for (JsonPairConst kv : obj.as()) + if (kv.key() == key) + return true; + return false; +} + +bool get_string(JsonVariantConst obj, const char *key, std::string &out) { + JsonVariantConst v = obj[key]; + if (!v.is()) + return false; + out = v.as(); + return true; +} + +bool get_int(JsonVariantConst obj, const char *key, int &out) { + JsonVariantConst v = obj[key]; + if (!v.is()) + return false; + out = v.as(); + return true; +} + +bool parse_font(JsonVariantConst obj, FontSize &out) { + std::string s; + if (!get_string(obj, "font", s)) + return false; + if (s == "s") + out = FontSize::S; + else if (s == "m") + out = FontSize::M; + else if (s == "l") + out = FontSize::L; + else if (s == "xl") + out = FontSize::XL; + else + return false; + return true; +} + +// Removes every U+FE0F (UTF-8 EF B8 8F). +std::string strip_variation_selector(const std::string &s) { + std::string out; + out.reserve(s.size()); + for (size_t i = 0; i < s.size(); i++) { + if (i + 2 < s.size() && static_cast(s[i]) == 0xEF && static_cast(s[i + 1]) == 0xB8 && + static_cast(s[i + 2]) == 0x8F) { + i += 2; + continue; + } + out += s[i]; + } + return out; +} + +bool parse_item(JsonVariantConst j, Item &item) { + if (!j.is()) + return false; + std::string kind; + if (!get_string(j, "id", item.id) || !get_string(j, "kind", kind) || !parse_font(j, item.font)) + return false; + if (kind == "text") + item.kind = ItemKind::TEXT; + else if (kind == "emoji") + item.kind = ItemKind::EMOJI; + else if (kind == "entity") + item.kind = ItemKind::ENTITY; + else if (kind == "battery") + item.kind = ItemKind::BATTERY; + else if (kind == "brightness") + item.kind = ItemKind::BRIGHTNESS; + else + return false; + if (item.kind == ItemKind::TEXT || item.kind == ItemKind::EMOJI) { + if (!get_string(j, "text", item.text)) + return false; + if (item.kind == ItemKind::EMOJI) + item.text = strip_variation_selector(item.text); + } + return true; +} + +bool parse_block(JsonVariantConst j, Block &b) { + if (!j.is()) + return false; + std::string bg, widget; + if (!get_string(j, "id", b.id) || !get_int(j, "x", b.x) || !get_int(j, "y", b.y) || !get_string(j, "name", b.name) || + !get_string(j, "bg", bg) || !parse_font(j, b.font) || !get_string(j, "widget", widget)) + return false; + if (bg.size() != 6 || !parse_hex_rgb(bg, b.bg)) + return false; + if (widget == "light") + b.widget = Widget::LIGHT; + else if (widget == "climate") + b.widget = Widget::CLIMATE; + else if (widget == "custom") + b.widget = Widget::CUSTOM; + else + return false; + if (b.widget == Widget::CUSTOM) { + JsonVariantConst items = j["items"]; + if (!items.is()) + return false; + for (JsonVariantConst ij : items.as()) { + Item item; + if (!parse_item(ij, item)) + return false; + b.items.push_back(std::move(item)); + } + } + return true; +} + +} // namespace + +ParseError parse_layout(const std::string &json, Layout &out) { + JsonDocument doc; + if (deserializeJson(doc, json) || !doc.is()) + return ParseError::BAD_JSON; + JsonVariantConst root = doc.as(); + + int v = 0; + if (!get_int(root, "v", v) || v != PROTOCOL_VERSION) + return ParseError::UNSUPPORTED_VERSION; + + Layout l; + JsonVariantConst start = root["start"]; + int sleep = 0; + if (!get_string(root, "rev", l.rev) || !get_int(root, "sleep", sleep) || sleep < 0 || sleep > 3600) + return ParseError::INVALID_PAYLOAD; + l.sleep_s = static_cast(sleep); + if (start.is()) + l.start = start.as(); + else if (!start.isNull() || !has_key(root, "start")) + return ParseError::INVALID_PAYLOAD; + + JsonVariantConst blocks = root["blocks"]; + if (!blocks.is()) + return ParseError::INVALID_PAYLOAD; + for (JsonVariantConst bj : blocks.as()) { + Block b; + if (!parse_block(bj, b)) + return ParseError::INVALID_PAYLOAD; + l.blocks.push_back(std::move(b)); + } + out = std::move(l); + return ParseError::NONE; +} + +} // namespace ha_controller +} // namespace esphome diff --git a/esphome/components/ha_controller/layout.h b/esphome/components/ha_controller/layout.h new file mode 100644 index 0000000..7717ba1 --- /dev/null +++ b/esphome/components/ha_controller/layout.h @@ -0,0 +1,49 @@ +#pragma once +#include +#include +#include + +namespace esphome { +namespace ha_controller { + +constexpr int PROTOCOL_VERSION = 1; + +enum class FontSize : uint8_t { S, M, L, XL }; +enum class Widget : uint8_t { LIGHT, CLIMATE, CUSTOM }; +enum class ItemKind : uint8_t { TEXT, EMOJI, ENTITY, BATTERY, BRIGHTNESS }; +enum class ParseError : uint8_t { NONE, BAD_JSON, UNSUPPORTED_VERSION, INVALID_PAYLOAD }; + +struct Item { + std::string id; + ItemKind kind{ItemKind::TEXT}; + FontSize font{FontSize::M}; + std::string text; +}; + +struct Block { + std::string id; + int x{0}; + int y{0}; + std::string name; + uint32_t bg{0}; + FontSize font{FontSize::M}; + Widget widget{Widget::CUSTOM}; + std::vector items; +}; + +struct Layout { + std::string rev; + std::string start; // "" when the payload has null + uint32_t sleep_s{20}; // payload "sleep"; 0 = never + std::vector blocks; + + const Block *find(const std::string &id) const; + const Block *find_at(int x, int y) const; +}; + +// `out` is replaced only when NONE is returned. +ParseError parse_layout(const std::string &json, Layout &out); +const char *parse_error_code(ParseError e); + +} // namespace ha_controller +} // namespace esphome diff --git a/esphome/components/ha_controller/light_view.cpp b/esphome/components/ha_controller/light_view.cpp new file mode 100644 index 0000000..4df19b2 --- /dev/null +++ b/esphome/components/ha_controller/light_view.cpp @@ -0,0 +1,118 @@ +#include "views.h" + +#include + +namespace esphome { +namespace ha_controller { + +namespace { + +const char *const DASH = "\xE2\x80\x94"; + +// Dimmable light: arc 0-100 with the percentage in the centre. On/off-only light: the centre becomes a +// 220 px round toggle button. Tapping the centre toggles in both cases. +class LightView final : public KnobBlockView { + public: + LightView(lv_obj_t *parent, const Block &block, const Theme &theme, ControlSink &sink) + : KnobBlockView(parent, block, theme, sink, true) { + StateUpdate none; + none.id = block.id; + none.available = false; + this->draw_(none); + } + + protected: + void render_(const StateUpdate &u) override { + this->available_ = u.available; + if (u.available) + this->dimmable_ = u.brightness.has_value(); + this->apply_mode_(); + this->set_disabled_(!u.available); + if (!u.available) { + if (!this->dimmable_) + this->style_toggle_(false); + lv_label_set_text(this->value_label_, DASH); + lv_label_set_text(this->sub_label_, "Unavailable"); + lv_obj_remove_flag(this->sub_label_, LV_OBJ_FLAG_HIDDEN); + lv_arc_set_value(this->arc_, 0); + return; + } + lv_obj_add_flag(this->sub_label_, LV_OBJ_FLAG_HIDDEN); + if (this->dimmable_) { + int b = *u.brightness; + b = b < 0 ? 0 : (b > 100 ? 100 : b); + bool on = u.on.value_or(b > 0) && b > 0; + this->on_ = on; + if (b > 0) + this->last_brightness_ = b; + lv_arc_set_value(this->arc_, on ? b : 0); + this->show_percent_(on ? b : 0); + } else { + this->on_ = u.on.value_or(false); + this->style_toggle_(this->on_); + } + } + + void on_arc_changed_(int value) override { this->show_percent_(value); } + void on_arc_released_(int value) override { this->sink_.on_control(this->id_, "", "set", (float) value); } + // Local feedback right away; the hold only defers incoming states. + void on_centre_tap_() override { + this->sink_.on_control(this->id_, "", "toggle", 0); + this->on_ = !this->on_; + if (this->dimmable_) { + int b = this->on_ ? (this->last_brightness_ > 0 ? this->last_brightness_ : 100) : 0; + lv_arc_set_value(this->arc_, b); + this->show_percent_(b); + } else { + this->style_toggle_(this->on_); + } + this->layout_centre_(); + } + + void show_percent_(int value) { + if (value <= 0) { + lv_label_set_text(this->value_label_, "Off"); + return; + } + char buf[16]; + std::snprintf(buf, sizeof buf, "%d%%", value); + lv_label_set_text(this->value_label_, buf); + } + + // Dimmable: transparent 290 px centre and visible arc. On/off-only: filled 220 px button, no arc. + void apply_mode_() { + if (this->dimmable_) { + lv_obj_remove_flag(this->arc_, LV_OBJ_FLAG_HIDDEN); + lv_obj_set_size(this->centre_, 290, 290); + lv_obj_set_style_bg_opa(this->centre_, LV_OPA_TRANSP, 0); + lv_obj_set_style_text_color(this->value_label_, lv_color_hex(this->fg_), 0); + lv_obj_set_style_text_color(this->sub_label_, lv_color_hex(this->fg_), 0); + } else { + lv_obj_add_flag(this->arc_, LV_OBJ_FLAG_HIDDEN); + lv_obj_set_size(this->centre_, 220, 220); + } + } + + void style_toggle_(bool on) { + lv_obj_set_style_bg_color(this->centre_, lv_color_hex(this->fg_), 0); + lv_obj_set_style_bg_opa(this->centre_, on ? LV_OPA_COVER : LV_OPA_20, 0); + uint32_t label_color = on ? this->bg_ : this->fg_; + lv_obj_set_style_text_color(this->value_label_, lv_color_hex(label_color), 0); + lv_obj_set_style_text_color(this->sub_label_, lv_color_hex(label_color), 0); + lv_label_set_text(this->value_label_, on ? "On" : "Off"); + } + + bool dimmable_{true}; + bool on_{false}; + int last_brightness_{0}; +}; + +} // namespace + +std::unique_ptr make_light_view(lv_obj_t *parent, const Block &block, const Theme &theme, + ControlSink &sink) { + return std::make_unique(parent, block, theme, sink); +} + +} // namespace ha_controller +} // namespace esphome diff --git a/esphome/components/ha_controller/pager.cpp b/esphome/components/ha_controller/pager.cpp new file mode 100644 index 0000000..16fe211 --- /dev/null +++ b/esphome/components/ha_controller/pager.cpp @@ -0,0 +1,269 @@ +#include "pager.h" + +// Needed for the lv_hit_test_info_t body (LV_EVENT_HIT_TEST); relies on the pinned LVGL 9.5 layout. +#include + +namespace esphome { +namespace ha_controller { + +namespace { +struct HintSpec { + int start; + int end; + Edge edge; +}; +constexpr HintSpec HINTS[4] = { + {350, 10, Edge::RIGHT}, + {80, 100, Edge::BOTTOM}, + {170, 190, Edge::LEFT}, + {260, 280, Edge::TOP}, +}; +constexpr int HINT_SIZE = 458; +} // namespace + +void Pager::attach(lv_obj_t *screen, int size, int edge_width) { + this->size_ = size; + this->edge_width_ = edge_width; + SwipeConfig cfg; + cfg.size = size; + this->tracker_ = SwipeTracker(cfg); + + this->viewport_ = lv_obj_create(screen); + lv_obj_remove_style_all(this->viewport_); + lv_obj_set_size(this->viewport_, size, size); + lv_obj_set_pos(this->viewport_, 0, 0); + lv_obj_remove_flag(this->viewport_, LV_OBJ_FLAG_SCROLLABLE); + lv_obj_remove_flag(this->viewport_, LV_OBJ_FLAG_CLICKABLE); + + for (int i = 0; i < 4; i++) { + lv_obj_t *arc = lv_arc_create(lv_layer_top()); + lv_obj_remove_style_all(arc); + lv_obj_set_size(arc, HINT_SIZE, HINT_SIZE); + lv_obj_align(arc, LV_ALIGN_CENTER, 0, 0); + lv_obj_remove_flag(arc, LV_OBJ_FLAG_CLICKABLE); + lv_obj_remove_flag(arc, LV_OBJ_FLAG_SCROLLABLE); + lv_arc_set_rotation(arc, 0); + lv_arc_set_bg_angles(arc, HINTS[i].start, HINTS[i].end); + lv_obj_set_style_arc_width(arc, 6, LV_PART_MAIN); + lv_obj_set_style_arc_color(arc, lv_color_white(), LV_PART_MAIN); + lv_obj_set_style_arc_opa(arc, LV_OPA_60, LV_PART_MAIN); + lv_obj_set_style_arc_opa(arc, LV_OPA_TRANSP, LV_PART_INDICATOR); + lv_obj_set_style_bg_opa(arc, LV_OPA_TRANSP, LV_PART_KNOB); + lv_obj_add_flag(arc, LV_OBJ_FLAG_HIDDEN); + this->hints_[i] = arc; + } + + this->edge_ = lv_obj_create(lv_layer_top()); + lv_obj_remove_style_all(this->edge_); + lv_obj_set_size(this->edge_, size, size); + lv_obj_set_pos(this->edge_, 0, 0); + lv_obj_remove_flag(this->edge_, LV_OBJ_FLAG_SCROLLABLE); + lv_obj_add_flag(this->edge_, LV_OBJ_FLAG_CLICKABLE); + lv_obj_add_flag(this->edge_, LV_OBJ_FLAG_ADV_HITTEST); + lv_obj_add_event_cb(this->edge_, Pager::on_edge_event_, LV_EVENT_ALL, this); +} + +void Pager::on_edge_event_(lv_event_t *e) { + auto *self = static_cast(lv_event_get_user_data(e)); + if (lv_event_get_code(e) == LV_EVENT_DELETE) + return; + switch (lv_event_get_code(e)) { + case LV_EVENT_HIT_TEST: { + lv_hit_test_info_t *info = lv_event_get_hit_test_info(e); + info->res = classify_edge(info->point->x, info->point->y, self->size_, self->edge_width_) != Edge::NONE; + break; + } + case LV_EVENT_PRESSED: + self->on_pressed_(); + break; + case LV_EVENT_PRESSING: + self->on_pressing_(); + break; + case LV_EVENT_RELEASED: + case LV_EVENT_PRESS_LOST: + self->on_released_(); + break; + default: + break; + } +} + +const PageRef *Pager::page_at_(int x, int y) const { + for (const auto &p : this->pages_) { + if (p.x == x && p.y == y) + return &p; + } + return nullptr; +} + +const PageRef *Pager::current_page_() const { + return this->current_idx_ >= 0 ? &this->pages_[this->current_idx_] : nullptr; +} + +void Pager::on_pressed_() { + if (!this->enabled_ || this->animating_) + return; + // A fresh press while a swipe is still tracked means the release was lost: drop the stale swipe. + if (this->tracker_.active()) + this->abort_swipe_(); + const PageRef *cur = this->current_page_(); + lv_indev_t *indev = lv_indev_active(); + if (cur == nullptr || indev == nullptr) + return; + lv_point_t p; + lv_indev_get_point(indev, &p); + Edge edge = classify_edge(p.x, p.y, this->size_, this->edge_width_); + if (edge == Edge::NONE) + return; + GridStep step = step_for(edge); + const PageRef *target = this->page_at_(cur->x + step.dx, cur->y + step.dy); + this->dx_ = step.dx; + this->dy_ = step.dy; + this->target_idx_ = target != nullptr ? static_cast(target - this->pages_.data()) : -1; + this->tracker_.begin(edge, target != nullptr, p.x, p.y, lv_tick_get()); + if (target != nullptr) + lv_obj_remove_flag(target->obj, LV_OBJ_FLAG_HIDDEN); + this->place_(0); +} + +void Pager::on_pressing_() { + if (!this->tracker_.active()) + return; + lv_indev_t *indev = lv_indev_active(); + if (indev == nullptr) + return; + lv_point_t p; + lv_indev_get_point(indev, &p); + this->place_(this->tracker_.update(p.x, p.y, lv_tick_get())); +} + +void Pager::on_released_() { + if (!this->tracker_.active()) + return; + int offset = this->tracker_.progress(); + bool commit = this->tracker_.release(lv_tick_get()) && this->target_idx_ >= 0; + this->place_(offset); + int remaining = commit ? this->size_ - offset : offset; + if (remaining <= 0) { + this->finish_(commit); + return; + } + this->animating_ = true; + this->anim_commit_ = commit; + lv_anim_t a; + lv_anim_init(&a); + lv_anim_set_var(&a, this); + lv_anim_set_exec_cb(&a, Pager::anim_exec_); + lv_anim_set_values(&a, offset, commit ? this->size_ : 0); + lv_anim_set_duration(&a, settle_duration_ms(remaining, this->size_)); + lv_anim_set_path_cb(&a, lv_anim_path_ease_out); + lv_anim_set_completed_cb(&a, Pager::anim_done_); + lv_anim_start(&a); +} + +void Pager::anim_exec_(void *var, int32_t value) { static_cast(var)->place_(value); } + +void Pager::anim_done_(lv_anim_t *a) { + auto *self = static_cast(a->var); + self->finish_(self->anim_commit_); +} + +void Pager::place_(int offset) { + const PageRef *cur = this->current_page_(); + if (cur != nullptr) + lv_obj_set_pos(cur->obj, -this->dx_ * offset, -this->dy_ * offset); + if (this->target_idx_ >= 0) { + const PageRef &t = this->pages_[this->target_idx_]; + lv_obj_set_pos(t.obj, this->dx_ * (this->size_ - offset), this->dy_ * (this->size_ - offset)); + } +} + +void Pager::finish_(bool commit) { + this->animating_ = false; + const PageRef *cur = this->current_page_(); + if (commit && this->target_idx_ >= 0) { + if (cur != nullptr) + lv_obj_add_flag(cur->obj, LV_OBJ_FLAG_HIDDEN); + this->current_idx_ = this->target_idx_; + this->current_id_ = this->pages_[this->current_idx_].id; + } else if (this->target_idx_ >= 0) { + lv_obj_add_flag(this->pages_[this->target_idx_].obj, LV_OBJ_FLAG_HIDDEN); + } + this->target_idx_ = -1; + this->dx_ = 0; + this->dy_ = 0; + cur = this->current_page_(); + if (cur != nullptr) + lv_obj_set_pos(cur->obj, 0, 0); + this->refresh_hints_(); +} + +// Stops any swipe or animation and puts the current page back in place. +void Pager::abort_swipe_() { + lv_anim_delete(this, Pager::anim_exec_); + this->tracker_.reset(); + if (this->target_idx_ >= 0 && this->target_idx_ < static_cast(this->pages_.size())) + lv_obj_add_flag(this->pages_[this->target_idx_].obj, LV_OBJ_FLAG_HIDDEN); + this->finish_(false); +} + +void Pager::set_pages(std::vector pages, const std::string &show_id) { + // Cancel first: the old page objects may already be gone and are never touched again. + lv_anim_delete(this, Pager::anim_exec_); + this->tracker_.reset(); + this->animating_ = false; + this->target_idx_ = -1; + this->dx_ = 0; + this->dy_ = 0; + this->current_idx_ = -1; + this->pages_ = std::move(pages); + this->current_id_.clear(); + for (size_t i = 0; i < this->pages_.size(); i++) { + lv_obj_add_flag(this->pages_[i].obj, LV_OBJ_FLAG_HIDDEN); + lv_obj_set_pos(this->pages_[i].obj, 0, 0); + if (this->pages_[i].id == show_id) + this->current_idx_ = static_cast(i); + } + if (this->current_idx_ < 0 && !this->pages_.empty()) + this->current_idx_ = 0; + if (this->current_idx_ >= 0) { + lv_obj_remove_flag(this->pages_[this->current_idx_].obj, LV_OBJ_FLAG_HIDDEN); + this->current_id_ = this->pages_[this->current_idx_].id; + } + this->refresh_hints_(); +} + +void Pager::set_enabled(bool enabled) { + if (this->enabled_ == enabled) + return; + this->enabled_ = enabled; + if (!enabled) + this->abort_swipe_(); + if (this->edge_ != nullptr) { + if (enabled) + lv_obj_remove_flag(this->edge_, LV_OBJ_FLAG_HIDDEN); + else + lv_obj_add_flag(this->edge_, LV_OBJ_FLAG_HIDDEN); + } + this->refresh_hints_(); +} + +void Pager::refresh_hints_() { + const PageRef *cur = this->current_page_(); + for (int i = 0; i < 4; i++) { + if (this->hints_[i] == nullptr) + continue; + bool show = false; + if (this->enabled_ && cur != nullptr) { + GridStep s = step_for(HINTS[i].edge); + show = this->page_at_(cur->x + s.dx, cur->y + s.dy) != nullptr; + } + if (show) + lv_obj_remove_flag(this->hints_[i], LV_OBJ_FLAG_HIDDEN); + else + lv_obj_add_flag(this->hints_[i], LV_OBJ_FLAG_HIDDEN); + } +} + +} // namespace ha_controller +} // namespace esphome diff --git a/esphome/components/ha_controller/pager.h b/esphome/components/ha_controller/pager.h new file mode 100644 index 0000000..52df424 --- /dev/null +++ b/esphome/components/ha_controller/pager.h @@ -0,0 +1,64 @@ +#pragma once +#include + +#include +#include + +#include "gesture.h" + +namespace esphome { +namespace ha_controller { + +struct PageRef { + std::string id; + int x; + int y; + lv_obj_t *obj; +}; + +// Edge-swipe navigation between pages placed on a grid (spec 5.1-5.4). Every method runs on the main loop. +class Pager { + public: + // Creates the viewport (under `screen`), the edge overlay and the four hint arcs (on lv_layer_top()). + void attach(lv_obj_t *screen, int size, int edge_width); + lv_obj_t *viewport() const { return this->viewport_; } + // Replaces the pages. Cancels animations, resets the tracker and shows one page (show_id, else the first). + void set_pages(std::vector pages, const std::string &show_id); + // False while a message is shown: swipes and hints are off. + void set_enabled(bool enabled); + const std::string ¤t_id() const { return this->current_id_; } + + protected: + static void on_edge_event_(lv_event_t *e); + static void anim_exec_(void *var, int32_t value); + static void anim_done_(lv_anim_t *a); + + void on_pressed_(); + void on_pressing_(); + void on_released_(); + const PageRef *page_at_(int x, int y) const; + const PageRef *current_page_() const; + void place_(int offset); + void finish_(bool commit); + void abort_swipe_(); + void refresh_hints_(); + + lv_obj_t *viewport_{nullptr}; + lv_obj_t *edge_{nullptr}; + lv_obj_t *hints_[4]{}; // RIGHT, BOTTOM, LEFT, TOP + int size_{466}; + int edge_width_{36}; + bool enabled_{true}; + bool animating_{false}; + bool anim_commit_{false}; + int dx_{0}; + int dy_{0}; + std::vector pages_; + std::string current_id_; + int current_idx_{-1}; + int target_idx_{-1}; + SwipeTracker tracker_; +}; + +} // namespace ha_controller +} // namespace esphome diff --git a/esphome/components/ha_controller/sleep.h b/esphome/components/ha_controller/sleep.h new file mode 100644 index 0000000..9f6c331 --- /dev/null +++ b/esphome/components/ha_controller/sleep.h @@ -0,0 +1,18 @@ +#pragma once +#include + +namespace esphome { +namespace ha_controller { + +// Inactivity delay used until the first layout arrives. +constexpr uint32_t DEFAULT_SLEEP_S = 20; + +// True when the screen must sleep. A timeout of 0 means never. +inline bool should_sleep(uint32_t inactive_ms, uint32_t timeout_s) { + if (timeout_s == 0) + return false; + return (uint64_t) inactive_ms >= (uint64_t) timeout_s * 1000u; +} + +} // namespace ha_controller +} // namespace esphome diff --git a/esphome/components/ha_controller/stack.h b/esphome/components/ha_controller/stack.h new file mode 100644 index 0000000..72a3fe1 --- /dev/null +++ b/esphome/components/ha_controller/stack.h @@ -0,0 +1,75 @@ +#pragma once +// Pure geometry for the custom block: vertical stack of items kept inside the safe circles. +#include +#include +#include + +namespace esphome { +namespace ha_controller { + +struct StackItem { + int height; + int half_width; + bool interactive; // must stay inside the control radius; other items only inside the visible circle +}; + +struct StackLayout { + std::vector top; // top edge of each item, relative to the screen centre + int gap{0}; + bool fits{false}; +}; + +// Half of the chord of a circle of `radius` at horizontal half extent `half_width`. +inline int chord_limit(int radius, int half_width) { + double v = (double) radius * radius - (double) half_width * half_width; + return v > 0 ? (int) std::floor(std::sqrt(v)) : 0; +} + +// Centres the stack. If an item leaves its circle, the gap shrinks 8 -> 4 -> 0 px; if it still does not fit, +// the whole stack shifts as little as possible. `fits` is false when no shift can satisfy every item. +inline StackLayout layout_stack(const std::vector &items, int control_radius = 185, + int visible_radius = 233) { + StackLayout out; + const int n = (int) items.size(); + out.top.assign(n, 0); + if (n == 0) { + out.fits = true; + return out; + } + int sum = 0; + for (const auto &it : items) + sum += it.height; + const int gaps[3] = {8, 4, 0}; + int lo = 0, hi = 0; + for (int gi = 0; gi < 3; gi++) { + int gap = gaps[gi]; + int y = -(sum + gap * (n - 1)) / 2; + lo = -100000; + hi = 100000; + for (int i = 0; i < n; i++) { + out.top[i] = y; + int lim = chord_limit(items[i].interactive ? control_radius : visible_radius, items[i].half_width); + lo = std::max(lo, -lim - y); + hi = std::min(hi, lim - (y + items[i].height)); + y += items[i].height + gap; + } + out.gap = gap; + if (lo <= 0 && hi >= 0) { + out.fits = true; + return out; + } + } + int shift = 0; + if (lo <= hi) { + shift = lo > 0 ? lo : (hi < 0 ? hi : 0); + out.fits = true; + } else { + shift = (lo + hi) / 2; + } + for (auto &t : out.top) + t += shift; + return out; +} + +} // namespace ha_controller +} // namespace esphome diff --git a/esphome/components/ha_controller/states.cpp b/esphome/components/ha_controller/states.cpp new file mode 100644 index 0000000..5381a33 --- /dev/null +++ b/esphome/components/ha_controller/states.cpp @@ -0,0 +1,48 @@ +#include "states.h" + +#include + +namespace esphome { +namespace ha_controller { + +bool parse_states(const std::string &json, std::vector &out) { + JsonDocument doc; + if (deserializeJson(doc, json)) + return false; + if (!doc.is()) + return false; + out.clear(); + for (JsonVariant el : doc.as()) { + if (!el["id"].is()) + continue; + StateUpdate u; + u.id = el["id"].as(); + if (el["available"].is()) + u.available = el["available"].as(); + if (el["on"].is()) + u.on = el["on"].as(); + if (el["brightness"].is()) + u.brightness = el["brightness"].as(); + if (el["target"].is()) + u.target = el["target"].as(); + if (el["min"].is()) + u.min = el["min"].as(); + if (el["max"].is()) + u.max = el["max"].as(); + if (el["step"].is()) + u.step = el["step"].as(); + if (el["unit"].is()) + u.unit = el["unit"].as(); + if (el["current"].is()) + u.current = el["current"].as(); + if (el["action"].is()) + u.action = el["action"].as(); + if (el["text"].is()) + u.text = el["text"].as(); + out.push_back(std::move(u)); + } + return true; +} + +} // namespace ha_controller +} // namespace esphome diff --git a/esphome/components/ha_controller/states.h b/esphome/components/ha_controller/states.h new file mode 100644 index 0000000..2970c32 --- /dev/null +++ b/esphome/components/ha_controller/states.h @@ -0,0 +1,24 @@ +#pragma once +#include +#include +#include + +namespace esphome { +namespace ha_controller { + +struct StateUpdate { + std::string id; + bool available{true}; + std::optional on; + std::optional brightness; // light; nullopt = on/off only + std::optional target; // climate + float min{7}, max{35}, step{0.5f}; + std::string unit, current, action; // climate + std::optional text; // entity item +}; + +// False on bad JSON or when the root is not an array. Elements without a string id are skipped. +bool parse_states(const std::string &json, std::vector &out); + +} // namespace ha_controller +} // namespace esphome diff --git a/esphome/components/ha_controller/views.h b/esphome/components/ha_controller/views.h new file mode 100644 index 0000000..d5df777 --- /dev/null +++ b/esphome/components/ha_controller/views.h @@ -0,0 +1,88 @@ +#pragma once +// Internal to the component: shared pieces of the block views (widgets.cpp builds them). +#include "color.h" +#include "hold.h" +#include "knob.h" +#include "widgets.h" + +namespace esphome { +namespace ha_controller { + +// Interactive controls stay inside this radius so they never touch the edge ring (spec 5.5). +constexpr int CONTROL_RADIUS = 185; +constexpr int KNOB_DIAMETER = 370; +constexpr int KNOB_WIDTH = 28; +constexpr int NAME_TOP = 96; + +inline int font_index(FontSize f) { return static_cast(f); } + +// Full-screen page filled with the block background. +inline lv_obj_t *make_page_root(lv_obj_t *parent, const Block &block, const Theme &theme) { + lv_obj_t *root = lv_obj_create(parent); + lv_obj_remove_style_all(root); + lv_obj_set_size(root, theme.size, theme.size); + lv_obj_set_pos(root, 0, 0); + lv_obj_remove_flag(root, LV_OBJ_FLAG_SCROLLABLE); + lv_obj_set_style_bg_opa(root, LV_OPA_COVER, 0); + lv_obj_set_style_bg_color(root, lv_color_hex(block.bg), 0); + return root; +} + +inline lv_obj_t *make_label(lv_obj_t *parent, const lv_font_t *font, uint32_t color, const char *text) { + lv_obj_t *label = lv_label_create(parent); + lv_obj_set_style_text_font(label, font, 0); + lv_obj_set_style_text_color(label, lv_color_hex(color), 0); + lv_obj_set_style_text_align(label, LV_TEXT_ALIGN_CENTER, 0); + lv_label_set_text(label, text); + return label; +} + +// Places `left` and `right` side by side inside `row`, vertically centred, and sizes the row to fit. +void layout_row(lv_obj_t *row, lv_obj_t *left, lv_obj_t *right, int gap); + +// Shared part of the light and climate pages: name, 270 degree arc knob, centre value and a small label. +// Subclasses decide what the arc means and how an update is drawn. +class KnobBlockView : public BlockView { + public: + void apply(const StateUpdate &u, uint32_t now_ms) override; + void loop(uint32_t now_ms) override; + + protected: + KnobBlockView(lv_obj_t *parent, const Block &block, const Theme &theme, ControlSink &sink, bool tappable_centre); + + virtual void render_(const StateUpdate &u) = 0; + virtual void on_arc_changed_(int value) = 0; // drag in progress: update the centre label only + virtual void on_arc_released_(int value) = 0; // drag finished: send the value + virtual void on_centre_tap_() {} + + void touch_(); + void set_disabled_(bool disabled); + // Renders an update, then re-centres the value and sub labels (no flex layout in this LVGL build). + void draw_(const StateUpdate &u); + void layout_centre_(); + + static void arc_event_(lv_event_t *e); + static void centre_event_(lv_event_t *e); + + ControlSink &sink_; + const Theme &theme_; + uint32_t fg_; // text colour for the block background + uint32_t bg_; + InteractionHold hold_; + bool has_pending_{false}; + StateUpdate pending_; + bool available_{false}; + lv_obj_t *arc_{nullptr}; + lv_obj_t *centre_{nullptr}; + lv_obj_t *value_label_{nullptr}; + lv_obj_t *sub_label_{nullptr}; +}; + +std::unique_ptr make_light_view(lv_obj_t *parent, const Block &block, const Theme &theme, ControlSink &sink); +std::unique_ptr make_climate_view(lv_obj_t *parent, const Block &block, const Theme &theme, + ControlSink &sink); +std::unique_ptr make_custom_view(lv_obj_t *parent, const Block &block, const Theme &theme, + const LocalSources &local); + +} // namespace ha_controller +} // namespace esphome diff --git a/esphome/components/ha_controller/widgets.cpp b/esphome/components/ha_controller/widgets.cpp new file mode 100644 index 0000000..843eed2 --- /dev/null +++ b/esphome/components/ha_controller/widgets.cpp @@ -0,0 +1,32 @@ +#include "widgets.h" + +#include "views.h" + +namespace esphome { +namespace ha_controller { + +BlockView::~BlockView() { + if (this->root_ != nullptr) + lv_obj_delete(this->root_); +} + +bool BlockView::owns(const std::string &id) const { return id == this->id_; } +void BlockView::apply(const StateUpdate &, uint32_t) {} +void BlockView::on_local_update() {} +void BlockView::loop(uint32_t) {} + +std::unique_ptr make_block_view(lv_obj_t *parent, const Block &block, const Theme &theme, ControlSink &sink, + const LocalSources &local) { + switch (block.widget) { + case Widget::LIGHT: + return make_light_view(parent, block, theme, sink); + case Widget::CLIMATE: + return make_climate_view(parent, block, theme, sink); + case Widget::CUSTOM: + break; + } + return make_custom_view(parent, block, theme, local); +} + +} // namespace ha_controller +} // namespace esphome diff --git a/esphome/components/ha_controller/widgets.h b/esphome/components/ha_controller/widgets.h new file mode 100644 index 0000000..9cfabb6 --- /dev/null +++ b/esphome/components/ha_controller/widgets.h @@ -0,0 +1,60 @@ +#pragma once +#include + +#include +#include + +#include "esphome/components/binary_sensor/binary_sensor.h" +#include "esphome/components/number/number.h" +#include "esphome/components/sensor/sensor.h" + +#include "layout.h" +#include "states.h" + +namespace esphome { +namespace ha_controller { + +// Receives the control events of the views (knob, toggle). Implemented by HaController. +class ControlSink { + public: + virtual ~ControlSink() = default; + virtual void on_control(const std::string &block, const std::string &item, const char *op, float value) = 0; +}; + +struct Theme { + const lv_font_t *text[4]; + const lv_font_t *value[4]; + const lv_font_t *emoji[4]; + int size; + int edge_width; +}; + +struct LocalSources { + sensor::Sensor *battery{}; + binary_sensor::BinarySensor *charging{}; + number::Number *brightness{}; +}; + +// One full-screen view per block. Every method runs on the ESPHome main loop. +class BlockView { + public: + virtual ~BlockView(); + lv_obj_t *root() const { return this->root_; } + const std::string &id() const { return this->id_; } + // True when a state update with this id belongs to the view (the block or one of its items). + virtual bool owns(const std::string &id) const; + virtual void apply(const StateUpdate &u, uint32_t now_ms); + // Battery, charging or brightness changed. + virtual void on_local_update(); + virtual void loop(uint32_t now_ms); + + protected: + lv_obj_t *root_{nullptr}; + std::string id_; +}; + +std::unique_ptr make_block_view(lv_obj_t *parent, const Block &block, const Theme &theme, ControlSink &sink, + const LocalSources &local); + +} // namespace ha_controller +} // namespace esphome diff --git a/esphome/ha-controller.yaml b/esphome/ha-controller.yaml new file mode 100644 index 0000000..0524b2d --- /dev/null +++ b/esphome/ha-controller.yaml @@ -0,0 +1,49 @@ +substitutions: + name: ha-controller + friendly_name: HA Controller + +packages: + version: !include version.yaml + board: !include packages/board-waveshare-amoled-175.yaml + ui: !include packages/ui.yaml + +esphome: + name: ${name} + friendly_name: ${friendly_name} + name_add_mac_suffix: true + min_version: 2026.10.0 + project: + name: pyxel-dev.ha-controller + version: ${project_version} + +logger: +http_request: + verify_ssl: true +api: + actions: + - action: install_firmware + variables: {url: string, md5_url: string} + then: + - lambda: |- + id(ui).show_message("Updating firmware…", "Do not unplug the screen"); + - ota.http_request.flash: + url: !lambda return url; + md5_url: !lambda return md5_url; + - lambda: |- + id(ui).show_message("Update failed", "Check the screen's internet access"); + - delay: 5s + - lambda: id(ui).hide_message(); +ota: + - platform: esphome + - platform: http_request + +wifi: + ap: + ssid: HA Controller +captive_portal: +improv_serial: + +external_components: + - source: + type: local + path: components diff --git a/esphome/packages/board-waveshare-amoled-175.yaml b/esphome/packages/board-waveshare-amoled-175.yaml new file mode 100644 index 0000000..db1cbd9 --- /dev/null +++ b/esphome/packages/board-waveshare-amoled-175.yaml @@ -0,0 +1,80 @@ +esphome: + platformio_options: + board_build.flash_mode: dio + board_build.f_flash: 80000000L + board_build.f_cpu: 240000000L +esp32: + variant: esp32s3 + flash_size: 16MB + framework: + type: esp-idf +psram: + mode: octal + speed: 80MHz +external_components: + - source: + type: git + url: https://github.com/shelson/esphome-cst9217 + ref: ab90a2289824240b01d1d69d8d08a1d06e6b1cb3 + components: [cst9217] +i2c: + - id: bus_a + sda: GPIO15 + scl: GPIO14 + frequency: 400kHz +spi: + - id: display_qspi + type: quad + clk_pin: GPIO38 + data_pins: [GPIO4, GPIO5, GPIO6, GPIO7] +display: + - platform: mipi_spi + id: amoled + model: CO5300 + bus_mode: quad + reset_pin: GPIO39 + cs_pin: GPIO12 + dimensions: {width: 466, height: 466} + auto_clear_enabled: false + update_interval: never +touchscreen: + - platform: cst9217 + id: touch + display: amoled + interrupt_pin: GPIO11 + reset_pin: GPIO40 + transform: {mirror_x: true, mirror_y: true} + on_touch: + - logger.log: {level: DEBUG, format: "touch x=%d y=%d", args: [touch.x, touch.y]} +axp2101_battery: + i2c_id: bus_a + battery_level: {id: battery_level, name: Battery} + battery_voltage: {name: Battery voltage} + charging: {id: battery_charging, name: Charging} +number: + - platform: template + id: screen_brightness + name: Screen brightness + icon: mdi:brightness-6 + entity_category: config + unit_of_measurement: "%" + min_value: 5 + max_value: 100 + step: 1 + initial_value: 80 + restore_value: true + optimistic: true + on_value: + - if: + condition: + lambda: return !id(ui).is_sleeping(); + then: + - script.execute: screen_on + +script: + - id: screen_on + then: + - lambda: id(amoled).set_brightness((uint8_t) lroundf(id(screen_brightness).state * 2.55f)); + - id: screen_off + then: + - lambda: id(amoled).set_brightness(0); diff --git a/esphome/packages/ui.yaml b/esphome/packages/ui.yaml new file mode 100644 index 0000000..fb9c9dc --- /dev/null +++ b/esphome/packages/ui.yaml @@ -0,0 +1,167 @@ +font: + - id: font_s + file: {type: gfonts, family: Inter, weight: 600} + size: 20 + bpp: 4 + glyphsets: [GF_Latin_Core] + - id: font_m + file: {type: gfonts, family: Inter, weight: 600} + size: 28 + bpp: 4 + glyphsets: [GF_Latin_Core] + - id: font_l + file: {type: gfonts, family: Inter, weight: 600} + size: 40 + bpp: 4 + glyphsets: [GF_Latin_Core] + - id: font_xl + file: {type: gfonts, family: Inter, weight: 600} + size: 56 + bpp: 4 + glyphsets: [GF_Latin_Core] + - id: value_s + file: {type: gfonts, family: Inter, weight: 600} + size: 40 + bpp: 4 + glyphs: " 0123456789.,-+%°CFOfn—" + - id: value_m + file: {type: gfonts, family: Inter, weight: 600} + size: 56 + bpp: 4 + glyphs: " 0123456789.,-+%°CFOfn—" + - id: value_l + file: {type: gfonts, family: Inter, weight: 600} + size: 72 + bpp: 4 + glyphs: " 0123456789.,-+%°CFOfn—" + - id: value_xl + file: {type: gfonts, family: Inter, weight: 600} + size: 96 + bpp: 4 + glyphs: " 0123456789.,-+%°CFOfn—" + - id: emoji_s + file: {type: gfonts, family: Noto Emoji} + size: 32 + bpp: 4 + glyphs: !include ../../custom_components/ha_controller/emoji.json + - id: emoji_m + file: {type: gfonts, family: Noto Emoji} + size: 48 + bpp: 4 + glyphs: !include ../../custom_components/ha_controller/emoji.json + - id: emoji_l + file: {type: gfonts, family: Noto Emoji} + size: 64 + bpp: 4 + glyphs: !include ../../custom_components/ha_controller/emoji.json + - id: emoji_xl + file: {type: gfonts, family: Noto Emoji} + size: 88 + bpp: 4 + glyphs: !include ../../custom_components/ha_controller/emoji.json +lvgl: + displays: [amoled] + touchscreens: [touch] + buffer_size: 25% + bg_color: 0x000000 + pages: + - id: boot_page + widgets: + - label: + align: center + y: -40 + text: HA Controller + text_font: font_m + text_color: 0xFFFFFF + - label: + align: center + y: 10 + text: v${project_version} + text_font: font_s + text_color: 0x9CA3AF + - label: + align: center + y: 70 + text: "💡" + text_font: emoji_m + text_color: 0xFFFFFF + - arc: + id: keep_arc + hidden: true + - slider: + id: keep_slider + hidden: true + +ha_controller: + id: ui + size: 466 + edge_width: 36 + text_fonts: {s: font_s, m: font_m, l: font_l, xl: font_xl} + value_fonts: {s: value_s, m: value_m, l: value_l, xl: value_xl} + emoji_fonts: {s: emoji_s, m: emoji_m, l: emoji_l, xl: emoji_xl} + battery_level: battery_level + battery_charging: battery_charging + screen_brightness: screen_brightness + touchscreen: touch + on_sleep: + - script.execute: screen_off + - lvgl.pause + on_wake: + - lvgl.resume + - lvgl.widget.redraw + - script.execute: screen_on + on_control: + - homeassistant.event: + event: esphome.ha_controller_control + data: + block: !lambda 'return block;' + item: !lambda 'return item;' + op: !lambda 'return op;' + value: !lambda 'return str_sprintf("%.2f", value);' + +api: + on_client_connected: + - delay: 5s + - script.execute: + id: send_hello + reason: connected + actions: + - action: set_layout + variables: + layout: string + then: + - lambda: id(ui).set_layout(layout); + - script.execute: + id: send_hello + reason: applied + - action: set_states + variables: + states: string + then: + - lambda: id(ui).set_states(states); + +script: + - id: send_hello + mode: queued + parameters: + reason: string + then: + - homeassistant.event: + event: esphome.ha_controller_hello + data: + node: !lambda 'return App.get_name();' + version: ${project_version} + protocol: "1" + revision: !lambda 'return id(ui).get_revision();' + reason: !lambda 'return reason;' + +interval: + - interval: 60s + then: + - if: + condition: + api.connected: + then: + - script.execute: + id: send_hello + reason: heartbeat diff --git a/esphome/requirements.txt b/esphome/requirements.txt new file mode 100644 index 0000000..aff0e93 --- /dev/null +++ b/esphome/requirements.txt @@ -0,0 +1 @@ +esphome==2026.10.2 diff --git a/esphome/simulator.yaml b/esphome/simulator.yaml new file mode 100644 index 0000000..f31a4d1 --- /dev/null +++ b/esphome/simulator.yaml @@ -0,0 +1,66 @@ +packages: + version: !include version.yaml + ui: !include packages/ui.yaml + +esphome: + name: ha-controller-sim + friendly_name: HA Controller Simulator + project: + name: pyxel-dev.ha-controller + version: ${project_version} + +host: +logger: +api: + +external_components: + - source: + type: local + path: components + +display: + - platform: sdl + id: amoled + dimensions: + width: 466 + height: 466 + auto_clear_enabled: false + update_interval: never + +touchscreen: + - platform: sdl + id: touch + display: amoled + +sensor: + - platform: template + id: battery_level + name: Battery + update_interval: 5s + unit_of_measurement: "%" + lambda: return 76.0; + +binary_sensor: + - platform: template + id: battery_charging + name: Charging + lambda: return false; + +number: + - platform: template + id: screen_brightness + name: Screen brightness + unit_of_measurement: "%" + min_value: 5 + max_value: 100 + step: 1 + initial_value: 80 + optimistic: true + +script: + - id: screen_on + then: + - logger.log: screen_on + - id: screen_off + then: + - logger.log: screen_off diff --git a/esphome/tests/CMakeLists.txt b/esphome/tests/CMakeLists.txt new file mode 100644 index 0000000..ec61444 --- /dev/null +++ b/esphome/tests/CMakeLists.txt @@ -0,0 +1,33 @@ +cmake_minimum_required(VERSION 3.20) +project(ha_controller_host_tests CXX) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + +include(FetchContent) +FetchContent_Declare(doctest + GIT_REPOSITORY https://github.com/doctest/doctest.git + GIT_TAG v2.4.12) +FetchContent_Declare(ArduinoJson + GIT_REPOSITORY https://github.com/bblanchon/ArduinoJson.git + GIT_TAG v7.4.2) +FetchContent_MakeAvailable(doctest ArduinoJson) + +set(COMPONENT_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../components/ha_controller) + +file(GLOB TEST_SOURCES CONFIGURE_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test_*.cpp) +set(PURE_SOURCES + ${COMPONENT_DIR}/gesture.cpp + ${COMPONENT_DIR}/layout.cpp + ${COMPONENT_DIR}/states.cpp) + +add_executable(unit_tests ${TEST_SOURCES} ${PURE_SOURCES}) +target_include_directories(unit_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../components) +target_compile_definitions(unit_tests PRIVATE + FIXTURES_DIR="${CMAKE_CURRENT_SOURCE_DIR}/../../docs/protocol/fixtures") +target_compile_options(unit_tests PRIVATE -Wall -Wextra) +target_link_libraries(unit_tests PRIVATE doctest::doctest ArduinoJson) + +enable_testing() +add_test(NAME unit_tests COMMAND unit_tests) diff --git a/esphome/tests/fixtures.h b/esphome/tests/fixtures.h new file mode 100644 index 0000000..1d3424d --- /dev/null +++ b/esphome/tests/fixtures.h @@ -0,0 +1,38 @@ +#pragma once +#include + +#include +#include +#include +#include + +#ifndef FIXTURES_DIR +#error "FIXTURES_DIR must be defined by the build" +#endif + +inline std::string read_fixture(const std::string &relative) { + std::ifstream in(std::string(FIXTURES_DIR) + "/" + relative, std::ios::binary); + if (!in) + throw std::runtime_error("cannot open fixture " + relative); + std::stringstream ss; + ss << in.rdbuf(); + return ss.str(); +} + +// Re-serialises one top-level field of a fixture file as compact JSON. +inline std::string json_field(const std::string &file, const char *key) { + JsonDocument doc; + if (deserializeJson(doc, read_fixture(file))) + throw std::runtime_error("fixture is not JSON: " + file); + std::string out; + serializeJson(doc[key], out); + return out; +} + +// Returns a top-level string field of a fixture file as is (no JSON quoting). +inline std::string json_string_field(const std::string &file, const char *key) { + JsonDocument doc; + if (deserializeJson(doc, read_fixture(file))) + throw std::runtime_error("fixture is not JSON: " + file); + return doc[key].as(); +} diff --git a/esphome/tests/test_axp2101.cpp b/esphome/tests/test_axp2101.cpp new file mode 100644 index 0000000..a4429b2 --- /dev/null +++ b/esphome/tests/test_axp2101.cpp @@ -0,0 +1,19 @@ +#include + +#include "axp2101_battery/axp2101_regs.h" + +using namespace esphome::axp2101_battery; + +TEST_CASE("axp2101 register helpers") { + CHECK(battery_present(0x08)); + CHECK_FALSE(battery_present(0xF7)); + CHECK(is_charging(0x20)); + CHECK(is_charging(0x3F)); + CHECK_FALSE(is_charging(0x40)); + CHECK_FALSE(is_charging(0x00)); + CHECK_FALSE(is_charging(0xA0)); + CHECK(battery_millivolts(0x0F, 0xA0) == 4000); + CHECK(battery_millivolts(0xFF, 0xFF) == 0x1FFF); + CHECK(battery_percent(87) == 87.0f); + CHECK(battery_percent(150) == 100.0f); +} diff --git a/esphome/tests/test_color.cpp b/esphome/tests/test_color.cpp new file mode 100644 index 0000000..91ce05b --- /dev/null +++ b/esphome/tests/test_color.cpp @@ -0,0 +1,33 @@ +#include + +#include "fixtures.h" +#include "ha_controller/color.h" + +using namespace esphome::ha_controller; + +TEST_CASE("parse_hex_rgb accepts RRGGBB and #RRGGBB") { + uint32_t v = 0; + CHECK(parse_hex_rgb("5B9E4D", v)); + CHECK(v == 0x5B9E4D); + CHECK(parse_hex_rgb("#c94f3d", v)); + CHECK(v == 0xC94F3D); + v = 7; + CHECK_FALSE(parse_hex_rgb("GGGGGG", v)); + CHECK_FALSE(parse_hex_rgb("12345", v)); + CHECK_FALSE(parse_hex_rgb("#1234567", v)); + CHECK_FALSE(parse_hex_rgb("", v)); + CHECK(v == 7); +} + +TEST_CASE("text colour follows colors.json") { + JsonDocument doc; + REQUIRE_FALSE(deserializeJson(doc, read_fixture("colors.json"))); + REQUIRE(doc.as().size() > 0); + for (JsonObject e : doc.as()) { + uint32_t bg = 0, text = 0; + REQUIRE(parse_hex_rgb(e["bg"].as(), bg)); + REQUIRE(parse_hex_rgb(e["text"].as(), text)); + INFO(e["bg"].as()); + CHECK(text_color_for(bg) == text); + } +} diff --git a/esphome/tests/test_format.cpp b/esphome/tests/test_format.cpp new file mode 100644 index 0000000..2bf371f --- /dev/null +++ b/esphome/tests/test_format.cpp @@ -0,0 +1,15 @@ +#include + +#include + +#include "ha_controller/format.h" + +using namespace esphome::ha_controller; + +TEST_CASE("format helpers") { + CHECK(format_value(20.5f, 0.5f) == "20.5"); + CHECK(format_value(21, 1) == "21"); + CHECK(format_value(21, 0.5f) == "21.0"); + CHECK(format_percent(87.4f) == "87 %"); + CHECK(format_percent(NAN) == "— %"); +} diff --git a/esphome/tests/test_gesture.cpp b/esphome/tests/test_gesture.cpp new file mode 100644 index 0000000..d1eb9f2 --- /dev/null +++ b/esphome/tests/test_gesture.cpp @@ -0,0 +1,73 @@ +#include + +#include "ha_controller/gesture.h" + +using namespace esphome::ha_controller; + +TEST_CASE("edge classification") { + CHECK(classify_edge(233, 233, 466, 36) == Edge::NONE); + CHECK(classify_edge(460, 233, 466, 36) == Edge::RIGHT); + CHECK(classify_edge(5, 233, 466, 36) == Edge::LEFT); + CHECK(classify_edge(233, 4, 466, 36) == Edge::TOP); + CHECK(classify_edge(233, 462, 466, 36) == Edge::BOTTOM); + CHECK(classify_edge(430, 233, 466, 36) == Edge::RIGHT); // r = 197, boundary + CHECK(classify_edge(429, 233, 466, 36) == Edge::NONE); + CHECK(classify_edge(10, 10, 466, 36) == Edge::LEFT); // diagonal tie -> horizontal + CHECK(classify_edge(456, 10, 466, 36) == Edge::RIGHT); // outside the visible circle still classifies +} + +TEST_CASE("grid step per edge") { + CHECK(step_for(Edge::RIGHT).dx == 1); + CHECK(step_for(Edge::RIGHT).dy == 0); + CHECK(step_for(Edge::LEFT).dx == -1); + CHECK(step_for(Edge::LEFT).dy == 0); + CHECK(step_for(Edge::TOP).dx == 0); + CHECK(step_for(Edge::TOP).dy == -1); + CHECK(step_for(Edge::BOTTOM).dx == 0); + CHECK(step_for(Edge::BOTTOM).dy == 1); + CHECK(step_for(Edge::NONE).dx == 0); + CHECK(step_for(Edge::NONE).dy == 0); +} + +TEST_CASE("swipe tracker") { + SwipeTracker t; + t.begin(Edge::RIGHT, true, 460, 233, 0); + CHECK(t.update(400, 233, 50) == 60); + CHECK(t.update(300, 240, 300) == 160); + CHECK(t.release(400)); + + t.begin(Edge::RIGHT, true, 460, 233, 0); + CHECK(t.update(420, 233, 500) == 40); + CHECK_FALSE(t.release(600)); // slow and short + + t.begin(Edge::LEFT, true, 5, 233, 0); + t.update(25, 233, 10); + CHECK(t.update(65, 233, 40) == 60); + CHECK(t.release(45)); // flick + + t.begin(Edge::RIGHT, true, 460, 233, 0); + CHECK(t.update(470, 233, 50) == 0); // outward ignored + + t.begin(Edge::TOP, false, 233, 4, 0); + CHECK(t.update(233, 204, 100) == 48); + CHECK_FALSE(t.release(150)); // rubber band + + t.begin(Edge::BOTTOM, true, 233, 462, 0); + CHECK(t.update(233, -600, 50) == 466); // clamp to size + + t.begin(Edge::LEFT, true, 5, 233, 0xFFFFFFF0u); + t.update(65, 233, 0x00000020u); + CHECK(t.release(0x00000020u)); // wraparound flick + + t.begin(Edge::LEFT, true, 5, 233, 0); + t.update(300, 233, 10); + t.reset(); + CHECK_FALSE(t.active()); + CHECK_FALSE(t.release(20)); +} + +TEST_CASE("settle duration") { + CHECK(settle_duration_ms(466, 466) == 220); + CHECK(settle_duration_ms(0, 466) == 80); + CHECK(settle_duration_ms(233, 466) == 110); +} diff --git a/esphome/tests/test_hold.cpp b/esphome/tests/test_hold.cpp new file mode 100644 index 0000000..f51355f --- /dev/null +++ b/esphome/tests/test_hold.cpp @@ -0,0 +1,15 @@ +#include + +#include "ha_controller/hold.h" + +using namespace esphome::ha_controller; + +TEST_CASE("interaction hold") { + InteractionHold h; + CHECK_FALSE(h.active(0)); + h.touch(1000); + CHECK(h.active(2499)); + CHECK_FALSE(h.active(2500)); + h.touch(0xFFFFFF00u); + CHECK(h.active(0x00000100u)); +} diff --git a/esphome/tests/test_knob.cpp b/esphome/tests/test_knob.cpp new file mode 100644 index 0000000..347f451 --- /dev/null +++ b/esphome/tests/test_knob.cpp @@ -0,0 +1,18 @@ +#include + +#include "ha_controller/knob.h" + +using namespace esphome::ha_controller; + +TEST_CASE("knob scale") { + CHECK(KnobScale{0, 100, 1}.steps() == 100); + CHECK(KnobScale{7, 35, 0.5f}.steps() == 56); + CHECK(KnobScale{7, 35, 0.5f}.index_of(20.5f) == 27); + CHECK(KnobScale{7, 35, 0.5f}.value_at(27) == doctest::Approx(20.5)); + CHECK(KnobScale{7, 35, 0.5f}.index_of(100) == 56); + CHECK(KnobScale{7, 35, 0.5f}.index_of(-5) == 0); + CHECK(KnobScale{10, 10, 0.5f}.steps() == 0); + CHECK(KnobScale{7, 35, 0}.steps() == 28); + CHECK(KnobScale{7, 35, 0.5f}.value_at(999) == doctest::Approx(35)); + CHECK(KnobScale{7, 35, 0.5f}.value_at(-3) == doctest::Approx(7)); +} diff --git a/esphome/tests/test_layout.cpp b/esphome/tests/test_layout.cpp new file mode 100644 index 0000000..cf4e153 --- /dev/null +++ b/esphome/tests/test_layout.cpp @@ -0,0 +1,176 @@ +#include + +#include + +#include +#include + +#include "fixtures.h" +#include "ha_controller/layout.h" + +using namespace esphome::ha_controller; + +TEST_CASE("parses the reference payload") { + Layout l; + REQUIRE(parse_layout(json_field("payloads/valid/reference.json", "payload"), l) == ParseError::NONE); + CHECK(l.rev == "90538742"); + CHECK(l.start == "b1"); + CHECK(l.sleep_s == 20); + CHECK(l.blocks.size() == 4); + REQUIRE(l.find("b3") != nullptr); + CHECK(l.find("b3")->widget == Widget::CUSTOM); + CHECK(l.find("b3")->items.size() == 5); + CHECK(l.find("b3")->items[1].kind == ItemKind::EMOJI); + CHECK(l.find("b3")->items[1].text == "👋"); + CHECK(l.find("b3")->items[1].font == FontSize::XL); + CHECK(l.find("b3")->items[2].font == FontSize::S); + CHECK(l.find("b3")->items[2].kind == ItemKind::ENTITY); + CHECK(l.find("b3")->items[3].kind == ItemKind::BATTERY); + CHECK(l.find("b3")->items[4].kind == ItemKind::BRIGHTNESS); + CHECK(l.find("b3")->items[0].text == "Hello World"); + REQUIRE(l.find("b4") != nullptr); + CHECK(l.find("b4")->widget == Widget::CLIMATE); + REQUIRE(l.find("b1") != nullptr); + CHECK(l.find("b1")->bg == 0x5B9E4D); + CHECK(l.find("b1")->name == "Kitchen"); + CHECK(l.find("b1")->font == FontSize::M); + REQUIRE(l.find_at(0, -1) != nullptr); + CHECK(l.find_at(0, -1)->id == "b2"); + CHECK(l.find_at(5, 5) == nullptr); + CHECK(l.find("nope") == nullptr); +} + +TEST_CASE("parses the empty payload") { + Layout l; + l.start = "stale"; + REQUIRE(parse_layout(json_field("payloads/valid/empty.json", "payload"), l) == ParseError::NONE); + CHECK(l.rev == "c4aad3fa"); + CHECK(l.start == ""); + CHECK(l.sleep_s == 20); + CHECK(l.blocks.empty()); +} + +TEST_CASE("parses sleep 0 and 3600") { + Layout l; + CHECK(parse_layout(R"({"v":1,"rev":"x","start":null,"sleep":0,"blocks":[]})", l) == ParseError::NONE); + CHECK(l.sleep_s == 0); + CHECK(parse_layout(R"({"v":1,"rev":"x","start":null,"sleep":3600,"blocks":[]})", l) == ParseError::NONE); + CHECK(l.sleep_s == 3600); +} + +TEST_CASE("strips U+FE0F from emoji text") { + Layout l; + const std::string json = + "{\"v\":1,\"rev\":\"x\",\"start\":null,\"sleep\":20,\"blocks\":[{\"id\":\"b1\",\"x\":0,\"y\":0,\"name\":\"A\"," + "\"bg\":\"FFFFFF\",\"font\":\"m\",\"widget\":\"custom\",\"items\":[{\"id\":\"i1\",\"kind\":\"emoji\"," + "\"text\":\"\xE2\x9D\x84\xEF\xB8\x8F\",\"font\":\"xl\"}]}]}"; + REQUIRE(parse_layout(json, l) == ParseError::NONE); + CHECK(l.blocks[0].items[0].text == "\xE2\x9D\x84"); +} + +TEST_CASE("parses the emoji-variation fixture") { + Layout l; + REQUIRE(parse_layout(json_field("payloads/valid/emoji-variation.json", "payload"), l) == ParseError::NONE); + CHECK(l.sleep_s == 3600); + CHECK(l.blocks[0].items[0].text == "\xE2\x9D\x84"); +} + +static ParseError expected_code(const std::string &s) { + if (s == "bad_json") + return ParseError::BAD_JSON; + if (s == "unsupported_version") + return ParseError::UNSUPPORTED_VERSION; + if (s == "invalid_payload") + return ParseError::INVALID_PAYLOAD; + FAIL("unknown expectation " << s); + return ParseError::NONE; +} + +TEST_CASE("rejects every invalid payload fixture") { + std::vector names; + const std::string dir = std::string(FIXTURES_DIR) + "/payloads/invalid"; + DIR *d = opendir(dir.c_str()); + REQUIRE(d != nullptr); + while (dirent *e = readdir(d)) { + std::string n = e->d_name; + if (n.size() > 5 && n.substr(n.size() - 5) == ".json") + names.push_back(n); + } + closedir(d); + std::sort(names.begin(), names.end()); + REQUIRE(names.size() >= 6); + for (const auto &n : names) { + INFO(n); + const std::string file = "payloads/invalid/" + n; + Layout l; + l.rev = "keep"; + l.start = "b9"; + l.sleep_s = 77; + l.blocks.push_back(Block{}); + CHECK(parse_layout(json_string_field(file, "text"), l) == expected_code(json_string_field(file, "expect"))); + CHECK(l.rev == "keep"); + CHECK(l.start == "b9"); + CHECK(l.sleep_s == 77); + CHECK(l.blocks.size() == 1); + } +} + +static std::string block(const std::string &fields) { + return "{\"v\":1,\"rev\":\"x\",\"start\":null,\"sleep\":20,\"blocks\":[{" + fields + "}]}"; +} +static const std::string OK_BLOCK = + "\"id\":\"b1\",\"x\":0,\"y\":0,\"name\":\"A\",\"bg\":\"FFFFFF\",\"font\":\"m\",\"widget\":\"light\""; + +TEST_CASE("accepts the baseline block used by the hostile cases") { + Layout l; + CHECK(parse_layout(block(OK_BLOCK), l) == ParseError::NONE); +} + +TEST_CASE("rejects hostile payloads") { + auto replace = [](std::string s, const std::string &from, const std::string &to) { + auto p = s.find(from); + REQUIRE(p != std::string::npos); + return s.replace(p, from.size(), to); + }; + std::vector cases = { + block(replace(OK_BLOCK, "\"x\":0", "\"x\":1e40")), + block(replace(OK_BLOCK, "\"x\":0", "\"x\":\"1\"")), + block(replace(OK_BLOCK, "\"x\":0", "\"x\":1.5")), + block(replace(OK_BLOCK, "\"x\":0", "\"x\":3000000000")), + block(replace(OK_BLOCK, "\"name\":\"A\"", "\"name\":5")), + block(replace(OK_BLOCK, "\"widget\":\"light\"", "\"widget\":\"custom\"")), // custom without items + block(replace(OK_BLOCK, "\"font\":\"m\"", "\"font\":\"xxl\"")), + block(replace(OK_BLOCK, "\"bg\":\"FFFFFF\"", "\"bg\":\"GGGGGG\"")), + block(replace(OK_BLOCK, "\"bg\":\"FFFFFF\"", "\"bg\":\"#FFFFFF\"")), + block(replace(OK_BLOCK, "\"widget\":\"light\"", "\"widget\":\"custom\",\"items\":[{\"id\":\"i\",\"kind\":\"text\",\"font\":\"m\"}]")), + block(replace(OK_BLOCK, "\"widget\":\"light\"", "\"widget\":\"custom\",\"items\":[{\"id\":\"i\",\"kind\":\"gif\",\"font\":\"m\"}]")), + R"({"v":1,"rev":"x","start":null,"sleep":-1,"blocks":[]})", + R"({"v":1,"rev":"x","start":null,"sleep":4000,"blocks":[]})", + R"({"v":1,"rev":"x","start":null,"sleep":1.5,"blocks":[]})", + R"({"v":1,"rev":"x","start":null,"sleep":"20","blocks":[]})", + R"({"v":1,"rev":"x","start":null,"blocks":[]})", + R"({"v":1,"rev":"x","start":null,"sleep":20})", + R"({"v":1,"rev":"x","sleep":20,"blocks":[]})", + R"({"v":1,"rev":5,"start":null,"sleep":20,"blocks":[]})", + R"({"v":1,"rev":"x","start":5,"sleep":20,"blocks":[]})", + R"({"v":1,"rev":"x","start":null,"sleep":20,"blocks":{}})", + R"({"v":1,"rev":"x","start":null,"sleep":20,"blocks":[5]})", + "{\"v\":1,\"rev\":\"x\",\"start\":null,\"sleep\":20,\"blocks\":" + std::string(64, '[') + std::string(64, ']') + "}", + std::string(64, '[') + std::string(64, ']'), + }; + for (const auto &c : cases) { + INFO(c); + Layout l; + l.rev = "keep"; + ParseError e = parse_layout(c, l); + CHECK((e == ParseError::INVALID_PAYLOAD || e == ParseError::BAD_JSON)); + CHECK(l.rev == "keep"); + } +} + +TEST_CASE("parse_error_code names") { + CHECK(std::string(parse_error_code(ParseError::NONE)) == "none"); + CHECK(std::string(parse_error_code(ParseError::BAD_JSON)) == "bad_json"); + CHECK(std::string(parse_error_code(ParseError::UNSUPPORTED_VERSION)) == "unsupported_version"); + CHECK(std::string(parse_error_code(ParseError::INVALID_PAYLOAD)) == "invalid_payload"); +} diff --git a/esphome/tests/test_main.cpp b/esphome/tests/test_main.cpp new file mode 100644 index 0000000..0a3f254 --- /dev/null +++ b/esphome/tests/test_main.cpp @@ -0,0 +1,2 @@ +#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN +#include diff --git a/esphome/tests/test_sleep.cpp b/esphome/tests/test_sleep.cpp new file mode 100644 index 0000000..12fd15f --- /dev/null +++ b/esphome/tests/test_sleep.cpp @@ -0,0 +1,16 @@ +#include + +#include "ha_controller/sleep.h" + +using namespace esphome::ha_controller; + +TEST_CASE("sleep: default delay is 20 seconds") { CHECK(DEFAULT_SLEEP_S == 20); } + +TEST_CASE("sleep: a timeout of 0 never sleeps") { CHECK_FALSE(should_sleep(10'000'000, 0)); } + +TEST_CASE("sleep: sleeps exactly at the timeout") { + CHECK_FALSE(should_sleep(19'999, 20)); + CHECK(should_sleep(20'000, 20)); + CHECK_FALSE(should_sleep(3'599'999, 3600)); + CHECK(should_sleep(3'600'000, 3600)); +} diff --git a/esphome/tests/test_stack.cpp b/esphome/tests/test_stack.cpp new file mode 100644 index 0000000..12e3ebc --- /dev/null +++ b/esphome/tests/test_stack.cpp @@ -0,0 +1,48 @@ +#include + +#include "ha_controller/stack.h" + +using namespace esphome::ha_controller; + +static bool inside(const StackItem &it, int top, int radius) { + int lim = chord_limit(radius, it.half_width); + return top >= -lim && top + it.height <= lim; +} + +TEST_CASE("stack: few items stay centred with the default gap") { + std::vector items = {{40, 160, false}, {40, 160, false}, {40, 135, true}}; + auto l = layout_stack(items); + CHECK(l.fits); + CHECK(l.gap == 8); + CHECK(l.top[0] == -(120 + 16) / 2); +} + +TEST_CASE("stack: six items with the slider row last keep every control inside radius 185") { + std::vector items = {{50, 160, false}, {50, 160, false}, {50, 160, false}, + {50, 160, false}, {50, 160, false}, {40, 135, true}}; + auto l = layout_stack(items); + CHECK(l.fits); + for (size_t i = 0; i < items.size(); i++) + CHECK(inside(items[i], l.top[i], items[i].interactive ? 185 : 233)); + for (size_t i = 1; i < items.size(); i++) + CHECK(l.top[i] >= l.top[i - 1] + items[i - 1].height); +} + +TEST_CASE("stack: slider row alone in the middle of tall text is reported as not fitting") { + std::vector items = {{60, 160, false}, {60, 160, false}, {60, 160, false}, + {60, 160, false}, {60, 160, false}, {40, 135, true}}; + auto l = layout_stack(items); + CHECK_FALSE(l.fits); +} + +TEST_CASE("stack: single-line capped labels fit where wrapped text does not") { + std::vector wrapped = {{60, 160, false}, {60, 160, false}, {60, 160, false}, + {60, 160, false}, {60, 160, false}, {40, 135, true}}; + std::vector capped = {{30, 160, false}, {30, 160, false}, {30, 160, false}, + {30, 160, false}, {30, 160, false}, {40, 135, true}}; + CHECK_FALSE(layout_stack(wrapped).fits); + auto l = layout_stack(capped); + CHECK(l.fits); + for (size_t i = 0; i < capped.size(); i++) + CHECK(inside(capped[i], l.top[i], capped[i].interactive ? 185 : 233)); +} diff --git a/esphome/tests/test_states.cpp b/esphome/tests/test_states.cpp new file mode 100644 index 0000000..fbab74c --- /dev/null +++ b/esphome/tests/test_states.cpp @@ -0,0 +1,66 @@ +#include + +#include + +#include "fixtures.h" +#include "ha_controller/states.h" + +using namespace esphome::ha_controller; + +static std::vector load(const char *name) { + std::vector out; + REQUIRE(parse_states(json_field(std::string("states/") + name + ".json", "updates"), out)); + return out; +} + +TEST_CASE("parses light updates") { + auto v = load("light-dimmable-on"); + REQUIRE(v.size() == 1); + CHECK(v[0].on == true); + CHECK(v[0].brightness == 50); + auto o = load("light-onoff"); + REQUIRE(o.size() == 1); + CHECK(o[0].on == true); + CHECK(!o[0].brightness.has_value()); + auto u = load("light-unavailable"); + REQUIRE(u.size() == 1); + CHECK(u[0].available == false); +} + +TEST_CASE("parses climate updates") { + auto v = load("climate-heating"); + REQUIRE(v.size() == 1); + const StateUpdate &u = v[0]; + REQUIRE(u.target.has_value()); + CHECK(*u.target == doctest::Approx(20.5)); + CHECK(u.step == doctest::Approx(0.5)); + CHECK(u.unit == "°C"); + CHECK(u.current == "19.8 °C"); + CHECK(u.action == "Heating"); + auto d = load("climate-defaults"); + REQUIRE(d.size() == 1); + CHECK(!d[0].target.has_value()); + CHECK(d[0].current == "—"); +} + +TEST_CASE("parses entity updates") { + auto v = load("entity-precision"); + REQUIRE(!v.empty()); + bool found = false; + for (auto &u : v) + if (u.text.has_value() && *u.text == "12.3 °C") + found = true; + CHECK(found); + auto m = load("entity-missing"); + REQUIRE(m.size() == 1); + CHECK(*m[0].text == "—"); + CHECK(load("all-missing").size() == 4); +} + +TEST_CASE("rejects bad input and skips elements without id") { + std::vector out; + CHECK_FALSE(parse_states("{\"id\":1}", out)); + CHECK_FALSE(parse_states("not json", out)); + REQUIRE(parse_states("[{\"id\":1},{\"id\":\"a\"},5]", out)); + CHECK(out.size() == 1); +} diff --git a/esphome/version.yaml b/esphome/version.yaml new file mode 100644 index 0000000..57613b7 --- /dev/null +++ b/esphome/version.yaml @@ -0,0 +1,2 @@ +substitutions: + project_version: "0.1.0" diff --git a/esphome/web/index.html b/esphome/web/index.html new file mode 100644 index 0000000..5819314 --- /dev/null +++ b/esphome/web/index.html @@ -0,0 +1,78 @@ + + + + + + HA Controller — Web installer + + + + +
+

HA Controller

+

+ Firmware {{VERSION}} · + Release notes +

+ +
+ + Use Chrome or Edge on a desktop computer. + Open this page over HTTPS. + +
+ +
    +
  1. Connect the screen to your computer with a USB-C cable.
  2. +
  3. Click Install and pick the serial port of the screen.
  4. +
  5. Set up Wi-Fi when asked, or join the "HA Controller" access point.
  6. +
  7. Add the screen in Home Assistant (ESPHome integration).
  8. +
  9. Install the HA Controller integration {{VERSION}} from HACS.
  10. +
+ +

If the board is not detected, hold BOOT while plugging it in.

+
+ + diff --git a/hacs.json b/hacs.json new file mode 100644 index 0000000..6ef5b47 --- /dev/null +++ b/hacs.json @@ -0,0 +1 @@ +{"name": "HA Controller", "homeassistant": "2026.10.0", "zip_release": true, "filename": "ha_controller.zip"}