3
0

4 Коммиты 09e2910950 ... a95be5ac65

Автор SHA1 Сообщение Дата
  ZiB a95be5ac65 Write the zEPD ESPHome adapter; full compile verified end-to-end 4 недель назад
  ZiB a179e39d8d Add zEPD JSON model registry: loader, codegen, default.json schema 4 недель назад
  ZiB 5fd8bcca0d Copy engine core forward as zepd::Engine/EngineModel 4 недель назад
  ZiB ffee2a79af Scaffold esphome-zepd and esphome-docs directories 4 недель назад

+ 8 - 0
esphome-docs/README.md

@@ -0,0 +1,8 @@
+# esphome-docs
+
+Skeleton for the zEPD documentation tree, mirroring the real ESPHome
+project's `esphome-docs` layout/naming so it can be extracted to its own
+repo later with no renaming.
+
+Empty placeholder — content comes once `esphome-zepd` has a stable
+component to document. See `claude/ZEPD_PLAN.md`.

+ 8 - 0
esphome-zepd/README.md

@@ -0,0 +1,8 @@
+# esphome-zepd
+
+The zEPD ESPHome component — a fresh rebuild of the e-paper display engine,
+replacing `code/components/gxepd2/` (left untouched as the before/after
+baseline during this migration).
+
+Scaffold only right now. See `claude/ZEPD_PLAN.md` and
+`claude/DESCRIPTOR_REGISTRY_PLAN.md` for the plan this tree implements.

+ 1 - 0
esphome-zepd/components/zepd/__init__.py

@@ -0,0 +1 @@
+CODEOWNERS = ["@zib"]

+ 136 - 0
esphome-zepd/components/zepd/codegen.py

@@ -0,0 +1,136 @@
+"""Merged model dict -> C++ EngineModel codegen.
+
+Plain `(dict) -> str`, no ESPHome/`cg`/`CORE` dependency (see
+claude/DESCRIPTOR_REGISTRY_PLAN.md) - callable from display.py's to_code()
+at ESPHome compile time, and from standalone host tooling
+(check_descriptors.py and friends) outside any ESPHome build.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+_LINE_ORDERS = {"SEQUENTIAL": "LineOrder::SEQUENTIAL", "PAIRED_EDGES": "LineOrder::PAIRED_EDGES"}
+
+
+def _hex_bytes(s: str) -> list[int]:
+    s = s or ""
+    if len(s) % 2 != 0:
+        raise ValueError(f"odd-length hex byte string: {s!r}")
+    return [int(s[i : i + 2], 16) for i in range(0, len(s), 2)]
+
+
+def _byte_array_literal(data: list[int]) -> str:
+    return "{" + ", ".join(f"0x{b:02X}" for b in data) + "}"
+
+
+def _emit_sequence(out: list[str], prefix: str, seq: list[dict]) -> tuple[str, int]:
+    """Emits one EpdCommand table (and its per-entry data byte arrays) as
+    `prefix`-named globals; returns (array name, length)."""
+    entries = []
+    for i, c in enumerate(seq):
+        data = _hex_bytes(c.get("data", ""))
+        data_name = "nullptr"
+        if data:
+            data_name = f"{prefix}_{i}_DATA"
+            out.append(f"inline const uint8_t {data_name}[] = {_byte_array_literal(data)};")
+        cmd = _hex_bytes(c["cmd"])[0]
+        entries.append(
+            "    {{0x{cmd:02X}, {data_name}, {data_len}, {before}, {after}, {wait}}},".format(
+                cmd=cmd,
+                data_name=data_name,
+                data_len=len(data),
+                before=c.get("delay_before_ms", 0),
+                after=c.get("delay_after_ms", 0),
+                wait="true" if c.get("wait_busy_after", False) else "false",
+            )
+        )
+    seq_name = f"{prefix}_SEQ"
+    if entries:
+        out.append(f"inline const EpdCommand {seq_name}[] = {{")
+        out.extend(entries)
+        out.append("};")
+    else:
+        out.append(f"inline const EpdCommand *{seq_name} = nullptr;")
+    return seq_name, len(entries)
+
+
+def generate_cpp(model: dict[str, Any], var_name: str) -> str:
+    """Generates one `inline const EngineModel {var_name} = {...};`
+    plus its backing command/palette arrays, as a single translation unit's
+    worth of text (no #pragma once / includes - the caller wraps this)."""
+    out: list[str] = []
+    prefix = var_name.upper()
+
+    init_name, init_len = _emit_sequence(out, f"{prefix}_INIT", model["init_sequence"])
+    refresh_name, refresh_len = _emit_sequence(out, f"{prefix}_REFRESH", model["refresh_sequence"])
+    power_off_name, power_off_len = _emit_sequence(out, f"{prefix}_POWEROFF", model.get("power_off_sequence") or [])
+    hibernate_name, hibernate_len = _emit_sequence(out, f"{prefix}_HIBERNATE", model.get("hibernate_sequence") or [])
+
+    planes = model["planes"]
+    if len(planes) > 2:
+        raise ValueError(f"{var_name}: {len(planes)} planes given, engine supports at most 2")
+    window_names: list[str] = ["nullptr", "nullptr"]
+    window_lens: list[int] = [0, 0]
+    plane_write_cmd: list[int] = [0, 0]
+    plane_write_cmd_full: list[int] = [0, 0]
+    plane_invert: list[bool] = [False, False]
+    window_per_plane = False
+    plane_width = 0
+    base_window = planes[0].get("window_sequence")
+    for i, p in enumerate(planes):
+        window_seq = p.get("window_sequence") or (base_window if i == 0 else None)
+        if window_seq is not None:
+            if i > 0 and p.get("window_sequence") is not None:
+                window_per_plane = True
+            window_names[i], window_lens[i] = _emit_sequence(out, f"{prefix}_WINDOW{i}", window_seq)
+        plane_write_cmd[i] = _hex_bytes(p["plane_write_cmd"])[0]
+        plane_write_cmd_full[i] = _hex_bytes(p.get("plane_write_cmd_for_full_refresh", "00"))[0]
+        plane_invert[i] = bool(p.get("plane_invert", False))
+        if p.get("width") is not None:
+            plane_width = p["width"]
+
+    palette_name = "nullptr"
+    palette_len = 0
+    palette_entries = model.get("palette") or []
+    if palette_entries:
+        palette_name = f"{prefix}_PALETTE"
+        out.append(f"inline const EpdPaletteEntry {palette_name}[] = {{")
+        for e in palette_entries:
+            r, g, b = _hex_bytes(e["rgb"])
+            code = _hex_bytes(e["code"])[0]
+            out.append(f"    {{0x{r:02X}, 0x{g:02X}, 0x{b:02X}, 0x{code:02X}}},")
+        out.append("};")
+        palette_len = len(palette_entries)
+
+    out.append(f"inline const EngineModel {var_name} = {{")
+    out.append(f"    .width = {model['width']},")
+    out.append(f"    .height = {model['height']},")
+    out.append(f"    .busy_active_level = {'true' if model['busy_active_level'] else 'false'},")
+    out.append(f"    .busy_timeout_ms = {model['busy_timeout_ms']},")
+    out.append(f"    .init_sequence = {init_name},")
+    out.append(f"    .init_sequence_len = {init_len},")
+    out.append(f"    .window_sequence = {{{window_names[0]}, {window_names[1]}}},")
+    out.append(f"    .window_sequence_len = {{{window_lens[0]}, {window_lens[1]}}},")
+    out.append(f"    .window_per_plane = {'true' if window_per_plane else 'false'},")
+    out.append(f"    .plane_count = {len(planes)},")
+    out.append(f"    .plane_write_cmd = {{0x{plane_write_cmd[0]:02X}, 0x{plane_write_cmd[1]:02X}}},")
+    out.append(
+        "    .plane_write_cmd_for_full_refresh = "
+        f"{{0x{plane_write_cmd_full[0]:02X}, 0x{plane_write_cmd_full[1]:02X}}},"
+    )
+    out.append(f"    .plane_invert = {{{'true' if plane_invert[0] else 'false'}, {'true' if plane_invert[1] else 'false'}}},")
+    out.append(f"    .plane_width = {plane_width},")
+    out.append(f"    .line_order = {_LINE_ORDERS[model.get('line_order', 'SEQUENTIAL')]},")
+    out.append(f"    .bits_per_pixel = {model.get('bits_per_pixel', 1)},")
+    out.append(f"    .palette = {palette_name},")
+    out.append(f"    .palette_len = {palette_len},")
+    out.append(f"    .blank_code = 0x{model.get('blank_code', 0):02X},")
+    out.append(f"    .refresh_sequence = {refresh_name},")
+    out.append(f"    .refresh_sequence_len = {refresh_len},")
+    out.append(f"    .power_off_sequence = {power_off_name},")
+    out.append(f"    .power_off_sequence_len = {power_off_len},")
+    out.append(f"    .hibernate_sequence = {hibernate_name},")
+    out.append(f"    .hibernate_sequence_len = {hibernate_len},")
+    out.append("};")
+    return "\n".join(out) + "\n"

+ 133 - 0
esphome-zepd/components/zepd/display.py

@@ -0,0 +1,133 @@
+"""ESPHome display platform driving a zEPD engine model via the native
+replay engine (see engine/engine.h) instead of GxEPD2's own C++ classes.
+
+Models are selected via `model:`, each a drivers/<model>.json merged over
+drivers/default.json (see registry.py) and codegen'd at compile time to a
+single generated header (see codegen.py) - no per-model panel_*.h, and no
+`PANELS` dict here. See claude/DESCRIPTOR_REGISTRY_PLAN.md.
+"""
+
+import re
+
+import esphome.codegen as cg
+import esphome.config_validation as cv
+from esphome import pins
+from esphome.components import display, spi
+from esphome.const import (
+    CONF_BUSY_PIN,
+    CONF_CS_PIN,
+    CONF_DC_PIN,
+    CONF_ID,
+    CONF_LAMBDA,
+    CONF_MODEL,
+    CONF_RESET_PIN,
+    CONF_SPI_ID,
+    Framework,
+)
+from esphome.core import CORE
+from esphome.helpers import write_file_if_changed
+from esphome.types import ConfigType
+
+from . import codegen as zepd_codegen
+from . import registry as zepd_registry
+
+CODEOWNERS = ["@zib"]
+DEPENDENCIES = ["spi"]
+
+# See the matching comment in the legacy components/gxepd2/display.py - same
+# mono-inversion tradeoff, carried forward unchanged.
+CONF_INVERT_MONO = "invert_mono"
+
+# Compiles in ZepdDisplay's dev-time diagnostic methods (currently
+# diag_update_no_reset()), stashed behind this flag so a production build
+# doesn't pay flash for bench-only tooling. Off by default.
+CONF_DIAGNOSTICS = "diagnostics"
+
+zepd_ns = cg.esphome_ns.namespace("zepd")
+ZepdDisplay = zepd_ns.class_("ZepdDisplay", display.DisplayBuffer)
+
+MODELS = zepd_registry.list_models()
+
+
+# Human-facing label for test_pattern(): the first OEM part number minus its
+# GDEx series prefix (GDEQ0583T31 -> 0583T31), same rule as the legacy
+# _panel_label. Falls back to the registry key itself when a model carries
+# no oem_part_numbers yet.
+def _model_label(model_key: str, model: dict) -> str:
+    parts = model.get("oem_part_numbers") or []
+    part = parts[0] if parts else model_key
+    return re.sub(r"^GDE[A-Z]", "", part)
+
+
+CONFIG_SCHEMA = cv.All(
+    display.FULL_DISPLAY_SCHEMA.extend(
+        {
+            cv.GenerateID(): cv.declare_id(ZepdDisplay),
+            cv.GenerateID(CONF_SPI_ID): cv.use_id(spi.SPIComponent),
+            cv.Required(CONF_MODEL): cv.one_of(*MODELS),
+            cv.Required(CONF_CS_PIN): pins.gpio_output_pin_schema,
+            cv.Required(CONF_DC_PIN): pins.gpio_output_pin_schema,
+            cv.Optional(CONF_RESET_PIN): pins.gpio_output_pin_schema,
+            cv.Optional(CONF_BUSY_PIN): pins.gpio_input_pin_schema,
+            cv.Optional(CONF_INVERT_MONO): cv.boolean,
+            cv.Optional(CONF_DIAGNOSTICS, default=False): cv.boolean,
+        }
+    ),
+    # Same framework support rule as the legacy component - the runtime C++
+    # only uses portable ESPHome abstractions.
+    cv.only_with_framework([Framework.ESP_IDF, Framework.ARDUINO]),
+)
+
+
+async def to_code(config: ConfigType) -> None:
+    var = cg.new_Pvariable(config[CONF_ID])
+
+    model = zepd_registry.load_model(config[CONF_MODEL])
+
+    # Codegen the one selected model to a fixed-name generated header at
+    # src/ root - not under this component's own directory, which
+    # writer.copy_src_tree() would otherwise delete on every build (see
+    # claude/DESCRIPTOR_REGISTRY_PLAN.md, "Where generated C++ lands").
+    cpp_body = zepd_codegen.generate_cpp(model, "ZEPD_MODEL")
+    # Wrapped in esphome::zepd, the same namespace as the adapter
+    # (ZepdDisplay) and the engine core (EngineModel, Engine) both live in -
+    # see engine_model.h/engine.h. Keeping a single namespace avoids the
+    # ambiguity ESPHome's own generated main.cpp would otherwise hit: it
+    # writes unqualified `zepd::Foo` trusting `using namespace esphome;` to
+    # resolve it, which breaks if a second, unrelated top-level `zepd`
+    # namespace also exists.
+    generated = (
+        "#pragma once\n"
+        '#include "esphome/components/zepd/engine_model.h"\n\n'
+        "namespace esphome::zepd {\n\n"
+        f"{cpp_body}\n"
+        "}  // namespace esphome::zepd\n"
+    )
+    write_file_if_changed(CORE.relative_src_path("zepd_model_generated.h"), generated)
+
+    cg.add(var.set_descriptor(cg.RawExpression("&esphome::zepd::ZEPD_MODEL")))
+    cg.add(var.set_cs_pin(await cg.gpio_pin_expression(config[CONF_CS_PIN])))
+    cg.add(var.set_dc_pin(await cg.gpio_pin_expression(config[CONF_DC_PIN])))
+    if reset_pin := config.get(CONF_RESET_PIN):
+        cg.add(var.set_reset_pin(await cg.gpio_pin_expression(reset_pin)))
+    if busy_pin := config.get(CONF_BUSY_PIN):
+        cg.add(var.set_busy_pin(await cg.gpio_pin_expression(busy_pin)))
+
+    spi_parent = await cg.get_variable(config[CONF_SPI_ID])
+    cg.add(var.set_spi_parent(spi_parent))
+
+    cg.add(var.set_invert_mono(config.get(CONF_INVERT_MONO, False)))
+
+    cg.add(var.set_model_name(_model_label(config[CONF_MODEL], model)))
+    cg.add(var.set_verified(bool(model.get("verified", False))))
+
+    if config[CONF_DIAGNOSTICS]:
+        cg.add_define("USE_ZEPD_DIAGNOSTICS")
+
+    # A top-level `lambda:` must be processed and attached via set_writer()
+    # here - register_display() only wires up `pages:`.
+    if CONF_LAMBDA in config:
+        lambda_ = await cg.process_lambda(config[CONF_LAMBDA], [(display.DisplayRef, "it")], return_type=cg.void)
+        cg.add(var.set_writer(lambda_))
+
+    await display.register_display(var, config)

+ 1 - 0
esphome-zepd/components/zepd/drivers/GxEPD2_102.json

@@ -0,0 +1 @@
+{}

+ 9 - 0
esphome-zepd/components/zepd/drivers/README.md

@@ -0,0 +1,9 @@
+# drivers/
+
+One `<model>.json` per panel. `default.json` is both the full schema (every
+key present) and a real, working small mono panel (GxEPD2_102) - loading
+order is `default.json` -> `<model>.json` -> optional YAML overlay, each
+step a recursive dict merge (named keys merge; lists replace whole).
+
+See `../../../../claude/DESCRIPTOR_REGISTRY_PLAN.md` for the full design,
+`../registry.py` for the loader, `../codegen.py` for the dict -> C++ step.

+ 295 - 0
esphome-zepd/components/zepd/drivers/default.json

@@ -0,0 +1,295 @@
+{
+  "oem_part_numbers": [
+    "GDEW0102T4"
+  ],
+  "source_driver": "GxEPD2_102",
+  "source_url": "",
+  "verified": false,
+  "controller": "UC8175",
+  "fmt": "mono",
+  "width": 80,
+  "height": 128,
+  "busy_active_level": false,
+  "busy_timeout_ms": 15000,
+  "init_sequence": [
+    {
+      "cmd": "D2",
+      "data": "3F",
+      "delay_before_ms": 0,
+      "delay_after_ms": 0,
+      "wait_busy_after": false
+    },
+    {
+      "cmd": "00",
+      "data": "4F",
+      "delay_before_ms": 0,
+      "delay_after_ms": 0,
+      "wait_busy_after": false
+    },
+    {
+      "cmd": "01",
+      "data": "03002B2B",
+      "delay_before_ms": 0,
+      "delay_after_ms": 0,
+      "wait_busy_after": false
+    },
+    {
+      "cmd": "06",
+      "data": "3F",
+      "delay_before_ms": 0,
+      "delay_after_ms": 0,
+      "wait_busy_after": false
+    },
+    {
+      "cmd": "2A",
+      "data": "0000",
+      "delay_before_ms": 0,
+      "delay_after_ms": 0,
+      "wait_busy_after": false
+    },
+    {
+      "cmd": "30",
+      "data": "13",
+      "delay_before_ms": 0,
+      "delay_after_ms": 0,
+      "wait_busy_after": false
+    },
+    {
+      "cmd": "50",
+      "data": "57",
+      "delay_before_ms": 0,
+      "delay_after_ms": 0,
+      "wait_busy_after": false
+    },
+    {
+      "cmd": "60",
+      "data": "22",
+      "delay_before_ms": 0,
+      "delay_after_ms": 0,
+      "wait_busy_after": false
+    },
+    {
+      "cmd": "61",
+      "data": "5080",
+      "delay_before_ms": 0,
+      "delay_after_ms": 0,
+      "wait_busy_after": false
+    },
+    {
+      "cmd": "82",
+      "data": "12",
+      "delay_before_ms": 0,
+      "delay_after_ms": 0,
+      "wait_busy_after": false
+    },
+    {
+      "cmd": "E3",
+      "data": "33",
+      "delay_before_ms": 0,
+      "delay_after_ms": 0,
+      "wait_busy_after": false
+    },
+    {
+      "cmd": "00",
+      "data": "6F",
+      "delay_before_ms": 0,
+      "delay_after_ms": 0,
+      "wait_busy_after": false
+    },
+    {
+      "cmd": "30",
+      "data": "05",
+      "delay_before_ms": 0,
+      "delay_after_ms": 0,
+      "wait_busy_after": false
+    },
+    {
+      "cmd": "50",
+      "data": "F2",
+      "delay_before_ms": 0,
+      "delay_after_ms": 0,
+      "wait_busy_after": false
+    },
+    {
+      "cmd": "82",
+      "data": "00",
+      "delay_before_ms": 0,
+      "delay_after_ms": 0,
+      "wait_busy_after": false
+    },
+    {
+      "cmd": "23",
+      "data": "600101000001800F00000001000000000000000000000000000000000000000000000000000000000000",
+      "delay_before_ms": 0,
+      "delay_after_ms": 0,
+      "wait_busy_after": false
+    },
+    {
+      "cmd": "24",
+      "data": "900101000001400F00000001000000000000000000000000000000000000000000000000000000000000",
+      "delay_before_ms": 0,
+      "delay_after_ms": 0,
+      "wait_busy_after": false
+    },
+    {
+      "cmd": "04",
+      "data": "",
+      "delay_before_ms": 0,
+      "delay_after_ms": 0,
+      "wait_busy_after": true
+    }
+  ],
+  "refresh_sequence": [
+    {
+      "cmd": "92",
+      "data": "",
+      "delay_before_ms": 0,
+      "delay_after_ms": 1,
+      "wait_busy_after": false
+    },
+    {
+      "cmd": "D2",
+      "data": "3F",
+      "delay_before_ms": 0,
+      "delay_after_ms": 0,
+      "wait_busy_after": false
+    },
+    {
+      "cmd": "00",
+      "data": "4F",
+      "delay_before_ms": 0,
+      "delay_after_ms": 0,
+      "wait_busy_after": false
+    },
+    {
+      "cmd": "01",
+      "data": "03002B2B",
+      "delay_before_ms": 0,
+      "delay_after_ms": 0,
+      "wait_busy_after": false
+    },
+    {
+      "cmd": "06",
+      "data": "3F",
+      "delay_before_ms": 0,
+      "delay_after_ms": 0,
+      "wait_busy_after": false
+    },
+    {
+      "cmd": "2A",
+      "data": "0000",
+      "delay_before_ms": 0,
+      "delay_after_ms": 0,
+      "wait_busy_after": false
+    },
+    {
+      "cmd": "30",
+      "data": "13",
+      "delay_before_ms": 0,
+      "delay_after_ms": 0,
+      "wait_busy_after": false
+    },
+    {
+      "cmd": "50",
+      "data": "57",
+      "delay_before_ms": 0,
+      "delay_after_ms": 0,
+      "wait_busy_after": false
+    },
+    {
+      "cmd": "60",
+      "data": "22",
+      "delay_before_ms": 0,
+      "delay_after_ms": 0,
+      "wait_busy_after": false
+    },
+    {
+      "cmd": "61",
+      "data": "5080",
+      "delay_before_ms": 0,
+      "delay_after_ms": 0,
+      "wait_busy_after": false
+    },
+    {
+      "cmd": "82",
+      "data": "12",
+      "delay_before_ms": 0,
+      "delay_after_ms": 0,
+      "wait_busy_after": false
+    },
+    {
+      "cmd": "E3",
+      "data": "33",
+      "delay_before_ms": 0,
+      "delay_after_ms": 0,
+      "wait_busy_after": false
+    },
+    {
+      "cmd": "23",
+      "data": "605A5A000001000000000000000000000000000000000000000000000000000000000000000000000000",
+      "delay_before_ms": 0,
+      "delay_after_ms": 0,
+      "wait_busy_after": false
+    },
+    {
+      "cmd": "24",
+      "data": "905A5A000001000000000000000000000000000000000000000000000000000000000000000000000000",
+      "delay_before_ms": 0,
+      "delay_after_ms": 0,
+      "wait_busy_after": false
+    },
+    {
+      "cmd": "12",
+      "data": "",
+      "delay_before_ms": 0,
+      "delay_after_ms": 0,
+      "wait_busy_after": true
+    }
+  ],
+  "power_off_sequence": [
+    {
+      "cmd": "02",
+      "data": "",
+      "delay_before_ms": 0,
+      "delay_after_ms": 0,
+      "wait_busy_after": true
+    }
+  ],
+  "hibernate_sequence": [
+    {
+      "cmd": "07",
+      "data": "A5",
+      "delay_before_ms": 0,
+      "delay_after_ms": 0,
+      "wait_busy_after": false
+    }
+  ],
+  "line_order": "SEQUENTIAL",
+  "bits_per_pixel": 1,
+  "palette": [],
+  "blank_code": 0,
+  "planes": [
+    {
+      "window_sequence": [
+        {
+          "cmd": "91",
+          "data": "",
+          "delay_before_ms": 0,
+          "delay_after_ms": 0,
+          "wait_busy_after": false
+        },
+        {
+          "cmd": "90",
+          "data": "004F007F00",
+          "delay_before_ms": 0,
+          "delay_after_ms": 0,
+          "wait_busy_after": false
+        }
+      ],
+      "plane_write_cmd": "13",
+      "plane_write_cmd_for_full_refresh": "10",
+      "plane_invert": false,
+      "width": null
+    }
+  ]
+}

+ 532 - 0
esphome-zepd/components/zepd/engine.h

@@ -0,0 +1,532 @@
+#pragma once
+
+#include <cstdint>
+#include <cstdio>
+
+#include "esphome/core/gpio.h"
+#include "esphome/core/hal.h"
+#include "esphome/core/log.h"
+#include "esphome/components/spi/spi.h"
+#include "engine_model.h"
+
+namespace esphome::zepd {
+
+// Stock GxEPD2 vendor value (20MHz).
+using EpdSPIDevice = spi::SPIDevice<spi::BIT_ORDER_MSB_FIRST, spi::CLOCK_POLARITY_LOW, spi::CLOCK_PHASE_LEADING,
+                                     spi::DATA_RATE_20MHZ>;
+
+// Replays one GxEPD2 driver's refresh cycle - reset pulse, init command table,
+// RAM-window set, per-plane byte burst, refresh trigger, busy-pin wait - as a
+// state machine stepped from loop(), instead of GxEPD2's own synchronous
+// top-to-bottom call stack. step() never blocks: every state does a small
+// bounded unit of work and returns, so nothing here can starve another task or
+// need a watchdog subscription.
+//
+// request_power_off()/request_hibernate() are a separate, standalone entry
+// point (no init/window/plane-write) replaying just
+// power_off_sequence/hibernate_sequence - for a user's own lambda, not run
+// automatically by request_full_update(). Called while a refresh is still
+// in flight (e.g. from an adapter's teardown path), they force a reset
+// pulse first to abort it rather than writing over a busy controller - see
+// begin_power_down_().
+class Engine {
+ public:
+  void begin(const EngineModel *desc, GPIOPin *cs, GPIOPin *dc, GPIOPin *rst, GPIOPin *busy, EpdSPIDevice *spi) {
+    this->desc_ = desc;
+    this->cs_ = cs;
+    this->dc_ = dc;
+    this->rst_ = rst;
+    this->busy_ = busy;
+    this->spi_ = spi;
+    this->cs_->setup();
+    this->dc_->setup();
+    if (this->rst_ != nullptr)
+      this->rst_->setup();
+    if (this->busy_ != nullptr)
+      this->busy_->setup();
+    this->cs_->digital_write(true);
+    this->dc_->digital_write(true);
+  }
+
+  // Arms the state machine; returns immediately. planes[1] is ignored when
+  // desc->plane_count == 1. Undefined to call while !idle().
+  void request_full_update(const uint8_t *plane0, const uint8_t *plane1) {
+    this->arm_full_update_(plane0, plane1, this->rst_ != nullptr ? State::RESET_LOW : State::INIT_CMD);
+  }
+
+#ifdef USE_ZEPD_DIAGNOSTICS
+  // Dev-time diagnostic, compiled out unless the adapter's `diagnostics:
+  // true` is set: arms a full update starting at INIT_CMD, skipping the
+  // reset pulse entirely - the same path a panel with no reset pin wired
+  // already takes every cycle. Lets a bench test use the screen as the
+  // oracle for "is the panel actually non-responsive right now" (e.g. right
+  // after hibernate()): if a distinct pattern drawn this way does NOT
+  // appear, the prior power call really did take the panel off-line; a
+  // normal request_full_update() right after (reset pulse included) should
+  // then wake it and render correctly.
+  void diag_request_update_no_reset(const uint8_t *plane0, const uint8_t *plane1) {
+    this->arm_full_update_(plane0, plane1, State::INIT_CMD);
+  }
+#endif
+
+  // Arms a standalone powerOff() replay - no init/window/plane write, just
+  // the captured power_off_sequence (if any) then DONE. Safe to call any
+  // time, including mid-refresh: see begin_power_down_() below for why that
+  // matters. Safe to call repeatedly: GxEPD2's own powerOff() is itself
+  // guarded on "already off," which the capture already baked in.
+  void request_power_off() { this->begin_power_down_(false); }
+
+  // Arms a standalone hibernate() replay: power_off_sequence then
+  // hibernate_sequence (the deep-sleep trigger only - see engine_model.h).
+  // See begin_power_down_() below for the mid-refresh case. No paired "wake"
+  // call exists or is needed: request_full_update()'s RESET_LOW is an
+  // unconditional hardware reset pulse every cycle, which is exactly how
+  // GxEPD2 wakes a hibernating (RST-wakeable) panel.
+  void request_hibernate() { this->begin_power_down_(true); }
+
+  bool idle() const { return this->state_ == State::IDLE; }
+
+  // Called once per loop() tick. Does one bounded unit of work.
+  void step() {
+    switch (this->state_) {
+      case State::IDLE:
+        return;
+      case State::RESET_LOW:
+        this->rst_->digital_write(true);  // preset high, then pulse low - see GxEPD2_EPD::_reset()
+        this->deadline_ = millis() + 10;
+        this->set_state_(State::RESET_LOW_WAIT);
+        return;
+      case State::RESET_LOW_WAIT:
+        if (millis() < this->deadline_)
+          return;
+        this->rst_->digital_write(false);
+        this->deadline_ = millis() + 10;
+        this->set_state_(State::RESET_HIGH_WAIT);
+        return;
+      case State::RESET_HIGH_WAIT:
+        if (millis() < this->deadline_)
+          return;
+        this->rst_->digital_write(true);
+        this->deadline_ = millis() + 10;
+        this->set_state_(State::RESET_SETTLE);
+        return;
+      case State::RESET_SETTLE:
+        if (millis() < this->deadline_)
+          return;
+        this->cursor_ = 0;
+        this->cmd_phase_ = CmdPhase::BEFORE_DELAY;
+        // Post-reset busy wait, matching every vendor _InitDisplay()'s
+        // _waitWhileBusy() right after the reset pulse. Some controllers hold
+        // BUSY while they load settings/waveforms from OTP after a hardware
+        // reset (notably JD79676 / GDEY0213F52, whose init is otherwise just
+        // 0xE9 + power-on) - issuing any command before that clears gets it
+        // silently dropped, so the panel never refreshes. Panels that don't
+        // assert BUSY post-reset read "not busy" on the first poll and fall
+        // straight through to INIT_CMD, so this is safe for all of them.
+        // begin_power_down_()'s abort path sets reset_then_wait_busy_ to
+        // false instead - see there for why.
+        if (this->reset_then_wait_busy_) {
+          this->start_busy_wait_(this->reset_done_next_);
+        } else {
+          this->set_state_(this->reset_done_next_);
+        }
+        return;
+
+      case State::INIT_CMD:
+        this->step_sequence_(this->desc_->init_sequence, this->desc_->init_sequence_len, State::INIT_CMD,
+                              State::SET_WINDOW);
+        return;
+
+      case State::SET_WINDOW:
+        // window_sequence[this->plane_]: index 0 on the first entry
+        // (plane_ reset to 0 in request_full_update()); when
+        // window_per_plane is true, step_write_plane_() re-enters this
+        // state with plane_ already advanced to 1 before the next plane's
+        // byte burst, picking window_sequence[1] instead.
+        this->step_sequence_(this->desc_->window_sequence[this->plane_], this->desc_->window_sequence_len[this->plane_],
+                              State::SET_WINDOW, State::WRITE_PLANE);
+        return;
+
+      case State::WRITE_PLANE:
+        this->step_write_plane_();
+        return;
+
+      case State::REFRESH_CMD:
+        this->step_sequence_(this->desc_->refresh_sequence, this->desc_->refresh_sequence_len, State::REFRESH_CMD,
+                              State::DONE);
+        return;
+
+      case State::POWER_OFF_CMD:
+        // request_hibernate() routes through here first (hibernate() is
+        // itself powerOff() + one more command on every GxEPD2 driver) -
+        // done_state branches to HIBERNATE_CMD only then.
+        this->step_sequence_(this->desc_->power_off_sequence, this->desc_->power_off_sequence_len,
+                              State::POWER_OFF_CMD, this->hibernating_ ? State::HIBERNATE_CMD : State::DONE);
+        return;
+
+      case State::HIBERNATE_CMD:
+        this->step_sequence_(this->desc_->hibernate_sequence, this->desc_->hibernate_sequence_len,
+                              State::HIBERNATE_CMD, State::DONE);
+        return;
+
+      case State::POST_DELAY:
+        if (millis() < this->deadline_)
+          return;
+        this->set_state_(this->delay_return_state_);
+        return;
+
+      case State::WAIT_BUSY:
+        this->step_wait_busy_();
+        return;
+
+      case State::DONE:
+        ESP_LOGD("zepd", "Display update finished");
+        this->set_state_(State::IDLE);
+        return;
+
+      case State::ABORTED:
+        // A busy timeout means the panel isn't behaving as wired/expected
+        // (unplugged, dead, wrong busy polarity, ...) - pressing ahead
+        // with the rest of the sequence (more command bytes, another
+        // busy-wait) is very unlikely to "just work" and only obscures
+        // which step actually failed. Bail the whole cycle here instead of
+        // continuing to whatever state the timed-out wait was headed to.
+        ESP_LOGE("zepd", "Aborting display update: busy timeout");
+        this->cursor_ = 0;
+        this->plane_ = 0;
+        this->cmd_phase_ = CmdPhase::BEFORE_DELAY;
+        this->set_state_(State::IDLE);
+        return;
+    }
+  }
+
+ private:
+  // State/CmdPhase must come before arm_full_update_() below: a member
+  // function's PARAMETER types (unlike its body) are resolved at the point
+  // of declaration, not deferred to complete-class context, so `State` has
+  // to already be a known type by the time arm_full_update_()'s signature is
+  // parsed.
+  enum class State {
+    IDLE,
+    RESET_LOW,
+    RESET_LOW_WAIT,
+    RESET_HIGH_WAIT,
+    RESET_SETTLE,
+    INIT_CMD,
+    SET_WINDOW,
+    WRITE_PLANE,
+    REFRESH_CMD,
+    POWER_OFF_CMD,
+    HIBERNATE_CMD,
+    POST_DELAY,
+    WAIT_BUSY,
+    DONE,
+    ABORTED,
+  };
+  enum class CmdPhase { BEFORE_DELAY, ISSUE };
+
+  // Shared by request_full_update() and (dev builds only) the no-reset
+  // diagnostic path above - identical setup, different starting state.
+  void arm_full_update_(const uint8_t *plane0, const uint8_t *plane1, State start_state) {
+    this->planes_[0] = plane0;
+    this->planes_[1] = plane1;
+    uint32_t w = this->desc_->window_per_plane ? this->desc_->plane_width : this->desc_->width;
+    // width*height*bpp/8: /8 at 1bpp, /4 at 2bpp, /2 at 4bpp.
+    this->plane_bytes_ = (uint32_t) w * this->desc_->height * this->desc_->bits_per_pixel / 8;
+    this->bytes_per_row_ = this->plane_bytes_ / this->desc_->height;
+    // Wire length can exceed the buffer: PAIRED_EDGES sends each row twice
+    // (2x-height RAM). plane_bytes_ stays the real buffer size; wire_bytes_
+    // is what actually goes out on 0x10/0x24/... per plane.
+    uint32_t wire_lines = this->desc_->height;
+    if (this->desc_->line_order == LineOrder::PAIRED_EDGES)
+      wire_lines *= 2;
+    this->wire_bytes_ = wire_lines * this->bytes_per_row_;
+    this->cursor_ = 0;
+    this->plane_ = 0;
+    this->cmd_phase_ = CmdPhase::BEFORE_DELAY;
+    // Normal reset path: post-reset busy wait (see RESET_SETTLE below), then
+    // the real init sequence - this->reset_done_next_/reset_then_wait_busy_
+    // are only ever overridden by begin_power_down_()'s abort path.
+    this->reset_done_next_ = State::INIT_CMD;
+    this->reset_then_wait_busy_ = true;
+    this->set_state_(start_state);
+  }
+
+  // Shared by request_power_off()/request_hibernate(). Most controllers
+  // ignore new commands outright while BUSY is asserted, so writing
+  // power_off_sequence/hibernate_sequence straight over a cycle that's still
+  // mid-refresh would silently do nothing - the panel never actually powers
+  // down, it just keeps running the update it was already doing. If a reset
+  // pin is wired, force a hardware reset pulse first (the same one
+  // request_full_update() issues every normal cycle) to abort whatever's in
+  // flight and bring the controller back to a known, command-accepting
+  // state before sending the power-down sequence - skipping the post-reset
+  // busy wait that a real update takes, since this is an emergency path
+  // that can't afford to stall on busy_timeout_ms. Without a reset pin
+  // there's no way to interrupt a busy controller, so this is best-effort
+  // in that case: jamming the state machine straight to POWER_OFF_CMD, same
+  // as calling this while idle.
+  void begin_power_down_(bool hibernating) {
+    this->cursor_ = 0;
+    this->plane_ = 0;
+    this->cmd_phase_ = CmdPhase::BEFORE_DELAY;
+    this->hibernating_ = hibernating;
+    if (this->state_ != State::IDLE && this->rst_ != nullptr) {
+      this->reset_done_next_ = State::POWER_OFF_CMD;
+      this->reset_then_wait_busy_ = false;
+      this->set_state_(State::RESET_LOW);
+    } else {
+      this->set_state_(State::POWER_OFF_CMD);
+    }
+  }
+
+  // Every command byte and every data byte is its own SPI transaction, CS
+  // toggled around each one - this looks wasteful, but it's mechanically
+  // what GxEPD2_EPD::_writeCommand()/_writeData(uint8_t) do (see
+  // third_party/GxEPD2/src/GxEPD2_EPD.cpp), and matching the vendor cycle
+  // byte-for-byte is the point of this engine.
+  void write_byte_(uint8_t b, bool dc_high) {
+    this->dc_->digital_write(dc_high);
+    this->spi_->enable();
+    this->cs_->digital_write(false);
+    this->spi_->write_byte(b);
+    this->cs_->digital_write(true);
+    this->spi_->disable();
+  }
+
+  void write_command_(uint8_t cmd, const uint8_t *data, uint8_t data_len) {
+#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_DEBUG
+    // Command-level skeleton trace - deliberately left in (not gated to
+    // VERY_VERBOSE): the exact byte-for-byte counterpart to compare against
+    // a captured reference trace on the same panel. Bulk plane data isn't
+    // logged here (see step_write_plane_) - only the command skeleton
+    // matters for that comparison.
+    char buf[32] = {0};
+    int n = 0;
+    for (uint8_t i = 0; i < data_len && n < (int) sizeof(buf) - 3; i++)
+      n += snprintf(buf + n, sizeof(buf) - n, "%02X ", data[i]);
+    ESP_LOGD("zepd", "cmd 0x%02X data[%u]: %s", cmd, data_len, buf);
+#endif
+    this->write_byte_(cmd, false);
+    for (uint8_t i = 0; i < data_len; i++)
+      this->write_byte_(data[i], true);
+  }
+
+  // Steps through one EpdCommand table one entry (and one delay/busy-wait,
+  // if that entry has one) at a time, resuming in self_state after any
+  // wait so the same call re-enters here for the next entry. Shared by
+  // INIT_CMD and REFRESH_CMD - which table is being stepped is entirely
+  // determined by which state called this.
+  void step_sequence_(const EpdCommand *seq, uint8_t len, State self_state, State done_state) {
+    if (this->cursor_ >= len) {
+      this->cursor_ = 0;
+      this->cmd_phase_ = CmdPhase::BEFORE_DELAY;
+      this->set_state_(done_state);
+      return;
+    }
+    const EpdCommand &c = seq[this->cursor_];
+    if (this->cmd_phase_ == CmdPhase::BEFORE_DELAY) {
+      this->cmd_phase_ = CmdPhase::ISSUE;
+      if (c.delay_before_ms > 0) {
+        this->start_delay_(c.delay_before_ms, self_state);
+        return;
+      }
+    }
+    this->write_command_(c.cmd, c.data, c.data_len);
+    this->cursor_++;
+    this->cmd_phase_ = CmdPhase::BEFORE_DELAY;
+    if (c.wait_busy_after) {
+      this->start_busy_wait_(self_state);
+    } else if (c.delay_after_ms > 0) {
+      this->start_delay_(c.delay_after_ms, self_state);
+    }
+    // else: stays in self_state; the next step() call processes the next entry.
+  }
+
+  // Writes up to BYTE_BUDGET bytes of the current plane per call, then
+  // returns - this bound is what keeps a full-frame write (thousands of
+  // bytes) from ever making one loop() tick run long.
+  //
+  // 16384 allows up to ~25ms of blocking per step; the dominant cost is
+  // write_byte_()'s per-byte SPI enable()/disable() (ESP-IDF transaction
+  // setup/teardown), intentionally NOT batched away: it lets other devices
+  // on a shared spi: bus interleave between our bytes instead of being
+  // locked out for the whole burst.
+  static constexpr uint32_t BYTE_BUDGET = 16384;
+
+  void step_write_plane_() {
+    if (this->cursor_ == 0) {
+      const uint8_t *buf = this->planes_[this->plane_];
+      uint32_t histo[3] = {0, 0, 0};  // [0]=0x00, [1]=0xFF, [2]=other
+      if (buf != nullptr) {
+        for (uint32_t i = 0; i < this->plane_bytes_; i++) {
+          if (buf[i] == 0x00)
+            histo[0]++;
+          else if (buf[i] == 0xFF)
+            histo[1]++;
+          else
+            histo[2]++;
+        }
+      }
+      ESP_LOGD("zepd", "plane %u: cmd 0x%02X, %u wire bytes (buf %u), invert=%d, buf[0]=0x%02X buf[last]=0x%02X, histo(00/FF/other)=%u/%u/%u",
+               this->plane_, this->desc_->plane_write_cmd[this->plane_], (unsigned) this->wire_bytes_,
+               (unsigned) this->plane_bytes_, this->desc_->plane_invert[this->plane_], buf != nullptr ? buf[0] : 0,
+               buf != nullptr ? buf[this->plane_bytes_ - 1] : 0, (unsigned) histo[0], (unsigned) histo[1],
+               (unsigned) histo[2]);
+      this->write_byte_(this->desc_->plane_write_cmd[this->plane_], false);
+    }
+    const uint8_t *buf = this->planes_[this->plane_];
+    bool invert = this->desc_->plane_invert[this->plane_];
+    uint32_t end = this->cursor_ + BYTE_BUDGET;
+    if (end > this->wire_bytes_)
+      end = this->wire_bytes_;
+    for (; this->cursor_ < end; this->cursor_++) {
+      uint32_t src = this->line_src_index_(this->cursor_);
+      uint8_t b = buf != nullptr ? buf[src] : 0xFF;
+      this->write_byte_(invert ? static_cast<uint8_t>(~b) : b, true);
+    }
+    if (this->cursor_ >= this->wire_bytes_) {
+      this->cursor_ = 0;
+      this->plane_++;
+      this->cmd_phase_ = CmdPhase::BEFORE_DELAY;
+      if (this->plane_ >= this->desc_->plane_count) {
+        this->plane_ = 0;
+        this->set_state_(State::REFRESH_CMD);
+      } else if (this->desc_->window_per_plane) {
+        // Another plane to go and it needs its own window-set first (a
+        // genuinely separate physical RAM region, not just another color
+        // plane sharing the window already set) - re-enter SET_WINDOW,
+        // which will pick window_sequence[this->plane_] now that plane_
+        // has already advanced.
+        this->set_state_(State::SET_WINDOW);
+      }
+      // else: more planes, sharing one window already set - stay in
+      // WRITE_PLANE, next step() call starts the next plane's byte burst.
+    }
+  }
+
+  // Maps a wire-transmission-order byte position (0..wire_bytes_-1) to the
+  // buffer byte it reads. The wire is a sequence of lines, each bytes_per_row_
+  // bytes from one buffer row; line_order picks which buffer row each wire
+  // line carries (and, for PAIRED_EDGES, there are 2x as many wire lines as
+  // buffer rows). SEQUENTIAL is the identity (wire line i -> row i).
+  uint32_t line_src_index_(uint32_t wire_pos) const {
+    uint32_t wire_line = wire_pos / this->bytes_per_row_;
+    uint32_t byte_in_line = wire_pos % this->bytes_per_row_;
+    uint32_t buf_row;
+    switch (this->desc_->line_order) {
+      case LineOrder::PAIRED_EDGES: {
+        // wire lines come in pairs: for i in [0,H), line 2i = row (H-1-i),
+        // line 2i+1 = row i. Matches GxEPD2 writeNative's emission exactly.
+        uint32_t i = wire_line / 2;
+        buf_row = (wire_line % 2 == 0) ? (this->desc_->height - 1 - i) : i;
+        break;
+      }
+      case LineOrder::SEQUENTIAL:
+      default:
+        buf_row = wire_line;
+        break;
+    }
+    return buf_row * this->bytes_per_row_ + byte_in_line;
+  }
+
+  void start_delay_(uint16_t delay_ms, State return_to) {
+    this->deadline_ = millis() + delay_ms;
+    this->delay_return_state_ = return_to;
+    this->set_state_(State::POST_DELAY);
+  }
+
+  void start_busy_wait_(State next) {
+    this->busy_wait_next_ = next;
+    this->busy_wait_deadline_ = millis() + this->desc_->busy_timeout_ms;
+    this->set_state_(State::WAIT_BUSY);
+  }
+
+  void step_wait_busy_() {
+    if (this->busy_ == nullptr) {
+      this->set_state_(this->busy_wait_next_);
+      return;
+    }
+    bool busy = this->busy_->digital_read() == this->desc_->busy_active_level;
+    if (!busy) {
+      this->set_state_(this->busy_wait_next_);
+      return;
+    }
+    if (millis() >= this->busy_wait_deadline_) {
+      ESP_LOGW("zepd", "Busy timeout waiting for panel");
+      this->set_state_(State::ABORTED);
+    }
+  }
+
+  // Logs every state transition (only when the state actually changes -
+  // WAIT_BUSY and POST_DELAY re-enter their own case on every step() call
+  // while polling, which would otherwise spam this at loop() rate) so a
+  // first hardware run can be checked against the vendor cycle it's meant
+  // to replicate before this gets dialed back to WARN-only.
+  void set_state_(State s) {
+    if (s != this->state_)
+      ESP_LOGD("zepd", "state: %s -> %s", state_name_(this->state_), state_name_(s));
+    this->state_ = s;
+  }
+
+  static const char *state_name_(State s) {
+    switch (s) {
+      case State::IDLE:
+        return "IDLE";
+      case State::RESET_LOW:
+        return "RESET_LOW";
+      case State::RESET_LOW_WAIT:
+        return "RESET_LOW_WAIT";
+      case State::RESET_HIGH_WAIT:
+        return "RESET_HIGH_WAIT";
+      case State::RESET_SETTLE:
+        return "RESET_SETTLE";
+      case State::INIT_CMD:
+        return "INIT_CMD";
+      case State::SET_WINDOW:
+        return "SET_WINDOW";
+      case State::WRITE_PLANE:
+        return "WRITE_PLANE";
+      case State::REFRESH_CMD:
+        return "REFRESH_CMD";
+      case State::POWER_OFF_CMD:
+        return "POWER_OFF_CMD";
+      case State::HIBERNATE_CMD:
+        return "HIBERNATE_CMD";
+      case State::POST_DELAY:
+        return "POST_DELAY";
+      case State::WAIT_BUSY:
+        return "WAIT_BUSY";
+      case State::DONE:
+        return "DONE";
+      case State::ABORTED:
+        return "ABORTED";
+    }
+    return "?";
+  }
+
+  const EngineModel *desc_{nullptr};
+  GPIOPin *cs_{nullptr};
+  GPIOPin *dc_{nullptr};
+  GPIOPin *rst_{nullptr};
+  GPIOPin *busy_{nullptr};
+  EpdSPIDevice *spi_{nullptr};
+
+  State state_{State::IDLE};
+  uint32_t cursor_{0};
+  CmdPhase cmd_phase_{CmdPhase::BEFORE_DELAY};
+  uint8_t plane_{0};
+  const uint8_t *planes_[2]{nullptr, nullptr};
+  uint32_t plane_bytes_{0};   // real buffer size per plane
+  uint32_t wire_bytes_{0};    // bytes actually sent per plane (>= plane_bytes_)
+  uint32_t bytes_per_row_{0};
+  uint32_t deadline_{0};
+  State reset_done_next_{State::INIT_CMD};  // RESET_SETTLE's continuation - see arm_full_update_()/begin_power_down_()
+  bool reset_then_wait_busy_{true};         // false only for begin_power_down_()'s abort path
+  State delay_return_state_{State::DONE};
+  uint32_t busy_wait_deadline_{0};
+  State busy_wait_next_{State::DONE};
+  bool hibernating_{false};  // POWER_OFF_CMD's done_state: HIBERNATE_CMD if set, else DONE
+};
+
+}  // namespace esphome::zepd

+ 187 - 0
esphome-zepd/components/zepd/engine_model.h

@@ -0,0 +1,187 @@
+#pragma once
+
+#include <cstdint>
+
+namespace esphome::zepd {
+
+// One command byte plus its (fixed, compile-time) data bytes, as sent by
+// GxEPD2_EPD::_writeCommand()/_writeData(). delay_before_ms/delay_after_ms
+// and wait_busy_after mirror the fixed delay()s and _waitWhileBusy() calls
+// bracketing specific commands in the vendor source (which command gets
+// which varies per panel - e.g. GxEPD2_213_Z98c delays 10ms on both sides
+// of its SWRESET, while GxEPD2_154_Z90c busy-waits after its SWRESET
+// instead). At most one of delay_after_ms/wait_busy_after is expected to be
+// set on any one command.
+struct EpdCommand {
+  uint8_t cmd;
+  const uint8_t *data;  // nullptr if the command takes no data bytes
+  uint8_t data_len;
+  uint16_t delay_before_ms{0};
+  uint16_t delay_after_ms{0};
+  bool wait_busy_after{false};
+};
+
+// One palette entry for a packed (bits_per_pixel > 1) panel: a reference
+// RGB color (ESPHome Color space, 0-255 per channel) and the wire code the
+// controller uses for it. Classification at draw time picks the entry
+// nearest the drawn color, with exact matches winning - so named colors map
+// deterministically, the way GxEPD2's own color4()/color7() switch does.
+// Several entries may share a code (GxEPD2 maps green and orange both onto
+// the 4-color yellow code, and blue onto black).
+struct EpdPaletteEntry {
+  uint8_t r, g, b;
+  uint8_t code;
+};
+
+// Standard GxEPD2 4-color (BWRY) palette - codes per GxEPD2_4C.h color4():
+// black=0x00, white=0x01, yellow/green/orange=0x02, red=0x03, blue->black.
+inline const EpdPaletteEntry PALETTE_4C[] = {
+    {0x00, 0x00, 0x00, 0x00},  // black
+    {0xFF, 0xFF, 0xFF, 0x01},  // white
+    {0xFF, 0xFF, 0x00, 0x02},  // yellow
+    {0x00, 0xFF, 0x00, 0x02},  // green  -> yellow code
+    {0xFF, 0xA4, 0x00, 0x02},  // orange -> yellow code
+    {0xFF, 0x00, 0x00, 0x03},  // red
+    {0x00, 0x00, 0xFF, 0x00},  // blue   -> black code
+};
+inline const uint8_t PALETTE_4C_LEN = sizeof(PALETTE_4C) / sizeof(PALETTE_4C[0]);
+
+// Standard ACeP 7-color palette - codes per GxEPD2_7C.h color7(): black=0x00,
+// white=0x01, green=0x02, blue=0x03, red=0x04, yellow=0x05, orange=0x06.
+inline const EpdPaletteEntry PALETTE_7C[] = {
+    {0x00, 0x00, 0x00, 0x00},  // black
+    {0xFF, 0xFF, 0xFF, 0x01},  // white
+    {0x00, 0xFF, 0x00, 0x02},  // green
+    {0x00, 0x00, 0xFF, 0x03},  // blue
+    {0xFF, 0x00, 0x00, 0x04},  // red
+    {0xFF, 0xFF, 0x00, 0x05},  // yellow
+    {0xFF, 0xA4, 0x00, 0x06},  // orange
+};
+inline const uint8_t PALETTE_7C_LEN = sizeof(PALETTE_7C) / sizeof(PALETTE_7C[0]);
+
+// Everything the engine needs to drive one panel - this is the codegen'd
+// "engine model" produced from a model's drivers/<model>.json (see
+// ../../../../claude/DESCRIPTOR_REGISTRY_PLAN.md), hand-derived today from a
+// GxEPD2 vendor driver's .cpp/.h the same way the legacy
+// components/gxepd2/panel_*.h files were. Only what the engine actually
+// uses - the RAM-window-set command layout (0x44/0x45/0x4E/0x4F) is common
+// to every panel inspected so far and is hardcoded in Engine itself rather
+// than made part of this struct; revisit if/when a controller family turns
+// up that lays it out differently.
+//
+// Order in which the engine emits a plane's wire lines, derived by the diag
+// native-path tool. The buffer always holds `height` rows of real pixels;
+// this controls only which buffer row each wire line carries and how many
+// wire lines there are, so wire length can exceed buffer size.
+//   SEQUENTIAL   - wire line i carries buffer row i; line count == height.
+//                  Every single-region panel captured so far.
+//   PAIRED_EDGES - the controller fills a 2x-height RAM scanned from both
+//                  edges toward the middle: for i in [0,height) it wants
+//                  buffer row (height-1-i) then row i, so line count ==
+//                  2*height and each row is sent twice. GDEY0579F51 / HX8717.
+//                  This is exactly what GxEPD2's writeNative emits for that
+//                  panel (99 bytes/line x 544 lines/region), so a faithful
+//                  replay needs it - nothing panel-specific in the engine.
+enum class LineOrder : uint8_t { SEQUENTIAL, PAIRED_EDGES };
+
+struct EngineModel {
+  uint16_t width;
+  uint16_t height;
+  bool busy_active_level;    // digitalRead() level meaning "still busy"
+  uint32_t busy_timeout_ms;  // ceiling for every busy wait (init and refresh alike)
+
+  const EpdCommand *init_sequence;  // run once, after the reset pulse
+  uint8_t init_sequence_len;
+
+  // Sets the (always full-frame, since this engine has no partial-window
+  // support) RAM addressing window. window_sequence[0] runs once after
+  // init_sequence and before the first plane's byte burst; index 1 is only
+  // used when window_per_plane is true (see below). Was hardcoded assuming
+  // every controller shares SSD1680's 0x44/0x45/0x4E/0x4F byte-column
+  // layout - GxEPD2_426_GDEQ0426T82 (SSD1677) turned out to address in raw
+  // pixels with reversed Y and re-issues its entry-mode command here, and
+  // GxEPD2_583_GDEQ0583T31 (UC8179) uses one 0x90 command bracketed by
+  // 0x91/0x92 markers instead. Made per-model data, same as init/refresh,
+  // rather than special-cased in the engine.
+  const EpdCommand *window_sequence[2];
+  uint8_t window_sequence_len[2];
+
+  // true if each plane needs window_sequence[plane index] re-run before
+  // its own byte burst, instead of one window_sequence[0] covering every
+  // plane's burst (the default, e.g. a BW+red panel's shared full-frame
+  // window). This is how a panel with real master/slave regions (two
+  // genuinely separate physical RAM windows, not just two color planes
+  // sharing one) is handled - "plane" here just means "one more buffer
+  // with its own byte burst," which happens to fit a two-physical-region
+  // panel as well as a two-color-plane one.
+  bool window_per_plane{false};
+
+  uint8_t plane_count;          // 1 (BW), 2 (BW + accent color), or 2 physical regions
+  uint8_t plane_write_cmd[2];   // e.g. {0x24, 0x26}
+
+  // The extra "previous RAM bank" write GxEPD2's writeImageForFullRefresh()
+  // makes that plain writeImage() doesn't, on controllers where the two
+  // diverge (SSD1680/SSD1681/SSD1619-family: 0x26 then 0x24, or 0x10 then
+  // 0x13 - same bitmap written twice, to two different commands). 0x00 (the
+  // default) means no divergence was observed: writeImageForFullRefresh
+  // falls back to writeImage for that controller, the common case. NOT read
+  // by Engine today - this engine always does a plain single write per
+  // plane, correct for full-refresh-only operation, since the full-refresh
+  // waveform doesn't depend on the "previous" bank's content. It matters
+  // once partial refresh reads that bank to compute its diff, so it's
+  // captured now rather than needing a second capture pass later.
+  uint8_t plane_write_cmd_for_full_refresh[2]{0, 0};
+
+  bool plane_invert[2];         // true if the byte must be bit-inverted on write
+
+  // When window_per_plane is true, each plane's own buffer is sized for
+  // this width, not the descriptor's overall `width` (which is the full
+  // logical canvas the adapter draws into) - e.g. 396 for GDEY0579F51's
+  // master/slave halves, each 396x272 on its own, not the full 792x272.
+  // Unused otherwise.
+  uint16_t plane_width{0};
+
+  // Wire-line emission order for this panel's plane(s) - see LineOrder
+  // above. Default SEQUENTIAL; PAIRED_EDGES is not assumed for any panel
+  // without the diag native-path tool deriving it.
+  LineOrder line_order{LineOrder::SEQUENTIAL};
+
+  // Pixel bit-depth, which also selects the buffer model:
+  //   1 = one-bit-per-pixel plane model (mono, or BW + accent as two
+  //       separate 1bpp planes). plane_invert applies; palette is unused.
+  //   2 = packed 4-color: 2 bits/pixel, 4 pixels/byte, MSB-first.
+  //   4 = packed 7-color (ACeP): 4 bits/pixel, 2 pixels/byte, MSB-first.
+  // For bits_per_pixel > 1 the buffer is a single packed code-per-pixel
+  // stream (per region when window_per_plane), sized width*height*bpp/8,
+  // and each pixel's wire code comes from `palette` (nearest-color
+  // classification at draw time) rather than the 1bpp plane bitmasks;
+  // plane_invert is unused.
+  uint8_t bits_per_pixel{1};
+
+  // Packed-mode (bits_per_pixel > 1) palette and the wire code the buffer is
+  // cleared to (the panel's white/blank). Unused when bits_per_pixel == 1.
+  // See PALETTE_4C / PALETTE_7C.
+  const EpdPaletteEntry *palette{nullptr};
+  uint8_t palette_len{0};
+  uint8_t blank_code{0};
+
+  const EpdCommand *refresh_sequence;  // e.g. 0x22/0xF7 then trigger 0x20
+  uint8_t refresh_sequence_len;
+
+  // powerOff()/hibernate(), captured the same way as refresh_sequence.
+  // Exposed for a user's own lambda (Engine::request_power_off/
+  // request_hibernate), not run automatically by update(): this engine does
+  // a full hardware reset on every cycle regardless of prior power state,
+  // so correctness never depends on calling either. hibernate_sequence is
+  // the deep-sleep trigger ONLY (every GxEPD2 driver's hibernate() is
+  // powerOff() + one more command when rst is wired) - Engine runs
+  // power_off_sequence first, then hibernate_sequence, to replay the same
+  // two-step effect. Both nullptr/0 (not yet captured) is a safe no-op:
+  // Engine treats a zero-length sequence as already done.
+  const EpdCommand *power_off_sequence{nullptr};
+  uint8_t power_off_sequence_len{0};
+  const EpdCommand *hibernate_sequence{nullptr};  // deep-sleep trigger only, after power_off_sequence
+  uint8_t hibernate_sequence_len{0};
+};
+
+}  // namespace esphome::zepd

+ 72 - 0
esphome-zepd/components/zepd/registry.py

@@ -0,0 +1,72 @@
+"""The zEPD model registry: loads drivers/*.json and merges each named model
+over default.json.
+
+Pure Python, no ESPHome dependency - see claude/DESCRIPTOR_REGISTRY_PLAN.md.
+Both display.py (at ESPHome compile time) and standalone host tooling
+(check_descriptors.py and friends) import this module directly.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Any
+
+DRIVERS_DIR = Path(__file__).parent / "drivers"
+
+
+def _merge(base: Any, overlay: Any) -> Any:
+    """Recursive dict merge. Named dict keys merge recursively; anything
+    anonymous/positional (list elements) replaces whole. A key present in
+    `overlay` but not in `base` is dropped silently - the accumulated
+    `base` (built up from default.json first) is the implicit schema."""
+    if isinstance(base, dict) and isinstance(overlay, dict):
+        out = dict(base)
+        for key, value in overlay.items():
+            if key in out:
+                out[key] = _merge(out[key], value)
+            # else: unknown key, dropped - see unknown_keys() for a warning pass.
+        return out
+    return overlay
+
+
+def unknown_keys(base: dict, overlay: dict, prefix: str = "") -> list[str]:
+    """Dotted-path keys present in `overlay` that don't exist anywhere in
+    `base` - a likely typo, surfaced as a warning (not an error) by callers."""
+    found: list[str] = []
+    for key, value in overlay.items():
+        path = f"{prefix}.{key}" if prefix else key
+        if key not in base:
+            found.append(path)
+        elif isinstance(base.get(key), dict) and isinstance(value, dict):
+            found.extend(unknown_keys(base[key], value, path))
+    return found
+
+
+def load_default(drivers_dir: Path = DRIVERS_DIR) -> dict:
+    with open(drivers_dir / "default.json") as f:
+        return json.load(f)
+
+
+def load_model(name: str, drivers_dir: Path = DRIVERS_DIR, overlay: dict | None = None) -> dict:
+    """Load one model: default.json, then drivers/<name>.json (skipped when
+    name == "default"), then an optional YAML-provided overlay dict."""
+    merged = load_default(drivers_dir)
+    if name != "default":
+        path = drivers_dir / f"{name}.json"
+        with open(path) as f:
+            model_json = json.load(f)
+        unk = unknown_keys(merged, model_json)
+        if unk:
+            print(f"warning: {path}: unknown key(s), possible typo: {', '.join(unk)}")
+        merged = _merge(merged, model_json)
+    if overlay:
+        unk = unknown_keys(merged, overlay)
+        if unk:
+            print(f"warning: model_overlay for {name!r}: unknown key(s), possible typo: {', '.join(unk)}")
+        merged = _merge(merged, overlay)
+    return merged
+
+
+def list_models(drivers_dir: Path = DRIVERS_DIR) -> list[str]:
+    return sorted(p.stem for p in drivers_dir.glob("*.json") if p.stem != "default")

+ 455 - 0
esphome-zepd/components/zepd/zepd_display.h

@@ -0,0 +1,455 @@
+#pragma once
+
+#include "esphome/core/component.h"
+#include "esphome/core/helpers.h"
+#include "esphome/components/display/display_buffer.h"
+#include "esphome/components/spi/spi.h"
+#include "engine.h"
+#include "engine_model.h"
+#include "zepd_model_generated.h"
+
+namespace esphome::zepd {
+
+static const char *const TAG = "zepd";
+
+// ESPHome display component (the engine adapter) for a zEPD model. The
+// model arrives as one codegen'd zepd::EngineModel, selected at ESPHome
+// compile time by display.py from the drivers/*.json registry (see
+// claude/DESCRIPTOR_REGISTRY_PLAN.md) and written to
+// zepd_model_generated.h - not templated over per-panel C++ classes the
+// way GxEPD2 itself is. Driven by zepd::Engine, the generic replay state
+// machine; this class is the ESPHome-side half of the engine adapter.
+class ZepdDisplay : public display::DisplayBuffer {
+ public:
+  void set_cs_pin(GPIOPin *pin) { this->cs_ = pin; }
+  void set_dc_pin(GPIOPin *pin) { this->dc_ = pin; }
+  void set_reset_pin(GPIOPin *pin) { this->rst_ = pin; }
+  void set_busy_pin(GPIOPin *pin) { this->busy_ = pin; }
+  void set_spi_parent(spi::SPIComponent *parent) { this->spi_.set_spi_parent(parent); }
+  void set_descriptor(const EngineModel *desc) { this->desc_ = desc; }
+  void set_invert_mono(bool invert) { this->invert_mono_ = invert; }
+  // The short model label test_pattern() can print, derived from the
+  // registry's oem_part_numbers[0] (see display.py).
+  void set_model_name(const char *name) { this->model_name_ = name; }
+  // Whether this model's data is confirmed on real hardware (vs captured
+  // but not yet bench-verified) - surfaced in dump_config(). From the
+  // registry's `verified` field, via display.py.
+  void set_verified(bool v) { this->verified_ = v; }
+
+  // Bench visual-check pattern, bit-depth aware. Everything scales to what
+  // THIS panel can actually show (see test_colors_): the color-bar count,
+  // the ladder color cycle and the corner markers all follow the panel's
+  // real color set instead of a hardcoded 4, so the drawn pattern doubles as
+  // a statement of what the engine model expects of the panel. Adds a
+  // dithered grey ramp so a 1bpp panel shows a graded sweep, not just two
+  // flat blocks.
+  //
+  // Pass a font to label the panel with its model (and the panel can spare the
+  // room); pass nothing to skip the label - handy when you just want a quick
+  // pattern without defining a font. From the display lambda:
+  //   id(<display_id>).test_pattern();                 // no label
+  //   id(<display_id>).test_pattern(id(<font_id>));    // labelled
+  void test_pattern(display::BaseFont *font = nullptr) {
+    const int w = this->get_width();
+    const int h = this->get_height();
+    Color colors[8];
+    const int n = this->test_colors_(colors, 8);
+
+    this->fill(Color(0xFF, 0xFF, 0xFF));
+
+    const int smin = w < h ? w : h;
+    const int border = smin / 100 > 1 ? smin / 100 : 1;
+    const int x0 = border;
+    int y0 = border;
+    const int iw = w - 2 * border;
+    int ih = h - 2 * border;
+
+    // Name band, above every test zone. Drawn only when a font was passed and
+    // the panel is tall enough to give it a fifth of the interior without
+    // crowding the zones below.
+    if (font != nullptr && this->model_name_ != nullptr && this->model_name_[0] != '\0') {
+      int tw, xoff, baseline, th;
+      font->measure(this->model_name_, &tw, &xoff, &baseline, &th);
+      const int band = th + 4;
+      if (band <= ih / 5) {
+        this->print(w / 2, y0 + band / 2, font, Color(0x00, 0x00, 0x00), display::TextAlign::CENTER, this->model_name_);
+        y0 += band;
+        ih -= band;
+      }
+    }
+
+    // Vertical budget for the four zones below any name band.
+    const int bars_h = ih * 34 / 100;
+    int dither_h = ih * 12 / 100;
+    if (dither_h < 8) dither_h = 8;
+    const int row_h = ih * 18 / 100 > 2 ? ih * 18 / 100 : 2;
+    const int dy = y0 + bars_h;
+    const int ry = dy + dither_h;
+    const int col_y = ry + row_h;
+    const int col_h = (y0 + ih) - col_y;
+
+    // Color bars: one solid block per available color, in palette/wire-code
+    // order (black, white, then the accents). A wrong or missing block
+    // points straight at the color - or the wire code - it stands for.
+    const int bar_w = iw / n;
+    for (int i = 0; i < n; i++) {
+      const int bx = x0 + i * bar_w;
+      const int bw = (i == n - 1) ? (x0 + iw - bx) : bar_w;
+      this->filled_rectangle(bx, y0, bw, bars_h, colors[i]);
+    }
+
+    // Dithered grey ramp: brightness 255 (left) -> 0 (right) via an ordered
+    // 4x4 Bayer threshold. On a 1bpp panel this is the only zone that shows
+    // a graded sweep; on deeper panels it's a quick mono/uniformity check.
+    static const uint8_t BAYER4[4][4] = {
+        {0, 8, 2, 10}, {12, 4, 14, 6}, {3, 11, 1, 9}, {15, 7, 13, 5}};
+    for (int yy = 0; yy < dither_h; yy++) {
+      for (int xx = 0; xx < iw; xx++) {
+        const int bright = (iw <= 1) ? 255 : 255 - xx * 255 / (iw - 1);
+        const int thr = (BAYER4[yy & 3][xx & 3] * 2 + 1) * 255 / 32;
+        if (bright <= thr)
+          this->draw_pixel_at(x0 + xx, dy + yy, Color(0x00, 0x00, 0x00));
+      }
+    }
+
+    // Row ladder: 1px rows cycling the full color set - a dropped, doubled
+    // or reordered row breaks the N-row cadence.
+    for (int yy = 0; yy < row_h; yy++)
+      this->horizontal_line(x0, ry + yy, iw, colors[yy % n]);
+
+    // Column ladder: the same rotated 90 degrees, catching nibble/column
+    // order bugs the row ladder can't (packed formats put several pixels per
+    // byte, so a column-order fault can leave every row looking fine).
+    for (int xx = 0; xx < iw; xx++)
+      this->vertical_line(x0 + xx, col_y, col_h, colors[xx % n]);
+
+    // Corner markers for orientation, using the panel's ink colors (every
+    // color but white). BL is always black; TL/TR take the next inks when
+    // the panel has them; BR is left blank as the distinct "no marker"
+    // state. A 90/180 rotation or mirror can't survive this even though the
+    // bars and ladders are otherwise symmetric.
+    Color ink[8];
+    int ni = 0;
+    for (int i = 0; i < n; i++) {
+      if (colors[i].red == 0xFF && colors[i].green == 0xFF && colors[i].blue == 0xFF)
+        continue;  // skip white - a white marker is invisible
+      ink[ni++] = colors[i];
+    }
+    const int mk = smin / 12 > 3 ? smin / 12 : 3;
+    if (ni > 0) this->filled_rectangle(x0, y0 + ih - mk, mk, mk, ink[0]);        // BL
+    if (ni > 1) this->filled_rectangle(x0, y0, mk, mk, ink[1]);                  // TL
+    if (ni > 2) this->filled_rectangle(x0 + iw - mk, y0, mk, mk, ink[2]);        // TR
+
+    // Corner-to-corner diagonals over everything: the cheapest coordinate-
+    // transform check - a clean line means no row/column reordering.
+    this->line(0, 0, w - 1, h - 1, Color(0x00, 0x00, 0x00));
+    this->line(w - 1, 0, 0, h - 1, Color(0x00, 0x00, 0x00));
+
+    // Border frame last, so it stays an unbroken rectangle on all four edges
+    // even where a zone fills to the edge - catches a clipped/offset origin.
+    this->rectangle(0, 0, w, h, Color(0x00, 0x00, 0x00));
+  }
+
+  void setup() override {
+    const auto *desc = this->desc_;
+    // window_per_plane panels (e.g. a master+slave dual-region panel) size
+    // each plane's own buffer from plane_width (each region's own local
+    // width), not the descriptor's overall width (the full logical canvas
+    // the adapter draws into) - both regions are the same size here, so
+    // one plane_bytes_ value covers both buffers.
+    uint32_t w = desc->window_per_plane ? desc->plane_width : desc->width;
+    // width*height*bpp/8: /8 at 1bpp, /4 at 2bpp (4-color), /2 at 4bpp (7-color).
+    this->plane_bytes_ = (uint32_t) w * desc->height * desc->bits_per_pixel / 8;
+    RAMAllocator<uint8_t> allocator;
+    this->plane0_ = allocator.allocate(this->plane_bytes_);
+    bool need_plane1 = desc->plane_count > 1;
+    this->plane1_ = need_plane1 ? allocator.allocate(this->plane_bytes_) : nullptr;
+    if (this->plane0_ == nullptr || (need_plane1 && this->plane1_ == nullptr)) {
+      ESP_LOGE(TAG, "Failed to allocate %u-byte plane buffer(s)", (unsigned) this->plane_bytes_);
+      this->mark_failed();
+      return;
+    }
+    if (desc->bits_per_pixel > 1) {
+      // Packed modes: clear every pixel to the panel's white/blank code,
+      // replicated across the byte - e.g. 4-color white=0x01 -> 0x55, 7-color
+      // white=0x01 -> 0x11, matching GxEPD2's own writeScreenBuffer() fill
+      // (color4()*0x55 / color7()|<<4). Both regions of a window_per_plane
+      // panel (master/slave) get the same blank fill.
+      uint8_t fill = replicate_code_(desc->blank_code, desc->bits_per_pixel);
+      memset(this->plane0_, fill, this->plane_bytes_);
+      if (this->plane1_ != nullptr)
+        memset(this->plane1_, fill, this->plane_bytes_);
+    } else {
+      // 1bpp plane model: plane0 white = all bits set (0xFF); plane1 (the
+      // accent/red plane, when present) = 0 = not-red.
+      memset(this->plane0_, 0xFF, this->plane_bytes_);
+      if (this->plane1_ != nullptr)
+        memset(this->plane1_, 0x00, this->plane_bytes_);
+    }
+
+    this->spi_.spi_setup();
+    this->engine_.begin(desc, this->cs_, this->dc_, this->rst_, this->busy_, &this->spi_);
+  }
+
+  // Arms the state machine and returns immediately - the real several-
+  // seconds-long write/refresh/busy-wait cycle happens across many
+  // subsequent loop() ticks, not before this call returns.
+  void update() override {
+    if (!this->engine_.idle()) {
+      ESP_LOGW(TAG, "Skipping update: previous display refresh is still running");
+      return;
+    }
+    this->do_update_();
+    this->engine_.request_full_update(this->plane0_, this->plane1_);
+  }
+
+  void loop() override { this->engine_.step(); }
+
+  // True once the engine has returned to idle after the last update()/
+  // power_off()/hibernate() call. Lets a more complex application (a lambda
+  // chaining several updates, a deep_sleep automation deciding whether to
+  // wait) check "is the panel still mid-refresh" instead of guessing from
+  // timing - the same thing power_off()/hibernate()'s own guards below check
+  // internally.
+  bool idle() const { return this->engine_.idle(); }
+
+  // Turns off the panel's driving-voltage generation (reduces fading over
+  // time between refreshes). Call from a lambda, e.g.
+  // id(<display_id>).power_off(); - not called automatically by update(),
+  // since this engine does a full hardware reset every cycle regardless of
+  // prior power state, so correctness never depends on it. (It IS called
+  // automatically from on_powerdown() below.) Safe to call mid-refresh: see
+  // zepd::Engine::request_power_off().
+  void power_off() {
+    if (!this->engine_.idle())
+      ESP_LOGW(TAG, "power_off() called mid-refresh; aborting the in-progress update");
+    this->engine_.request_power_off();
+  }
+
+  // power_off() + deep sleep, wakeable only by a hardware reset pulse - which
+  // the next update() always issues (request_full_update()'s RESET_LOW), so
+  // no paired "wake" call is needed; just call update() as usual. Safe to
+  // call mid-refresh: see zepd::Engine::request_hibernate().
+  void hibernate() {
+    if (!this->engine_.idle())
+      ESP_LOGW(TAG, "hibernate() called mid-refresh; aborting the in-progress update");
+    this->engine_.request_hibernate();
+  }
+
+  // ESPHome calls this on every component right before deep_sleep actually
+  // suspends the MCU, and on safe_reboot() - see
+  // Application::run_powerdown_hooks() (fires after teardown_components()
+  // completes or times out, deep_sleep's should_teardown_() is unconditional
+  // on every supported platform). Powers the panel down with no YAML/lambda
+  // needed for the common case: hibernate() when a reset pin is wired (the
+  // next update()'s unconditional RESET_LOW wakes it - see hibernate()
+  // above), else power_off() (needs no reset pulse to recover, so it's safe
+  // with no rst pin at all).
+  //
+  // Deliberately NOT paired with a teardown() override to wait out a
+  // mid-flight refresh: ESPHome's teardown budget (1s on reboot, 5s on deep
+  // sleep) is far shorter than this engine's slower busy_timeout_ms classes
+  // (up to 45-60s for 4bpp/7-color panels), so stalling teardown here would
+  // just lose that race every time and get force-advanced anyway - the
+  // budget is sized for a network flush (see api_server::teardown()), not a
+  // hardware operation. If a refresh is still running when this fires,
+  // power_off()/hibernate() abort it with a reset pulse first rather than
+  // writing a power-down command over a controller that's still asserting
+  // BUSY and would just ignore it (see zepd::Engine::request_power_off()). A
+  // caller who cares about that race can check idle() (above) and hold off
+  // triggering deep sleep themselves.
+  void on_powerdown() override {
+    if (this->rst_ != nullptr) {
+      this->hibernate();
+    } else {
+      this->power_off();
+    }
+  }
+
+#ifdef USE_ZEPD_DIAGNOSTICS
+  // Dev-time diagnostics - compiled out entirely unless this display's YAML
+  // sets `diagnostics: true` (display.py then adds -DUSE_ZEPD_DIAGNOSTICS),
+  // so a production build pays nothing for them. A stash for throwaway bench
+  // tests, not a stable API - add more here as needed, don't feel obliged to
+  // keep any of it around once a test has done its job.
+  //
+  // Draws the current lambda/pages content and pushes it WITHOUT the reset
+  // pulse update() normally does first - see
+  // zepd::Engine::diag_request_update_no_reset(). Call from a lambda, e.g. to
+  // check whether power_off()/hibernate() actually took: call one of those,
+  // then this with a pattern distinct from what's already on screen - no
+  // change (or odd BUSY behavior) means the panel really is off-line; follow
+  // with a normal update() to confirm the next real reset wakes it and to
+  // leave the panel in a known state either way.
+  void diag_update_no_reset() {
+    if (!this->engine_.idle()) {
+      ESP_LOGW(TAG, "Skipping diag_update_no_reset: display refresh still in progress");
+      return;
+    }
+    this->do_update_();
+    this->engine_.diag_request_update_no_reset(this->plane0_, this->plane1_);
+  }
+#endif
+
+  void dump_config() override {
+    ESP_LOGCONFIG(TAG, "zEPD Display:");
+    ESP_LOGCONFIG(TAG, "  Model: %s", this->model_name_ != nullptr ? this->model_name_ : "(unknown)");
+    ESP_LOGCONFIG(TAG, "  Dimensions: %ux%u", (unsigned) this->desc_->width, (unsigned) this->desc_->height);
+    ESP_LOGCONFIG(TAG, "  Bits/pixel: %u (%s)", (unsigned) this->desc_->bits_per_pixel,
+                  this->desc_->bits_per_pixel == 1 ? "mono/plane" : "packed palette");
+    ESP_LOGCONFIG(TAG, "  Planes/regions: %u", (unsigned) this->desc_->plane_count);
+    ESP_LOGCONFIG(TAG, "  Busy active level: %s", this->desc_->busy_active_level ? "HIGH" : "LOW");
+    if (this->desc_->bits_per_pixel == 1)
+      ESP_LOGCONFIG(TAG, "  invert_mono: %s", YESNO(this->invert_mono_));
+    ESP_LOGCONFIG(TAG, "  Hardware-verified: %s", YESNO(this->verified_));
+    if (!this->verified_)
+      ESP_LOGW(TAG, "Model %s is not yet hardware-verified - the captured data may be wrong; "
+                    "if it renders correctly, please report it so it can be marked verified",
+               this->model_name_ != nullptr ? this->model_name_ : "(unknown)");
+    LOG_UPDATE_INTERVAL(this);
+  }
+
+  display::DisplayType get_display_type() override { return display::DisplayType::DISPLAY_TYPE_COLOR; }
+
+ protected:
+  // Replicates a packed wire code across a whole byte (one code per pixel
+  // slot), e.g. 2bpp code 0x01 -> 0x55, 4bpp code 0x01 -> 0x11.
+  static uint8_t replicate_code_(uint8_t code, uint8_t bpp) {
+    uint8_t mask = static_cast<uint8_t>((1u << bpp) - 1);
+    uint8_t out = 0;
+    for (uint8_t i = 0; i < 8 / bpp; i++)
+      out = static_cast<uint8_t>((out << bpp) | (code & mask));
+    return out;
+  }
+
+  // Maps a drawn RGB color to its panel wire code via the descriptor's
+  // palette: exact matches win (so named colors are deterministic, like
+  // GxEPD2's color4()/color7() switch), otherwise nearest in RGB space.
+  static uint8_t classify_(Color c, const EpdPaletteEntry *pal, uint8_t len) {
+    if (pal == nullptr || len == 0)
+      return 0;
+    uint8_t best = 0;
+    long best_d = -1;
+    for (uint8_t i = 0; i < len; i++) {
+      long dr = static_cast<long>(c.red) - pal[i].r;
+      long dg = static_cast<long>(c.green) - pal[i].g;
+      long db = static_cast<long>(c.blue) - pal[i].b;
+      long d = dr * dr + dg * dg + db * db;
+      if (d == 0)
+        return pal[i].code;
+      if (best_d < 0 || d < best_d) {
+        best_d = d;
+        best = i;
+      }
+    }
+    return pal[best].code;
+  }
+
+  // Packed code-per-pixel model (bits_per_pixel > 1): N bits/pixel, MSB
+  // first, matching GxEPD2's own out_data packing in writeImage (4-color
+  // 4px/byte, 7-color 2px/byte). Routes to the correct region for a
+  // window_per_plane (master/slave) panel the same way the mono path does.
+  void draw_packed_(int x, int y, Color color) {
+    const uint8_t bpp = this->desc_->bits_per_pixel;
+    uint8_t code = classify_(color, this->desc_->palette, this->desc_->palette_len);
+    uint16_t stride = this->desc_->width;
+    uint8_t *buf = this->plane0_;
+    int local_x = x;
+    if (this->desc_->window_per_plane && this->desc_->plane_count > 1) {
+      stride = this->desc_->plane_width;
+      if (x >= stride) {
+        buf = this->plane1_;
+        local_x = x - stride;
+      }
+    }
+    uint32_t px = static_cast<uint32_t>(y) * stride + local_x;
+    const uint8_t ppb = 8 / bpp;
+    uint32_t idx = px / ppb;
+    uint8_t shift = static_cast<uint8_t>((ppb - 1 - (px % ppb)) * bpp);
+    uint8_t mask = static_cast<uint8_t>((1u << bpp) - 1);
+    buf[idx] = static_cast<uint8_t>((buf[idx] & ~(mask << shift)) | ((code & mask) << shift));
+  }
+
+  void draw_absolute_pixel_internal(int x, int y, Color color) override {
+    if (x < 0 || y < 0 || x >= this->desc_->width || y >= this->desc_->height)
+      return;
+    if (this->desc_->bits_per_pixel > 1) {
+      this->draw_packed_(x, y, color);
+      return;
+    }
+    bool red = color.red > color.green && color.red > color.blue && color.red > 0x7f;
+    bool bright = color.red > 0x7f || color.green > 0x7f || color.blue > 0x7f;
+    uint32_t idx = (static_cast<uint32_t>(y) * this->desc_->width + x) / 8;
+    uint8_t mask = 0x80 >> (x % 8);
+    // Red/accent pixels go to the color plane (when the panel has one),
+    // everything else is black/white on the black plane. get_display_type()
+    // reports DISPLAY_TYPE_COLOR, so callers draw literal RGB colors, not
+    // the on/off is_on() convention, even on a plane_count==1 (BW-only)
+    // panel - there just is no color plane for a "red" classification to
+    // land on.
+    //
+    // Buffer convention here is 1=red/0=not-red, transformed to the wire
+    // value by plane_invert[1].
+    if (red && this->plane1_ != nullptr) {
+      this->plane1_[idx] |= mask;
+    } else {
+      if (this->plane1_ != nullptr)
+        this->plane1_[idx] &= ~mask;
+      // plane0 bit set = white/blank. invert_mono_ flips the mono sense so a
+      // bright color (e.g. ESPHome's default COLOR_ON) becomes ink, not blank
+      // - see display.py's CONF_INVERT_MONO. Red classification is unaffected.
+      if (bright ^ this->invert_mono_) {
+        this->plane0_[idx] |= mask;
+      } else {
+        this->plane0_[idx] &= ~mask;
+      }
+    }
+  }
+  int get_width_internal() override { return this->desc_->width; }
+  int get_height_internal() override { return this->desc_->height; }
+
+  // The colors this panel can actually show, each as a representative RGB, in
+  // a stable order (black, white, then accents). Packed panels (>1bpp): one
+  // entry per distinct palette wire code, first RGB seen for each. 1bpp:
+  // black + white, plus red when a second plane exists for the accent (only
+  // red-classified pixels reach it - see draw_absolute_pixel_internal). This
+  // is what makes test_pattern() bit-depth aware. Returns the count.
+  int test_colors_(Color *out, int max) {
+    int n = 0;
+    if (this->desc_->bits_per_pixel > 1 && this->desc_->palette != nullptr) {
+      uint8_t seen[16];
+      int seen_n = 0;
+      for (int i = 0; i < this->desc_->palette_len && n < max; i++) {
+        const uint8_t code = this->desc_->palette[i].code;
+        bool dup = false;
+        for (int j = 0; j < seen_n; j++)
+          if (seen[j] == code) { dup = true; break; }
+        if (dup) continue;
+        if (seen_n < (int) sizeof(seen)) seen[seen_n++] = code;
+        const auto &e = this->desc_->palette[i];
+        out[n++] = Color(e.r, e.g, e.b);
+      }
+    } else {
+      if (n < max) out[n++] = Color(0x00, 0x00, 0x00);  // black
+      if (n < max) out[n++] = Color(0xFF, 0xFF, 0xFF);  // white
+      if (this->desc_->plane_count >= 2 && n < max) out[n++] = Color(0xFF, 0x00, 0x00);  // accent
+    }
+    return n;
+  }
+
+  const EngineModel *desc_{nullptr};
+  const char *model_name_{nullptr};
+  bool verified_{false};
+  GPIOPin *cs_{nullptr};
+  GPIOPin *dc_{nullptr};
+  GPIOPin *rst_{nullptr};
+  GPIOPin *busy_{nullptr};
+  EpdSPIDevice spi_;
+  Engine engine_;
+  uint8_t *plane0_{nullptr};
+  uint8_t *plane1_{nullptr};
+  uint32_t plane_bytes_{0};
+  bool invert_mono_{false};
+};
+
+}  // namespace esphome::zepd

+ 27 - 0
tests/test_smoke_zepd.esp32-arduino.yaml

@@ -0,0 +1,27 @@
+# zEPD smoke test for the esphome-zepd tree (new registry-based component,
+# not the legacy gxepd2 one - see claude/ZEPD_PLAN.md). Mirrors
+# test_smoke.esp32-arduino.yaml's shape: 1bpp model (no PSRAM needed),
+# Arduino framework.
+esphome:
+  name: zepd-smoke-arduino
+esp32:
+  board: esp32dev
+  framework:
+    type: arduino
+external_components:
+  - source:
+      type: local
+      path: ../esphome-zepd/components
+    components: [zepd]
+spi:
+  clk_pin: 18
+  mosi_pin: 23
+logger:
+display:
+  - platform: zepd
+    model: GxEPD2_102
+    cs_pin: 5
+    dc_pin: 17
+    reset_pin: 16
+    busy_pin: 4
+    update_interval: 60s