#!/usr/bin/env python3
"""Build docs/BREADBOARD_GUIDE.html: a step-by-step, picture-first guide to breadboarding the turntable.

  python docs/breadboard/build_breadboard_guide.py

Every wire, part and hole reference in the guide comes from the tables below, so the pictures, the wire
lists and the hole names cannot disagree. The connections were taken from the mainboard schematic
(kicad_mainboard/*.kicad_sch, via a netlist export) and the GPIO numbers from src/pins.h.
"""
import os
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import bb  # noqa: E402
from bb import P, S, ROW, COL, fnum, esc  # noqa: E402

OUT = os.path.join(os.path.dirname(HERE), "BREADBOARD_GUIDE.html")

RAILS = {
    1: {"T1": ("+12V", "red"), "T2": ("GND", "black"), "B1": ("GND", "black")},
    2: {"T1": ("+3V3", "orange"), "T2": ("GND", "black"), "B1": ("GND", "black"), "B2": ("+3V3", "orange")},
    3: {"T1": ("+5V", "rose"), "T2": ("GND", "black"), "B1": ("GND", "black"), "B2": ("+5V", "rose")},
}
BOARD_NAME = {1: "Brain board (ESP32 + motor)", 2: "Panel board (knobs + button)", 3: "Lighting board (buffers + LEDs)"}
TOP_PAD = {1: 305, 2: 215, 3: 205}
BOT_PAD = {1: 130, 2: 120, 3: 205}
ETH_C1 = 9          # breadboard column of the ESP32-S3-ETH's pin 1
TMC_C1 = 36
DEV_C1 = 3
MCP_C1 = 37
AHCT_C1 = 34


def H1(n):          # ESP32-S3-ETH H1 pin n -> column (top row)
    return ETH_C1 + n - 1


H2 = H1             # H2 pin n -> same column (bottom row)

# ---------------------------------------------------------------- parts and wires
PARTS = []          # dicts: stage, kind, board, ...
WIRES = []          # dicts: stage, color, a, b, why, ...


def part(stage, kind, board, **kw):
    PARTS.append(dict(stage=stage, kind=kind, board=board, **kw))


def wire(stage, color, a, b, why, **kw):
    """a, b: (board, col, row) or ('obj', name). Wires between two boards are drawn as flags."""
    WIRES.append(dict(stage=stage, color=color, a=a, b=b, why=why, **kw))


# ---- stage 1: ESP32-S3-ETH on board 1
part(1, "eth", 1, c1=ETH_C1)
wire(1, "black", (1, H1(8), "i"), (1, H1(8), "T2"), "ESP32 ground (top row, pin 8) to the top GND rail")
wire(1, "black", (1, H2(8), "b"), (1, H2(8), "B1"), "ESP32 ground (bottom row, pin 8) to the bottom GND rail")
wire(1, "black", (1, 62, "T2"), (1, 62, "B1"), "Joins the top and bottom GND rails so both sides share ground", lift=0)

# ---- stage 2: stepper driver, motor, 12 V.  Driver pins 1..8 are columns 36..43.
T = TMC_C1
part(2, "jack", 1)
part(2, "motor", 1)
part(2, "tmc", 1, c1=T)
part(2, "diode", 1, a=(1, 33, "j"), k=(1, T, "j"), label="D1 1N5819")
part(2, "cap", 1, p=(1, T, "i"), m=(1, T + 1, "i"), label="100µF 35V")
part(2, "res", 1, a=(1, 25, "j"), b=(1, 31, "j"), value="1k", label="R23 1k")
part(2, "res", 1, a=(1, T - 2, "a"), b=(1, T + 4, "a"), value="1k", label="R9 1k")
wire(2, "red", ("obj", "jack+"), (1, 4, "T1"), "12 V adapter + to the +12V rail", lift=30)
wire(2, "black", ("obj", "jack-"), (1, 5, "T2"), "12 V adapter − to the GND rail", lift=22)
wire(2, "red", (1, 33, "T1"), (1, 33, "i"), "+12V rail to the diode D1 (anode side)", lift=0)
wire(2, "black", (1, T + 1, "j"), (1, T + 1, "T2"), "Driver ground (pin 2, top row) to the GND rail", lift=0)
wire(2, "black", (1, T + 7, "j"), (1, T + 7, "T2"), "Driver ground (pin 8, top row) to the GND rail", lift=0)
wire(2, "orange", (1, H1(5), "i"), (1, 31, "i"), "ESP32 3V3 pin to the 3V3 junction (column 31)", lift=30)
wire(2, "orange", (1, 31, "h"), (1, T + 6, "i"), "3V3 junction to the driver's logic supply (VIO)", lift=22)
wire(2, "green", ("obj", "motor-A-"), (1, T + 2, "i"), "Motor green wire (A−)", lift=0, bt=0.30)
wire(2, "black", ("obj", "motor-A+"), (1, T + 3, "i"), "Motor black wire (A+)", lift=0, bt=0.42)
wire(2, "red", ("obj", "motor-B+"), (1, T + 4, "i"), "Motor red wire (B+)", lift=0, bt=0.54)
wire(2, "blue", ("obj", "motor-B-"), (1, T + 5, "i"), "Motor blue wire (B−)", lift=0, bt=0.66)
wire(2, "black", (1, T + 1, "b"), (1, T + 1, "B1"), "Driver MS1 to GND (selects driver address 0)", lift=12, up=False)
wire(2, "black", (1, T + 2, "b"), (1, T + 2, "B1"), "Driver MS2 to GND (selects driver address 0)", lift=14, up=False)
wire(2, "black", (1, T + 5, "b"), (1, T + 5, "B1"), "Driver CLK to GND (use the internal clock)", lift=12, up=False)
wire(2, "lime", (1, T + 3, "b"), (1, T + 4, "b"), "Joins the driver's two PDN pins together", lift=8, up=False)
wire(2, "teal", (1, T + 3, "a"), (1, H1(12), "i"), "UART receive: driver PDN to ESP32 GPIO15", lift=130, bt=0.30)
wire(2, "lime", (1, H2(5), "b"), (1, T - 2, "b"), "UART transmit: ESP32 GPIO47 to R9 (the 1k resistor)", lift=34, up=False, bt=0.35)
wire(2, "pink", (1, H2(6), "b"), (1, T + 6, "b"), "STEP: ESP32 GPIO46 to the driver's STEP pin", lift=48, up=False, bt=0.45)
wire(2, "brown", (1, H2(4), "b"), (1, T + 7, "b"), "DIR: ESP32 GPIO48 to the driver's DIR pin", lift=62, up=False, bt=0.55)
wire(2, "grey", (1, H1(17), "i"), (1, T, "b"), "ENABLE: ESP32 GPIO0 to the driver's EN pin", lift=100, bt=0.30)

# ---- stage 3: the speed knob and the tap button (board 2).  KY-040 modules are 19 mm wide: 8 columns apart.
KY_ENC, KY_HUE, KY_SAT, KY_VAL = 27, 3, 11, 19
part(3, "ky", 2, c1=KY_ENC, title="SPEED")
part(3, "button", 2, c1=56)
wire(3, "black", (1, 59, "B1"), (2, 59, "B1"), "Ground link between the Brain board and the Panel board", cross=True)
wire(3, "orange", (1, 31, "g"), (2, 57, "B2"), "3V3 from the Brain board's junction (column 31) to the Panel board's 3V3 rail", cross=True)
wire(3, "black", (2, 62, "T2"), (2, 62, "B1"), "Joins the Panel board's top and bottom GND rails", lift=0)
wire(3, "orange", (2, 61, "T1"), (2, 61, "B2"), "Joins the Panel board's top and bottom 3V3 rails", lift=0)
wire(3, "black", (2, KY_ENC, "f"), (2, KY_ENC, "B1"), "Speed knob GND pin to GND", lift=0)
wire(3, "orange", (2, KY_ENC + 1, "f"), (2, KY_ENC + 1, "B2"), "Speed knob + pin to 3V3", lift=0)
wire(3, "blue", (1, H2(14), "b"), (2, KY_ENC + 4, "f"), "Speed knob CLK: ESP32 GPIO38", cross=True)
wire(3, "lightblue", (1, H2(12), "b"), (2, KY_ENC + 3, "f"), "Speed knob DT: ESP32 GPIO39", cross=True)
wire(3, "black", (2, 56, "d"), (2, 56, "B1"), "TAP button to GND", lift=0)
wire(3, "white", (1, H1(6), "i"), (2, 58, "g"), "TAP button signal: ESP32 GPIO21", cross=True)

# ---- stage 4: the other three knobs
for c1, title in ((KY_HUE, "HUE"), (KY_SAT, "SAT"), (KY_VAL, "VAL")):
    part(4, "ky", 2, c1=c1, title=title)
KNOBS = {"HUE": (KY_HUE, "purple", "pink", 24, None, "GPIO1", "GPIO40"),   # DT on H2 pin 11 (GPIO40) since 2026-11-10
         "SAT": (KY_SAT, "green", "lime", 28, 27, "GPIO43", "GPIO44"),
         "VAL": (KY_VAL, "yellow", "white", 18, 17, "GPIO41", "GPIO42")}
for name, (c1, ccl, cdt, ecl, edt, pcl, pdt) in KNOBS.items():
    row = "i" if name != "VAL" else "b"
    wire(4, "black", (2, c1, "f"), (2, c1, "B1"), f"{name} knob GND pin to GND", lift=0)
    wire(4, "orange", (2, c1 + 1, "f"), (2, c1 + 1, "B2"), f"{name} knob + pin to 3V3", lift=0)
    wire(4, ccl, (1, ecl, row), (2, c1 + 4, "f"), f"{name} knob CLK: ESP32 {pcl}", cross=True)
    dt_end = (1, edt, row) if edt is not None else (1, H2(11), "b")
    wire(4, cdt, dt_end, (2, c1 + 3, "f"), f"{name} knob DT: ESP32 {pdt}", cross=True)

# ---- stage 5: the I2C expander for the four knob buttons
part(5, "dip", 2, c1=MCP_C1, n=28, name="MCP23017", labels=bb.MCP_LABELS)
part(5, "res", 2, a=(2, 49, "c"), b=(2, 51, "B2"), value="4.7k", label="R21 4.7k", ldx=16, ldy=18)
part(5, "res", 2, a=(2, 48, "c"), b=(2, 46, "B2"), value="4.7k", label="R22 4.7k", ldx=-16, ldy=18)
part(5, "capc", 2, a=(2, 45, "c"), b=(2, 46, "c"), label="0.1µF")
wire(5, "orange", (2, 45, "d"), (2, 45, "B2"), "Expander power (VDD, pin 9) to 3V3", lift=0)
wire(5, "black", (2, 46, "d"), (2, 43, "B1"), "Expander ground (VSS, pin 10) to GND", lift=0)
wire(5, "orange", (2, 47, "g"), (2, 47, "T1"), "Expander RESET (pin 18) held high at 3V3", lift=0)
wire(5, "black", (2, 48, "g"), (2, 47, "T2"), "Address pin A2 (pin 17) to GND", lift=0)
wire(5, "black", (2, 49, "g"), (2, 49, "T2"), "Address pin A1 (pin 16) to GND", lift=0)
wire(5, "black", (2, 50, "g"), (2, 50, "T2"), "Address pin A0 (pin 15) to GND (all three: address 0x20)", lift=0)
wire(5, "cyan", (1, H1(7), "i"), (2, 49, "a"), "I2C data (SDA): ESP32 GPIO17", cross=True)
wire(5, "teal", (1, H1(9), "i"), (2, 48, "a"), "I2C clock (SCL): ESP32 GPIO16", cross=True)
wire(5, "purple", (2, KY_HUE + 2, "f"), (2, 44, "g"), "HUE knob button (SW) to the expander's GPA0", lift=60, bt=0.4)
wire(5, "cyan", (2, KY_ENC + 2, "f"), (2, 41, "g"), "Speed knob button (SW) to the expander's GPA3 (it was ESP32 GPIO40 until 2026-11-10)", lift=50, bt=0.5)
wire(5, "green", (2, KY_SAT + 2, "f"), (2, 42, "d"), "SAT knob button (SW) to the expander's GPB5", lift=40, up=False, bt=0.5)
wire(5, "yellow", (2, KY_VAL + 2, "f"), (2, 39, "g"), "VAL knob button (SW) to the expander's GPA5", lift=45, bt=0.6)

# ---- stage 6: lighting board.  The ESP32-S3-ETH drives the strip itself: data (GPIO18) through gate 1 of the
# 74AHCT125 (U3 on the PCB), clock (GPIO2) through gate 2 (U5). A 5 V adapter feeds the +5V rails.
part(6, "dip", 3, c1=AHCT_C1, n=14, name="74AHCT125", labels=bb.AHCT_LABELS)
part(6, "res", 3, a=(3, 30, "b"), b=(3, 35, "b"), value="330", label="R18 330Ω", ldy=-4)
part(6, "res", 3, a=(3, 35, "c"), b=(3, 32, "c"), value="10k", label="R26 10k", ldy=30)
part(6, "res", 3, a=(3, 44, "b"), b=(3, 38, "b"), value="330", label="R61 330Ω", ldy=-4)
part(6, "res", 3, a=(3, 38, "c"), b=(3, 42, "c"), value="10k", label="R62 10k", ldy=30)
part(6, "capc", 3, a=(3, 33, "T1"), b=(3, 33, "T2"), label="0.1µF")
part(6, "strip", 3)
part(6, "jack5", 3)
wire(6, "rose", ("obj", "jack5+"), (3, 5, "T1"), "5 V adapter + to the +5V rail")
wire(6, "black", ("obj", "jack5-"), (3, 8, "T2"), "5 V adapter − to the GND rail")
wire(6, "rose", (3, 62, "T1"), (3, 62, "B2"), "Joins the +5V rails", lift=0)
wire(6, "black", (3, 61, "T2"), (3, 61, "B1"), "Joins the GND rails", lift=0)
wire(6, "black", (3, 32, "a"), (3, 32, "B1"), "Column 32 to GND, for R26 (holds the data input low while the ESP32 starts)", lift=0)
wire(6, "black", (3, 42, "a"), (3, 42, "B1"), "Column 42 to GND, for R62 (holds the clock input low while the ESP32 starts)", lift=0)
wire(6, "black", (3, 34, "a"), (3, 34, "B1"), "74AHCT125 pin 1 (gate 1 output enable, active low) to GND", lift=0)
wire(6, "black", (3, 37, "a"), (3, 37, "B1"), "74AHCT125 pin 4 (gate 2 output enable, active low) to GND", lift=0)
wire(6, "black", (3, 40, "a"), (3, 40, "B1"), "74AHCT125 ground (pin 7) to GND", lift=0)
wire(6, "black", (3, 39, "g"), (3, 39, "T2"), "Unused gate 3: pin 9 (input) to GND", lift=0)
wire(6, "rose", (3, 38, "g"), (3, 38, "T1"), "Unused gate 3: pin 10 (OE) to +5V, which switches it off", lift=0)
wire(6, "black", (3, 36, "g"), (3, 37, "T2"), "Unused gate 4: pin 12 (input) to GND", lift=0)
wire(6, "rose", (3, 35, "g"), (3, 35, "T1"), "Unused gate 4: pin 13 (OE) to +5V", lift=0)
wire(6, "rose", (3, 34, "g"), (3, 34, "T1"), "74AHCT125 power (VCC, pin 14) to +5V", lift=0)
wire(6, "lime", (3, 36, "a"), ("obj", "strip-DIN"), "LED data out (74AHCT125 pin 3) to the strip's DIN pad", lift=0, bt=0.55)
wire(6, "teal", (3, 39, "a"), ("obj", "strip-CKI"), "LED clock out (74AHCT125 pin 6) to the strip's CKI pad", lift=0, bt=0.55)
wire(6, "rose", ("obj", "strip+5V"), (3, 45, "B2"), "LED strip +5V to the +5V rail", lift=0, bt=0.55)
wire(6, "black", ("obj", "strip-GND"), (3, 47, "B1"), "LED strip GND to the GND rail", lift=0, bt=0.55)
wire(6, "lime", (1, H1(10), "i"), (3, 30, "a"), "LED data: ESP32 GPIO18 to R18", cross=True)
wire(6, "teal", (1, H1(15), "i"), (3, 44, "a"), "LED clock: ESP32 GPIO2 to R61", cross=True)
wire(6, "black", (1, 61, "B1"), (3, 59, "B1"), "Ground link between the Brain board and the Lighting board", cross=True)

# ---- stage 7 (optional): the fan.  Header pins are columns 46..49 (GND, +12V, TACH, PWM).
part(7, "fanhdr", 1)
part(7, "fan", 1)
part(7, "to92", 1, legs=[(1, 56, "d"), (1, 57, "d"), (1, 58, "d")], label="Q6 2N7000")
part(7, "res", 1, a=(1, 57, "c"), b=(1, 53, "c"), value="1k", label="R57 1k", ldy=-4)
part(7, "res", 1, a=(1, 57, "b"), b=(1, 57, "B1"), value="10k", label="R58 10k", ldx=16, ldy=18)
part(7, "res", 1, a=(1, 48, "i"), b=(1, 52, "i"), value="4.7k", label="R59 4.7k", ldy=-6)
wire(7, "black", (1, 46, "j"), (1, 46, "T2"), "Fan ground to the GND rail", lift=0)
wire(7, "red", (1, 47, "j"), (1, 36, "h"), "Fan +12 V to the driver's VM column (after diode D1)", lift=50)
wire(7, "black", (1, 56, "c"), (1, 55, "B1"), "Q6 source to GND", lift=0)
wire(7, "pink", (1, H2(7), "b"), (1, 53, "b"), "Fan speed: ESP32 GPIO45 to R57", lift=30, up=False, bt=0.45)
wire(7, "blue", (1, 58, "c"), (1, 49, "h"), "Q6 drain to the fan's PWM wire", lift=45, up=True)
wire(7, "green", (1, 52, "j"), (2, 38, "g"), "Fan tach (through R59) to the expander's GPA6", cross=True)

# sanity check: no two wires or part leads may end in the same breadboard hole
_seen = {}
def _claim(end, what):
    if end[0] == "obj":
        return
    board, col, row = end
    if row in ("T1", "T2", "B1", "B2"):
        col = bb.rail_col(col)
    key = (board, col, row)
    if key in _seen:
        raise SystemExit(f"hole clash at board {board} {row}{col}: {_seen[key]} and {what}")
    _seen[key] = what
for _w in WIRES:
    for _e in (_w["a"], _w["b"]):
        _claim(_e, "wire: " + _w["why"])
def _module_holes(p):
    """(pin holes, hidden holes) of a module: pins are claimed, holes under the body cannot be used."""
    k, b = p["kind"], p["board"]
    pins, hidden = [], []
    if k == "eth":
        c = p["c1"]
        pins = [(b, c + i, r) for i in range(20) for r in "hc"]
        hidden = [(b, col, r) for col in range(1, c + 21) for r in "gfed"]
    elif k == "tmc":
        c = p["c1"]
        pins = [(b, c + i, r) for i in range(8) for r in "gc"]
        hidden = [(b, c + i, r) for i in range(8) for r in "fed"]
    elif k == "devkit":
        c = p["c1"]
        pins = [(b, c + i, r) for i in range(22) for r in "ib"]
        hidden = [(b, c + i, r) for i in range(22) for r in "hgfedc"]
    elif k == "dip":
        c = p["c1"]
        pins = [(b, c + i, r) for i in range(p["n"] // 2) for r in "ef"]
    elif k == "ky":
        pins = [(b, p["c1"] + i, "j") for i in range(5)]
    elif k == "button":
        pins = [(b, c, r) for c in (p["c1"], p["c1"] + 2) for r in "ef"]
    elif k == "fanhdr":
        pins = [(b, 46 + i, "g") for i in range(4)]
    return pins, hidden


_hidden = set()
for _p in PARTS:
    _pins, _hid = _module_holes(_p)
    for _e in _pins:
        _claim(_e, "module pin: " + _p["kind"])
    _hidden.update(_hid)
for _w in WIRES:
    for _e in (_w["a"], _w["b"]):
        if _e[0] != "obj" and _e in _hidden:
            raise SystemExit(f"wire goes to a hole under a module: {_e} ({_w['why']})")
for _p in PARTS:
    for _k in ("a", "b", "p", "m", "k"):
        if _k in _p and isinstance(_p[_k], tuple) and _p["kind"] in ("res", "cap", "capc", "diode"):
            _claim(_p[_k], "part: " + _p.get("label", _p["kind"]))
    for _e in _p.get("legs", []):
        _claim(_e, "part: " + _p.get("label", _p["kind"]))

# number the wires in order
for i, w in enumerate(sorted(range(len(WIRES)), key=lambda k: (WIRES[k]["stage"], k))):
    WIRES[w]["n"] = i + 1


# ---------------------------------------------------------------- electrical check against the schematic
import json as _json


def _norm(name):
    """Schematic net name -> the name the breadboard uses (protection parts and the fuse do not exist here)."""
    if name is None or name.startswith("unconnected"):
        return None
    if name.startswith("+5V") or name == "Net-(D33-K)":
        return "+5V"
    if name == "FAN_TACH_J":
        return name                      # the fan side of R59 stays a separate net from the expander side
    if name.endswith("_J"):
        name = name[:-2]
    if name.startswith("3V3_"):
        return "+3V3"
    return name


def verify():
    """Rebuild the breadboard's connectivity from the hole tables and compare it with the schematic's nets."""
    with open(os.path.join(HERE, "pinmap.json"), encoding="utf-8") as f:
        pm = _json.load(f)
    parent = {}

    def find(x):
        parent.setdefault(x, x)
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x

    def union(a, b):
        parent[find(a)] = find(b)

    def node(e):
        if e[0] == "obj":
            return ("obj", e[1])
        board, col, row = e
        if row in ("T1", "T2", "B1", "B2"):
            return (board, row)
        return (board, col, "t" if row in "jihgf" else "b")

    names = []          # (node, expected net name, description)

    def pin(e, name, what):
        n = _norm(name)
        if n is not None:
            names.append((node(e), n, what))

    for w in WIRES:
        union(node(w["a"]), node(w["b"]))
    obj_names = {"jack+": "+12V_MOTOR_PSU", "jack-": "GND", "motor-A-": "MOTOR_COIL_A2", "motor-A+": "MOTOR_COIL_A1",
                 "motor-B+": "MOTOR_COIL_B1", "motor-B-": "MOTOR_COIL_B2", "strip+5V": "+5V", "strip-DIN": "LED_DATA_5V",
                 "strip-CKI": "LED_CLK_5V", "strip-GND": "GND", "jack5+": "+5V", "jack5-": "GND"}
    for k, v in obj_names.items():
        names.append((("obj", k), v, k))
    internal_gnd = {}   # board/module -> list of nodes to tie together (a module's GND pins are one net inside the module)
    for p in PARTS:
        k, b = p["kind"], p["board"]
        if k == "eth":
            c = p["c1"]
            for n in range(1, 21):
                for ref, row in (("J1-H1", "h"), ("J1-H2", "c")):
                    nm = pm[ref][str(n)]
                    if ref == "J1-H1" and n == 2:
                        nm = None           # VSYS: fed from +5V_LED_LOGIC on the PCB; on the breadboard the module runs from its USB
                    if ref == "J1-H1" and n == 4:
                        nm = None           # 3V3_EN: left open on the PCB too (the module's own regulator makes the 3V3)
                    pin((b, c + n - 1, row), nm, f"ESP32-S3-ETH {ref} pin {n}")
                    if nm == "GND":
                        internal_gnd.setdefault(("eth", b), []).append(node((b, c + n - 1, row)))
        elif k == "tmc":
            c = p["c1"]
            for n in range(1, 9):
                pin((b, c + n - 1, "c"), pm["J2-MODE"][str(n)], f"TMC2209 MODE pin {n}")
                pin((b, c + n - 1, "g"), pm["J2-MOTOR"][str(n)], f"TMC2209 MOTOR pin {n}")
        elif k == "devkit":
            c = p["c1"]
            for n in range(1, 23):
                for refs, row in ((("J6-J1", "J6-J1B"), "b"), (("J6-J3", "J6-J3B"), "i")):
                    nm = pm[refs[0]].get(str(n)) if n <= 20 else pm[refs[1]].get(str(n - 20))
                    pin((b, c + n - 1, row), nm, f"DevKitC {refs[0]} pin {n}")
                    if _norm(nm) == "GND":
                        internal_gnd.setdefault(("dev", b), []).append(node((b, c + n - 1, row)))
        elif k == "dip" and p["name"] == "MCP23017":
            c = p["c1"]
            # The board's U1 is a TCA9555 (since 2026-11-10); the breadboard keeps the DIP MCP23017, which the firmware also
            # drives. Their pins match by function: GPAn = IO0_n, GPBn = IO1_n.
            mcp_to_tca = {**{n: 12 + n for n in range(1, 9)}, **{n: n - 17 for n in range(21, 29)},
                          9: 24, 10: 12, 12: 22, 13: 23, 15: 21, 16: 2, 17: 3}
            for n in range(1, 29):
                col = c + n - 1 if n <= 14 else c + 28 - n
                if n in mcp_to_tca:
                    nm = pm["U1"][str(mcp_to_tca[n])]
                else:
                    nm = "+3V3" if n == 18 else None     # RESET tied high on the breadboard; NC and INTA/INTB open
                pin((b, col, "e" if n <= 14 else "f"), nm, f"MCP23017 pin {n}")
        elif k == "dip":        # 74AHCT125: gate 1 is U3 (data), gate 2 is U5 (clock); gates 3 and 4 are tied off
            c = p["c1"]
            logical = {1: "GND", 2: "LED_DATA", 3: "LED_DATA_5V", 4: "GND", 5: "LED_CLK", 6: "LED_CLK_5V", 7: "GND", 9: "GND",
                       10: "+5V", 12: "GND", 13: "+5V", 14: "+5V"}
            u3 = {int(n): nm for n, nm in pm["U3"].items()}
            u5 = {int(n): nm for n, nm in pm["U5"].items()}
            assert u3[1] == "GND" and u3[2] == "LED_DATA" and u3[4] == "LED_DATA_5V" and u3[3] == "GND", u3
            assert u5[1] == "GND" and u5[2] == "LED_CLK" and u5[4] == "LED_CLK_5V" and u5[3] == "GND", u5
            for n, nm in logical.items():
                col = c + n - 1 if n <= 7 else c + 14 - n
                pin((b, col, "e" if n <= 7 else "f"), nm, f"74AHCT125 pin {n}")
        elif k == "ky":
            c, title = p["c1"], p["title"]
            pre = "ENC" if title == "SPEED" else title
            for i, nm in enumerate(["GND", "+3V3", f"{pre}_SW", f"{pre}_DT", f"{pre}_CLK"]):
                pin((b, c + i, "j"), nm, f"{title} knob pin {i + 1}")
        elif k == "fanhdr":
            for i, nm in enumerate([pm["J-FAN"][str(n)] for n in (1, 2, 3, 4)]):
                pin((b, 46 + i, "g"), nm, f"fan plug pin {i + 1}")
        elif k == "to92":
            for e, nm in zip(p["legs"], ["GND", "FAN_GATE", "FAN_PWM_OUT"]):
                pin(e, nm, "2N7000 Q6")
        elif k == "res":
            lab = p["label"].split()[0]
            ends = {"R23": ("ENABLE", "+3V3"), "R9": ("TMC_UART_TX", "TMC_UART_RX"), "R18": ("LED_DATA_3V3", "LED_DATA"),
                    "R26": ("LED_DATA", "GND"), "R61": ("LED_CLK_3V3", "LED_CLK"), "R62": ("LED_CLK", "GND"), "R21": ("I2C_SDA", "+3V3"), "R22": ("I2C_SCL", "+3V3"),
                    "R57": ("FAN_GATE", "FAN_PWM"), "R58": ("FAN_GATE", "GND"), "R59": ("FAN_TACH_J", "FAN_TACH")}[lab]
            # the schematic says which two nets the resistor joins
            sch = {_norm(n) for n in pm[lab].values()} if lab in pm and pm[lab] else None
            if sch is not None:
                want = {_norm(ends[0]), _norm(ends[1])}
                if lab not in ("R57", "R58", "R59") and sch != want:
                    raise SystemExit(f"{lab}: schematic joins {sch}, guide uses {want}")
            pin(p["a"], ends[0], lab + " lead A")
            pin(p["b"], ends[1], lab + " lead B")
        elif k == "cap":
            pin(p["p"], "+12V_MOTOR", "100uF +")
            pin(p["m"], "GND", "100uF -")
        elif k == "capc":
            if p["a"][2] == "T1":
                pin(p["a"], "+5V", "0.1uF"); pin(p["b"], "GND", "0.1uF")
            else:
                pin(p["a"], "+3V3", "0.1uF"); pin(p["b"], "GND", "0.1uF")
        elif k == "diode":
            pin(p["a"], "+12V_MOTOR_PSU", "D1 anode")
            pin(p["k"], "+12V_MOTOR", "D1 cathode")
    # the push button: wired diagonally, so its two terminals are always on different nets; nothing to check on its legs
    for lst in internal_gnd.values():
        for x in lst[1:]:
            union(lst[0], x)
    groups = {}
    for nd, nm, what in names:
        groups.setdefault(find(nd), {}).setdefault(nm, []).append(what)
    problems = []
    for root, d in groups.items():
        if len(d) > 1:
            problems.append("SHORT: one breadboard net holds " + " and ".join(f"{k} ({', '.join(v[:3])})" for k, v in d.items()))
    where = {}
    for root, d in groups.items():
        for nm in d:
            where.setdefault(nm, []).append(root)
    for nm, roots in where.items():
        if len(roots) > 1:
            parts = []
            for r in roots:
                parts.append(", ".join(groups[r][nm][:3]))
            problems.append(f"OPEN: net {nm} is split into {len(roots)} pieces: " + " | ".join(parts))
    return problems, groups


# ---------------------------------------------------------------- drawing a figure
def hole_name(board, col, row):
    if row in ("T1", "T2", "B1", "B2"):
        lab = RAILS[board][row][0]
        return f"{lab} rail ({'top' if row[0] == 'T' else 'bottom'}), near column {bb.rail_col(col)}"
    return f"{row}{col}"


def tag_hole(board, col, row):
    if row in ("T1", "T2", "B1", "B2"):
        return f"{RAILS[board][row][0]} rail"
    return f"{row}{col}"


def short_hole(board, col, row):
    if row in ("T1", "T2", "B1", "B2"):
        return f"{RAILS[board][row][0]} rail, col {bb.rail_col(col)}"
    return f"{row}{col}"


OBJ_NAMES = {"jack+": "12 V adapter +", "jack-": "12 V adapter −", "motor-A-": "motor green (A−)",
             "motor-A+": "motor black (A+)", "motor-B+": "motor red (B+)", "motor-B-": "motor blue (B−)",
             "strip-DIN": "LED strip DIN", "strip-CKI": "LED strip CKI", "strip+5V": "LED strip +5V", "strip-GND": "LED strip GND",
             "jack5+": "5 V adapter +", "jack5-": "5 V adapter −"}


def end_text(e):
    if e[0] == "obj":
        return OBJ_NAMES[e[1]]
    return f"Board {e[0]}: {short_hole(*e)}"


def objects_for(b, stage):
    """Pixel positions of the off-board objects for board b."""
    obj = {}
    if b.num == 1:
        jx, jy = b.x(2) - 8, b.oy - 3 * P - 120
        svg, plus, minus = bb.draw_jack(jx, jy, stage == 2)
        obj["jack"] = svg
        obj["jack+"], obj["jack-"] = plus, minus
        mcx, my = b.x(37.5), b.oy - 3 * P - 235
        obj["motor"] = bb.draw_motor(mcx, my, stage == 2)
        for name, dx in (("motor-A-", -9), ("motor-A+", -3), ("motor-B+", 3), ("motor-B-", 9)):
            obj[name] = (mcx + dx * 1.0, my + 84 + 4)
        obj["_motor_cx"], obj["_motor_y"] = mcx, my
        fcx, fy = b.x(47.5), b.oy - 3 * P - 160
        obj["fan"] = bb.draw_fan(fcx, fy, stage == 7)
        obj["_fan"] = (fcx, fy)
    if b.num == 3:
        jx, jy = b.x(3), b.oy - 3 * P - 110
        svg, plus, minus = bb.draw_jack(jx, jy, stage == 6, label="5 V DC adapter, 2 A")
        obj["jack5"] = svg
        obj["jack5+"], obj["jack5-"] = plus, minus
        sx, sy = b.x(36), b.oy + 14 * P + 46
        svg, pads = bb.draw_led_strip(sx, sy, stage == 6)
        obj["strip"] = svg
        obj["strip+5V"], obj["strip-CKI"], obj["strip-DIN"], obj["strip-GND"] = pads
    return obj


def draw_part(p, boards, objs, stage):
    kind, b = p["kind"], boards[p["board"]]
    new = p["stage"] == stage
    pt = lambda e: b.pt(e[1], e[2])
    if kind == "eth":
        return bb.draw_eth(b, p["c1"], new)
    if kind == "tmc":
        return bb.draw_tmc(b, p["c1"], new)
    if kind == "devkit":
        return bb.draw_devkit(b, p["c1"], new)
    if kind == "dip":
        return bb.draw_dip(b, p["c1"], p["n"], p["name"], p["labels"], new)
    if kind == "ky":
        return bb.draw_ky040(b, p["c1"], p["title"], new)
    if kind == "button":
        return bb.draw_button(b, p["c1"], new)
    if kind == "res":
        return bb.draw_resistor(pt(p["a"]), pt(p["b"]), p["value"], p["label"], new, ldx=p.get("ldx", 0), ldy=p.get("ldy", 0))
    if kind == "cap":
        return bb.draw_cap_elec(pt(p["p"]), pt(p["m"]), p["label"], new)
    if kind == "capc":
        return bb.draw_cap_ceramic(pt(p["a"]), pt(p["b"]), p["label"], new)
    if kind == "diode":
        return bb.draw_diode(pt(p["a"]), pt(p["k"]), p["label"], new)
    if kind == "to92":
        return bb.draw_to92([pt(e) for e in p["legs"]], p["label"], new)
    if kind == "fanhdr":
        return bb.draw_header_pins(b, 46, "g", 4, ["GND", "+12V", "TACH", "PWM"], "fan plug fits here", new)
    if kind == "jack":
        return objs[1]["jack"]
    if kind == "motor":
        return objs[1]["motor"]
    if kind == "fan":
        o = objs[1]
        fcx, fy = o["_fan"]
        pts = [boards[1].pt(46 + i, "g") for i in range(4)]
        cols = ["#222", "#d9b800", "#2fb457", "#3a86ff"]
        s = [o["fan"]]
        for i, q in enumerate(pts):
            s.append(f'<path d="M{fnum(fcx - 12 + i * 8)} {fnum(fy + 96)} C{fnum(fcx - 12 + i * 8)} {fnum(fy + 120)} {fnum(q[0])} {fnum(q[1] - 60)} {fnum(q[0])} {fnum(q[1] - 18)}" '
                     f'fill="none" stroke="{cols[i]}" stroke-width="2.4"/>')
        return "".join(s)
    if kind == "strip":
        return objs[3]["strip"]
    if kind == "jack5":
        return objs[3]["jack5"]
    raise ValueError(kind)


def resolve(e, boards, objs):
    if e[0] == "obj":
        return objs[boards_key(e[1])][e[1]]
    return boards[e[0]].pt(e[1], e[2])


def boards_key(name):
    return 3 if name.startswith(("strip", "jack5")) else 1


def figure(stage, show, title):
    """Render one SVG for the given stage, showing the listed boards."""
    W = 70 + 62 * P + 90
    boards, objs, y = {}, {}, 8
    for n in show:
        pad = 95 if (n == 1 and stage == 1) else TOP_PAD[n]
        bpad = 45 if (n == 1 and stage < 3) else BOT_PAD[n]
        b = bb.Board(n, 70, y + pad, RAILS[n])
        boards[n] = b
        objs[n] = objects_for(b, stage)
        y += pad + 17 * P + bpad
    H = y
    out = [f'<svg class="fig" viewBox="0 0 {fnum(W)} {fnum(H)}" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="{esc(title)}">']
    for n in show:
        out.append(bb.board_svg(boards[n]))
    for p in PARTS:
        if p["stage"] <= stage and p["board"] in boards:
            out.append(draw_part(p, boards, objs, stage))
    # wires: old faint, new bold
    for w in sorted(WIRES, key=lambda k: (k["stage"] != stage, k["n"])):
        if w["stage"] > stage:
            continue
        faint = w["stage"] < stage
        ends = [w["a"], w["b"]]
        on = [e for e in ends if e[0] != "obj" and e[0] in boards]
        if w.get("cross"):
            for e, other in ((ends[0], ends[1]), (ends[1], ends[0])):
                if e[0] in boards:
                    p = boards[e[0]].pt(e[1], e[2])
                    top_half = e[2] in "jihgf" or e[2] in ("T1", "T2")
                    fdir = w.get("fdir") or ("down" if (e[0] == 2 and e[2] == "f") or not top_half else "up")
                    ln = 58 if fdir == "up" else (150 if e[2] == "f" else 74)
                    if e[2] in ("B1", "B2"):
                        ln = 48
                    txt = f"to B{other[0]}: {tag_hole(*other)}"
                    out.append(bb.flag_svg(p, w["color"], txt, w["n"], fdir, ln, faint))
            continue
        if not on:
            continue
        if len(on) == 2 and on[0][0] != on[1][0]:
            continue
        p0, p1 = resolve(ends[0], boards, objs), resolve(ends[1], boards, objs)
        up = w.get("up")
        if up is None:
            ys = [e[2] for e in ends if e[0] != "obj"]
            up = not all(r in "edcba" or r in ("B1", "B2") for r in ys)
        if ends[0][0] == "obj" or ends[1][0] == "obj":
            up = None if ends[0][0] == "obj" and ends[0][1].startswith(("jack", "motor")) else up
        via = None
        lift = w.get("lift")
        if ends[0][0] == "obj" and ends[0][1].startswith("motor"):
            via = [(p0[0], p0[1] + 18), (p1[0], p1[1] - 12)]
        elif ends[0][0] == "obj" and ends[0][1].startswith("strip") or ends[1][0] == "obj" and ends[1][1].startswith("strip"):
            lift = 24
            up = False
        out.append(bb.wire_svg(p0, p1, w["color"], w["n"], via=via, lift=lift, up=True if up is None else up, faint=faint, bt=w.get("bt", 0.5)))
    out.append("</svg>")
    return "".join(out)


def wire_rows(stage):
    rows = []
    for w in sorted((w for w in WIRES if w["stage"] == stage), key=lambda k: k["n"]):
        fill, edge = COL[w["color"]]
        rows.append(
            f'<tr><td class="n"><span class="bdg">{w["n"]}</span></td>'
            f'<td><span class="sw" style="background:{fill};border-color:{edge}"></span> {w["color"]}</td>'
            f'<td>{esc(end_text(w["a"]))}</td><td>{esc(end_text(w["b"]))}</td><td>{esc(w["why"])}</td></tr>')
    return "".join(rows)


# ---------------------------------------------------------------- page text
CSS = """
:root{--bg:#f7f6f2;--card:#fff;--ink:#1d2430;--mut:#5d6675;--line:#dcd8cc;--acc:#e8590c;--ok:#2b8a3e;--warn:#c92a2a;--note:#e7f1ff}
*{box-sizing:border-box}
html{scroll-behavior:smooth}
section{scroll-margin-top:56px}
body{margin:0;background:var(--bg);color:var(--ink);font:16px/1.55 system-ui,Segoe UI,Arial,sans-serif}
header.hero{background:#1d2430;color:#fff;padding:36px 20px 30px}
header.hero .in,main{max-width:1120px;margin:0 auto;padding:0 20px}
header.hero h1{margin:0 0 6px;font-size:30px}
header.hero p{margin:6px 0;color:#d6dbe5;max-width:70ch}
nav.toc{background:#fff;border-bottom:1px solid var(--line);position:sticky;top:0;z-index:5}
nav.toc .in{max-width:1120px;margin:0 auto;padding:8px 20px;display:flex;gap:6px 14px;flex-wrap:wrap;font-size:14px}
nav.toc a{color:#1d2430;text-decoration:none;padding:2px 8px;border-radius:12px;background:#eef0f4}
nav.toc a:hover{background:#dde3ee}
section{background:var(--card);border:1px solid var(--line);border-radius:10px;margin:22px 0;padding:22px 24px}
section h2{margin:0 0 4px;font-size:24px}
section h2 .step{display:inline-block;background:var(--acc);color:#fff;border-radius:6px;padding:0 9px;margin-right:8px;font-size:18px;vertical-align:2px}
section h3{margin:22px 0 6px;font-size:18px}
.lead{color:var(--mut);margin:0 0 12px}
.box{border-radius:8px;padding:10px 14px;margin:12px 0;border:1px solid}
.box.warn{background:#fff0f0;border-color:#f3b4b4}
.box.note{background:var(--note);border-color:#b9d3f5}
.box.check{background:#ecf8ef;border-color:#b5dfc0}
.box b.t{display:block;margin-bottom:2px}
table{border-collapse:collapse;width:100%;font-size:14px}
th,td{border:1px solid var(--line);padding:5px 8px;text-align:left;vertical-align:top}
th{background:#f0eee6}
td.n{width:44px;text-align:center}
.bdg{display:inline-block;min-width:22px;padding:0 6px;border-radius:11px;background:#1b1f27;color:#fff;font-weight:700;font-size:12px;line-height:22px;text-align:center}
.sw{display:inline-block;width:14px;height:14px;border-radius:7px;border:2px solid;vertical-align:-2px}
.figwrap{overflow-x:auto;border:1px solid var(--line);border-radius:8px;background:#fbfaf7;margin:12px 0}
svg.fig{display:block;width:100%;min-width:900px;height:auto}
code,kbd{background:#eef0f4;border-radius:4px;padding:1px 5px;font-size:.92em}
pre{background:#1d2430;color:#e8ecf3;border-radius:8px;padding:12px 14px;overflow-x:auto;font-size:13px}
pre code{background:none;color:inherit;padding:0}
ul.parts li{margin:3px 0}
.two{display:grid;grid-template-columns:1fr 1fr;gap:18px}
@media(max-width:800px){.two{grid-template-columns:1fr}}
.legend{display:flex;flex-wrap:wrap;gap:6px 16px;font-size:13px;margin:8px 0}
.legend span{display:inline-flex;align-items:center;gap:5px}
details{margin:10px 0}
summary{cursor:pointer;font-weight:600}
@media print{nav.toc{display:none}section{break-inside:avoid-page}header.hero{background:#fff;color:#000}header.hero p{color:#333}}
"""


def legend():
    items = [("red", "+12 V"), ("rose", "+5 V"), ("orange", "+3.3 V"), ("black", "Ground"), ("blue", "Speed knob"),
             ("purple", "Hue knob"), ("green", "Saturation knob"), ("yellow", "Value knob"), ("white", "Tap button"),
             ("pink", "Step"), ("brown", "Direction"), ("grey", "Driver enable"), ("teal", "UART / I2C clock"),
             ("cyan", "I2C data"), ("lime", "UART / LED data")]
    s = ['<div class="legend">']
    for c, t in items:
        fill, edge = COL[c]
        s.append(f'<span><i class="sw" style="background:{fill};border-color:{edge}"></i>{t}</span>')
    s.append("</div>")
    return "".join(s)


def howto_svg():
    """A small diagram of which breadboard holes are connected."""
    b = bb.Board(0, 60, 100, {"T1": ("+", "red"), "T2": ("−", "black"), "B1": ("−", "black"), "B2": ("+", "red")})
    W, H = 620, 300
    o = [f'<svg class="fig" style="min-width:0" viewBox="0 0 {W} {H}" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="How breadboard holes connect">']
    o.append('<svg x="0" y="0" width="620" height="300" viewBox="30 30 620 300" overflow="hidden">')
    o.append(bb.board_svg(b))
    for col, colr in ((8, "#ff9f1c"), (13, "#3a86ff")):
        for rows in ("jihgf", "edcba"):
            y0, y1 = b.y(rows[0]) - 8, b.y(rows[-1]) + 8
            o.append(f'<rect x="{fnum(b.x(col) - 7)}" y="{fnum(y0)}" width="14" height="{fnum(y1 - y0)}" rx="7" fill="{colr}" opacity=".30"/>')
    xr0, xr1 = b.x(2), b.x(22)
    for r in ("T1", "B2"):
        o.append(f'<rect x="{fnum(xr0)}" y="{fnum(b.y(r) - 7)}" width="{fnum(xr1 - xr0)}" height="14" rx="7" fill="#ff9f1c" opacity=".30"/>')
    o.append("</svg>")
    o.append("</svg>")
    return "".join(o)


def build():
    base = bb.base_symbol()
    parts_table = [
        ("Breadboards", "3 full-size, 830-point boards (63 columns, 10 lettered rows, 2 power rails on each long edge)"),
        ("ESP32-S3-ETH", "Waveshare ESP32-S3-ETH **with the header pins soldered on** (the pre-soldered version). USB-C cable."),
        ("TMC2209 stepper driver", "BigTreeTech TMC2209 V1.3 (or a compatible StepStick-style TMC2209) with header pins"),
        ("Stepper motor", "NEMA17, for example StepperOnline 17HS08-1004S (black, green, red, blue wires)"),
        ("12 V power", "12 V DC adapter, 1 A or more, and a barrel-jack-to-screw-terminal adapter (or a bench supply)"),
        ("5 V power", "5 V DC adapter, 2 A or more, and a second barrel-jack-to-screw-terminal adapter"),
        ("MCP23017-E/SP", "28-pin DIP I2C port expander (the PCB uses the surface-mount version)"),
        ("74AHCT125 (DIP-14)", "or 74HCT125. The PCB uses two single-gate 74AHCT1G125s"),
        ("KY-040 rotary encoder modules", "4 pieces, 5-pin"),
        ("Push button", "1 tactile button (4-leg, 6 mm)"),
        ("LED strip", "8 LEDs, APA102 or SK9822 (data and clock), 5 V, with 4 wires or pads (+5V, CKI or CI, DIN or DI, GND)"),
        ("Resistors (1/4 W)", "1 kΩ ×3 (R9, R23, R57), 4.7 kΩ ×3 (R21, R22, R59), 330 Ω ×2 (R18, R61), 10 kΩ ×3 (R26, R62, R58)"),
        ("Capacitors", "100 µF 35 V electrolytic ×1 (use 2 if you have them, in parallel), 0.1 µF ceramic ×3"),
        ("Diode", "1N5819 (or 1N5822) Schottky ×1"),
        ("Fan section (optional)", "12 V 4-wire PWM fan (ARCTIC P12 PWM or Noctua NF-P12 redux), 2N7000 (TO-92; a stand-in for the board's SOT-23 2N7002) ×1, 4-pin male header"),
        ("Jumper wires", "A pack of 65+ solid-core jumpers in assorted lengths (the pictures use wire colours; use what you have), plus 14 long (20–30 cm) male-to-male jumpers to join the boards"),
        ("Tools", "Multimeter, small wire cutter / tweezers, a computer with the Arduino CLI or IDE"),
    ]
    h = []
    h.append(f'<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">'
             f'<title>Breadboard Guide</title><style>{CSS}</style></head><body>')
    h.append(f'<svg width="0" height="0" style="position:absolute"><defs>{base}</defs></svg>')
    h.append('<header class="hero"><div class="in"><h1>Breadboard the Liquid Turntable</h1>'
             '<p>A picture-by-picture guide to building the whole controller on solderless breadboards before the circuit board is made. '
             'No soldering of the circuit, no experience needed: you push parts into holes and join them with jumper wires, one small step at a time, '
             'and test after each step.</p>'
             '<p>Every connection here comes from the project\'s schematic, so what you build behaves like the real board.</p></div></header>')
    h.append('<nav class="toc"><div class="in"><a href="index.html">&larr; All documentation</a><a href="#start">Before you start</a><a href="#s1">1 ESP32</a><a href="#s2">2 Motor</a>'
             '<a href="#s3">3 Speed knob</a><a href="#s4">4 More knobs</a><a href="#s5">5 Expander</a><a href="#s6">6 Lights</a>'
             '<a href="#s7">7 Fan</a><a href="#final">Final check</a><a href="#ref">Reference</a></div></nav><main>')

    # ---- before you start
    h.append('<section id="start"><h2>Before you start</h2><p class="lead">Read this page once; it saves mistakes later.</p>')
    h.append('<h3>The plan</h3><p>The turntable controller is built from several circuits. You will build them on <b>three breadboards</b>, one stage at a time, '
             'checking that each stage works before adding the next:</p><ol>'
             '<li><b>Brain board</b>: the ESP32-S3-ETH (the main computer) and the stepper driver that moves the motor.</li>'
             '<li><b>Panel board</b>: four knobs, a tap button and a small chip (an I2C expander) that reads three of the knob buttons.</li>'
             '<li><b>Lighting board</b>: a signal-boosting chip and a short LED strip standing in for the 178-LED ring, driven by the ESP32-S3-ETH itself.</li></ol>')
    h.append('<div class="box warn"><b class="t">Safety rules (these protect your parts and you)</b><ul>'
             '<li><b>Power off before you change any wire.</b> Unplug the 12 V adapter and the USB cables first.</li>'
             '<li><b>Never plug or unplug the motor while the 12 V is on.</b> This can destroy the driver chip.</li>'
             '<li>Do <b>not</b> connect mains (wall) power to anything here except through the finished 12 V adapter. There is no mains wiring on a breadboard.</li>'
             '<li>The 12 V rail and the 3.3 V / 5 V rails must <b>never touch</b>. Keep red 12 V wires well away from orange 3.3 V wires.</li></ul></div>')
    h.append('<h3>How a breadboard works</h3><div class="two"><div class="figwrap" style="margin:0">' + howto_svg() + '</div><div>'
             '<ul><li>Each short vertical line of <b>5 holes</b> (one column, in the top half or the bottom half) is joined inside. '
             'In the picture the <span style="background:#ffd9a0;padding:0 4px;border-radius:4px">orange</span> and <span style="background:#c5d9ff;padding:0 4px;border-radius:4px">blue</span> stripes show two such columns.</li>'
             '<li>The top half and the bottom half are <b>not</b> joined. The channel in the middle separates them; chips straddle it.</li>'
             '<li>The long lines along the edges are <b>power rails</b>. Every hole in one rail line is joined. We use them for 12 V, 3.3 V, 5 V and ground (GND).</li>'
             '<li><b>Some breadboards split each rail in the middle.</b> If yours does, bridge the gap with a jumper, or your power will stop halfway along.</li>'
             '<li>Each hole has a name: its <b>row letter</b> then its <b>column number</b>, like <code>h13</code>. Rails are named by what they carry, like "GND rail near column 16".</li></ul>'
             '</div></div>')
    h.append('<h3>How to read the pictures</h3><ul>'
             '<li>Turn each breadboard so the <b>row letters</b> and <b>column numbers</b> printed on it match the picture (letter <code>j</code> at the top, column 1 on the left).</li>'
             '<li>A <b style="color:#e8590c">dashed orange outline</b> marks a part you add in the current step. Wires from earlier steps are shown faded.</li>'
             '<li>Each new wire has a <b>numbered black circle</b>. The table under the picture lists that number, the wire colour (a suggestion; any colour works), where it starts and where it ends.</li>'
             '<li>A wire that goes to <b>another breadboard</b> ends in a vertical tag that says where the other end goes ("to Board 2: f27"). Use long jumper wires for these.</li>'
             '<li>Press parts in <b>straight</b> and firmly. Half-inserted pins are the most common cause of "it does not work".</li></ul>')
    h.append(legend())
    h.append('<h3>Parts you need</h3><table><tr><th>Part</th><th>What to get</th></tr>')
    for a, bx in parts_table:
        h.append(f'<tr><td><b>{esc(a)}</b></td><td>{esc(bx).replace("**", "")}</td></tr>')
    h.append('</table><p class="lead">Resistor colour bands: 330 Ω orange-orange-brown, 1 kΩ brown-black-red, 4.7 kΩ yellow-violet-red, 10 kΩ brown-black-orange.</p>')
    h.append('<h3>Software you need first</h3><p>The ESP32-S3-ETH runs this project\'s firmware. Install the <b>Arduino CLI</b> (or the Arduino IDE) and the ESP32 board support, then see '
             '<a href="files/README.md#building--flashing">Building / flashing</a> in the README. It also drives the LEDs, so there is nothing else to flash.</p>')
    h.append('<div class="box note"><b class="t">Where the breadboard differs from the real circuit board</b>'
             'The breadboard is built for learning and testing, so it leaves out some protection parts that matter on the finished board: '
             'the 2 A resettable fuse, the 3.3 V converter (the ESP32 module makes the 3.3 V for you here), the surge and static diodes, the reverse-polarity circuit, '
             'and the 178-LED ring. The final <a href="#ref">reference section</a> lists them all. Wiring is the same everywhere else.</div></section>')

    # ---- stage text
    T = TMC_C1
    w2 = [w["n"] for w in WIRES if w["stage"] == 2]
    w2a, w2b = min(w2), max(w2)

    def stage(sid, num, title, lead, show, parts_html, steps_html, check_html, extra=""):
        stg = int(sid[1:])
        h.append(f'<section id="{sid}"><h2><span class="step">{num}</span>{esc(title)}</h2><p class="lead">{lead}</p>')
        h.append(parts_html)
        h.append(steps_html)
        for n in show:
            h.append(f'<div class="figwrap">{figure(stg, [n] if len(show) > 1 and False else show, title)}</div>')
            break
        h.append('<h3>Wires to add</h3><table><tr><th>#</th><th>Colour</th><th>From</th><th>To</th><th>What it does</th></tr>' + wire_rows(stg) + '</table>')
        h.append(extra)
        h.append(check_html)
        h.append("</section>")

    stage("s1", 1, "The ESP32-S3-ETH and ground",
          "The main computer. It also makes the 3.3 V that powers everything else on the breadboards.", [1],
          '<h3>Parts for this step</h3><ul class="parts"><li>Breadboard 1</li><li>ESP32-S3-ETH (header pins soldered on), USB-C cable</li><li>3 jumper wires</li></ul>'
          '<div class="box note"><b class="t">Why no 3.3 V converter?</b>On the finished board a separate converter makes the 3.3 V. On the breadboard the ESP32-S3-ETH\'s own regulator does it, powered from USB, and its <code>3V3</code> pin supplies the other chips. The loads here are small (the driver\'s logic, one chip and four knobs).</div>',
          '<h3>Do this</h3><ol>'
          '<li>Put <b>Breadboard 1</b> in front of you with row letters matching the picture. Join the rails by adding wire 3 first.</li>'
          '<li><b>Plug the ESP32-S3-ETH across the centre channel.</b> Its <b>USB-C and Ethernet end goes to the left</b>. Its first pin (<i>pin 1</i>, the end of each pin row nearest the USB-C port) goes in <b>column 9</b>; '
          'the pins fill columns 9 to 28. One row of pins lands in row <code>h</code> and the other in row <code>c</code>. <b>Check:</b> the pin labels printed on the module should read GP21, GP17 (and so on) along the top row; '
          'they are drawn on the picture. If the printed labels run the other way, the module is backwards.</li>'
          '<li>Add wires 1 and 2 (ground) and 3 (links the top and bottom ground rails). Do <b>not</b> connect the pin labelled <code>3V3_EN</code> to anything: on the finished board it is grounded, but here the module must make its own 3.3 V.</li></ol>',
          '<div class="box check"><b class="t">Test it</b>'
          '<ol><li>Plug the USB-C cable from your computer into the <b>ESP32-S3-ETH</b>. A light on the module comes on.</li>'
          '<li>Flash the firmware as described in the README (the <code>arduino-cli compile</code> / <code>upload</code> commands there; the board name must have <code>CDCOnBoot=cdc</code>). '
          'Open the serial monitor at <b>115200 baud</b>. You should see the boot messages and, with an Ethernet cable plugged in, <code>ETH got IP</code>.</li>'
          '<li>With a multimeter set to DC volts, put the black probe on a GND rail and the red probe on hole <code>i13</code> (the module\'s 3V3 pin). You should read <b>3.3 V</b> (3.2 to 3.4).</li></ol>'
          '<b>Nothing lights up?</b> Try another USB cable (some only charge) and check the module is pressed all the way in.</div>')

    stage("s2", 2, "Stepper driver and motor",
          "The TMC2209 takes STEP and DIR pulses from the ESP32 and drives the motor coils with 12 V.", [1],
          '<h3>Parts for this step</h3><ul class="parts"><li>TMC2209 driver module (pins soldered on)</li><li>NEMA17 motor</li><li>12 V adapter with screw-terminal jack</li>'
          '<li>1N5819 diode, 100 µF 35 V capacitor</li><li>Two 1 kΩ resistors (R9 and R23)</li><li>About 20 jumper wires</li></ul>',
          '<div class="box warn"><b class="t">Power order matters</b>Unplug <b>both</b> the 12 V adapter and the USB cable before wiring this step. '
          'Never plug in or unplug the motor with 12 V on. Never power the 12 V with the driver or motor wires loose.</div>'
          '<h3>Do this</h3><ol>'
          f'<li><b>Place the driver.</b> Pins 1 to 8 of one row go in <b>columns {T} to {T + 7}</b> of the bottom pin row (<code>c</code>) and the other row in the top pin row (<code>g</code>). '
          f'The end labelled <b>EN</b> / <b>VM</b> goes to the <b>left</b> (column {T}). <b>Read the labels printed on your module</b> and check against the picture before you press it in: '
          'a driver put in backwards will be destroyed when power is applied.</li>'
          f'<li>Add the diode <b>D1</b> from <code>j33</code> to <code>j{T}</code> with the <b>stripe (cathode) on the right</b>, at the driver end. The stripe must point toward the driver.</li>'
          f'<li>Add the <b>100 µF capacitor</b>. Electrolytic capacitors have a <b>+ leg (longer)</b> and a stripe on the <b>− side</b>. The + leg goes in <code>i{T}</code> and the stripe (−) leg in <code>i{T + 1}</code>. '
          'Backwards, it can pop. Check twice.</li>'
          f'<li>Add the two 1 kΩ resistors (R23 from <code>j25</code> to <code>j31</code>, R9 from <code>a{T - 2}</code> to <code>a{T + 4}</code>), then wires {w2a} to {w2b} from the table. Do the power wires (red and black from the adapter) <b>last</b>.</li>'
          '<li><b>Check the 12 V adapter first.</b> With a multimeter on DC volts, confirm it reads +12 V (about 11 to 13 V) between its + and − terminals, and that the + terminal really is the positive one. Barrel-jack adapters are normally centre-positive, but check: reversed power will damage the driver.</li>'
          f'<li>Connect the motor wires <b>with everything off</b>: green → <code>i{T + 2}</code>, black → <code>i{T + 3}</code>, red → <code>i{T + 4}</code>, blue → <code>i{T + 5}</code>. '
          '(A motor wire set usually ends in a plug; use a plug-to-jumper lead, or twist the bare ends onto jumper-wire pins.)</li></ol>',
          '<div class="box check"><b class="t">Test it</b><ol>'
          '<li>Power: plug in USB (ESP32), then the 12 V adapter. Never the other way with the motor loose.</li>'
          '<li>The serial monitor shows the driver being set up: look for <code>TMC2209 UART</code> lines such as <code>microsteps confirmed</code> and <code>current reference is UART</code>.</li>'
          '<li>The motor shaft should feel <b>held</b> (stiffer to turn by hand).</li>'
          '<li>Open <code>http://liquidturntable.local/live</code> on a phone or computer on the same network and press <b>Start</b>. The shaft should turn smoothly. Press <b>Stop</b>.</li></ol>'
          '<b>Motor only buzzes, shudders or turns roughly?</b> The coil wires are paired wrongly. Switch everything off and unplug the motor. With a multimeter on the ohms range, find which two motor wires read a few ohms between them: those are one coil, and they must go to the matching pair of columns (A− and A+ together, B+ and B− together). Move the wires so each coil\'s pair sits in its own two columns. '
          '<b>Turns the wrong way?</b> That is fine: tick <b>Reverse motor direction</b> on the settings page.</div>')

    stage("s3", 3, "The speed knob and the tap button",
          "Start the panel board: the main speed knob (a KY-040 rotary encoder) and the TAP button.", [1, 2],
          '<h3>Parts for this step</h3><ul class="parts"><li>Breadboard 2</li><li>1 KY-040 knob module</li><li>1 push button</li><li>About 12 jumper wires, 6 of them long (to join the two boards)</li></ul>',
          '<h3>Do this</h3><ol>'
          '<li>Switch everything off.</li>'
          f'<li>On Breadboard 2, <b>plug the KY-040</b> into row <code>j</code>, columns {KY_ENC} to {KY_ENC + 4}, with the knob facing up and <b>the module hanging off the top edge</b>. '
          'Reading its labels left to right the pins are <b>GND, +, SW, DT, CLK</b>, as in the picture. (If it feels wobbly, you can instead use female-to-male jumper wires from the module\'s pins to the same holes.)</li>'
          '<li>Press the <b>button</b> across the centre channel, columns 56 and 58. It has four legs; this works whichever way round it goes.</li>'
          '<li>Add the wires. The wires marked with a tag go to the <b>other board</b>: for each, connect one end to the hole named on <b>Board 1</b> and the other to the hole named on <b>Board 2</b>.</li></ol>',
          '<div class="box check"><b class="t">Test it</b><ol><li>Power up (USB first, then 12 V).</li>'
          '<li>On the phone page (<code>/live</code>), turn the speed knob clockwise a few clicks: the speed figure rises and the motor starts to turn. Counter-clockwise past zero reverses it.</li>'
          '<li>Press the knob once: it jumps to the home speed. Press again: it stops.</li>'
          '<li>Press the TAP button four times in time: the BPM shown changes.</li></ol>'
          '<b>The number goes up two or four per click?</b> Normal for some modules; the README ("Encoder step size") says what to change. '
          '<b>Nothing happens?</b> Check that + goes to 3V3 (not GND) and the module is in row <code>j</code>.</div>')

    stage("s4", 4, "The other three knobs",
          "Hue, Saturation and Value (brightness): same wiring as the speed knob, different pins.", [1, 2],
          '<h3>Parts for this step</h3><ul class="parts"><li>3 KY-040 knob modules</li><li>12 jumper wires (6 short, 6 long)</li></ul>',
          '<h3>Do this</h3><ol>'
          '<li>Plug the three KY-040 modules into row <code>j</code> of Breadboard 2: <b>HUE</b> in columns 3–7, <b>SAT</b> in 11–15, <b>VAL</b> in 19–23 (all with GND on the left, CLK on the right). Leave a gap of one column between modules: each is about 19 mm wide.</li>'
          '<li>Add the wires from the table: power wires (black and orange) to the rails, and the long tagged wires to Board 1.</li>'
          '<li>The knobs\' push buttons (SW pins) are <b>not wired yet</b>. They go through the expander chip in the next step.</li></ol>',
          '<div class="box check"><b class="t">Test it</b>Open the <code>/live</code> page. Turn <b>HUE</b>: the colour value changes; <b>SAT</b>: how rich; <b>VAL</b>: brightness. '
          '(The LEDs are not connected yet, so you only see the numbers change.)</div>')

    stage("s5", 5, "The I2C expander and the four knob buttons",
          "The ESP32 has run out of pins, so a small chip (MCP23017) reads the four knob buttons and passes the result on over two wires.", [2],
          '<h3>Parts for this step</h3><ul class="parts"><li>MCP23017-E/SP (28-pin DIP chip)</li><li>Two 4.7 kΩ resistors (R21, R22)</li><li>0.1 µF ceramic capacitor</li><li>12 wires</li></ul>',
          '<h3>Do this</h3><ol>'
          '<li>Find <b>pin 1</b> of the chip: the end with the half-round notch or dot. Pins number up one side, then back down the other (a U shape).</li>'
          '<li>Press the chip across the centre channel with <b>pin 1 at column 37 on the bottom row (<code>e</code>)</b> and the notch on the left. '
          'Chip legs bend easily: straighten them against a table edge first.</li>'
          '<li>Add the two 4.7 kΩ pull-up resistors and the small ceramic capacitor (it has no polarity).</li>'
          '<li>Add the wires. The first six wires in the table give the chip power and set its address; SDA and SCL (cyan and teal) go to Board 1; the three button wires go from each knob\'s <b>SW</b> pin to the chip.</li></ol>',
          '<div class="box check"><b class="t">Test it</b>Power up. Press the <b>HUE</b> knob: the colour resets to red. <b>SAT</b>: toggles white. <b>VAL</b>: brightness returns to 100%. '
          'If a button does nothing, check its single wire first, then the 3V3 and GND wires to the chip. The serial log reports if the expander is not found.</div>')

    stage("s6", 6, "Lighting: the LED buffers and the LED strip",
          "The ESP32-S3-ETH drives the LEDs itself. A 74AHCT125 chip lifts its 3.3 V data and clock signals to 5 V for the LEDs, "
          "and a 5 V adapter powers the strip.", [3, 1],
          '<h3>Parts for this step</h3><ul class="parts"><li>Breadboard 3, 74AHCT125 chip, 330 Ω ×2, 10 kΩ ×2, 0.1 µF</li>'
          '<li>8-LED APA102 or SK9822 strip, 4 wires or pads</li><li>5 V DC adapter (2 A) and a barrel-jack-to-screw-terminal adapter</li>'
          '<li>About 24 wires</li></ul>'
          '<div class="box note"><b class="t">Nothing to set up</b>The firmware drives an SK9822 ring on GPIO18 (data) and GPIO2 (clock) as delivered, '
          'and the strip shows the first eight LEDs of it. The settings are on the <b>LEDs</b> tab of the settings page. '
          'Each LED is held to 36.6 mA, so the 8-LED strip draws at most about 0.3 A.</div>',
          '<h3>Do this</h3><ol>'
          '<li>Switch everything off. Press the <b>74AHCT125</b> chip across the channel, <b>pin 1 (notch end) at column 34</b>, bottom row. '
          'Add R18, R26, R61, R62 and the 0.1 µF capacitor between the two top rails.</li>'
          '<li>Power: connect the <b>5 V adapter</b> to the top rails (+ to +5V, − to GND). Never join the 5 V rails to the 3.3 V or 12 V rails.</li>'
          '<li>Wire the chip. Gate 1 carries the data and gate 2 the clock; the extra wires tie the two unused gates down so they do not pick up noise.</li>'
          '<li>Join the two boards: ground, GPIO18 (data) and GPIO2 (clock).</li>'
          '<li>Connect the strip: +5V and GND to the rails, <b>DIN</b> to the chip\'s pin 3 and <b>CKI</b> to its pin 6. Check the pad names on your strip: some say DI and CI.</li></ol>',
          '<div class="box check"><b class="t">Test it</b>Power up (USB for the ESP32, the 5 V adapter, then 12 V). The <b>LEDs</b> tab should show '
          '<i>LED engine, SK9822</i> at about 100 frames a second. Turn the HUE knob: the strip changes colour; SAT changes how rich, VAL changes brightness. '
          'Press the SAT knob: the strip goes white; press again: the colour returns.<br><b>Strip does nothing?</b> Check that DIN and CKI are not swapped, '
          'that the strip has 5 V at its +5V pad, and that the GND link between the boards is in. '
          '<b>Wrong colours?</b> Change <b>Colour order</b> on the LEDs tab (RBG for the SK9822; many APA102 strips are BGR).<br>'
          '<b>Only have a WS2812B strip?</b> Set <b>LED type</b> to WS281x and order GRB on the LEDs tab, and wire only DIN; the clock gate is then unused.</div>')

    stage("s7", 7, "Optional: the cooling fan",
          "A 12 V PWM fan on a small transistor switch. Skip this stage if you have no fan.", [1, 2],
          '<h3>Parts for this step</h3><ul class="parts"><li>12 V 4-wire PWM fan</li><li>2N7000 transistor (TO-92; a stand-in for the SOT-23 2N7002 on the board)</li><li>R57 1 kΩ, R58 10 kΩ, R59 4.7 kΩ</li><li>4-pin male header, 9 wires</li></ul>',
          '<div class="box warn"><b class="t">Check the 2N7000 pinout</b>With the flat face towards you and the legs down, the legs of a <b>2N7000</b> are <b>Source, Gate, Drain</b> from left to right. '
          'The look-alike <b>BS170</b> is <b>Drain, Gate, Source</b>: the opposite. Check your part\'s datasheet; a swapped transistor will not damage anything but the fan will not work.</div>'
          '<div class="box warn"><b class="t">Use a 12 V fan</b>A 5 V fan on this circuit will be damaged. Only fans that are marked 12 V and have 4 wires (ground, +12 V, tach, PWM).</div>'
          '<h3>Do this</h3><ol>'
          '<li>Press the 4-pin male header into row <code>g</code>, columns 46 to 49 (GND, +12V, TACH, PWM left to right) and plug the fan\'s 4-pin connector onto it.</li>'
          '<li>Add the transistor and the three resistors, then the wires in the table.</li></ol>',
          '<div class="box check"><b class="t">Test it</b>With the firmware running, the fan follows the chip temperature (it starts at the minimum speed, 25%). '
          'The status page shows <b>tach turning</b>. As a safety test, unplug the USB (ESP32 off) with 12 V still on: the fan should go to full speed.</div>')

    # ---- final check
    h.append('<section id="final"><h2>The finished system</h2><p class="lead">All three boards together.</p>')
    h.append(f'<div class="figwrap">{figure(7, [1, 2, 3], "The finished breadboards")}</div>')
    h.append('<div class="box check"><b class="t">Final checklist</b><ul>'
             '<li>Speed knob: speeds up, slows, reverses; its button jumps to home speed and stops.</li><li>TAP button: sets tempo.</li>'
             '<li>HUE / SAT / VAL knobs and their buttons change the strip.</li><li>The <code>/live</code> and settings pages open; the log shows no errors.</li>'
             '<li>Switching off: turn the <b>12 V adapter off first</b>, wait a few seconds, then unplug the USB cables.</li></ul></div></section>')

    # ---- reference
    h.append('<section id="ref"><h2>Reference</h2>')
    h.append('<h3>What the breadboard leaves out</h3><table><tr><th>On the circuit board</th><th>On the breadboard</th><th>Why it is safe to leave out</th></tr>'
             '<tr><td>2 A resettable fuse on the 12 V side (the 5 V side has no fuse)</td><td>None</td><td>Small loads, and you are watching. Use a bench supply with a current limit of about 1 A if you have one.</td></tr>'
             '<tr><td>TCA9555 expander (surface-mount, TSSOP-24)</td><td>MCP23017 (28-pin DIP)</td><td>The firmware drives either one: same address, same pins by function (GPAn = IO0_n, GPBn = IO1_n).</td></tr>'
             '<tr><td>Surge and static diodes (TVS), reverse-polarity FET</td><td>Only the 1N5819 diode on 12 V</td><td>They protect against faults you do not have on a bench.</td></tr>'
             '<tr><td>1 kΩ and 100 Ω resistors and a TVS on every knob wire</td><td>Direct wires</td><td>Static protection for the panel wiring; not needed on a bench.</td></tr>'
             '<tr><td>Two 74AHCT1G125 single-gate buffers (SMD)</td><td>74AHCT125 DIP, two of four gates used</td><td>Same function.</td></tr>'
             '<tr><td>33 Ω resistors R63/R64 at the buffer outputs, and D33 feeding the buffers</td><td>Direct wires and the 5 V rail</td><td>They damp the cable to the ring and guard against a reversed supply; a short breadboard lead does not need them.</td></tr>'
             '<tr><td>178-LED SK9822 ring, about 4.5 A</td><td>8-LED strip from a 5 V adapter</td><td>Keeps the current small. The strip proves the data and clock path.</td></tr>'
             '<tr><td>Bulk capacitors (2 × 100 µF), bleeder resistor</td><td>One 100 µF capacitor</td><td>Enough to keep the driver steady at this size.</td></tr>'
             '<tr><td>Ring thermistor on GPIO3 (10 kΩ pull-up, 1 kΩ, 100 nF; the NTC on the ring)</td><td>GPIO3 left open</td><td>The firmware reports the ring sensor as open and runs the fan at full speed with a 3 A ring limit, which does not matter for an 8-LED strip.</td></tr></table>')
    h.append('<h3>Every pin used, by signal</h3><table><tr><th>Signal</th><th>ESP32 GPIO</th><th>ESP32-S3-ETH header</th><th>Goes to</th></tr>'
             '<tr><td>STEP</td><td>46</td><td>H2 pin 6</td><td>TMC2209 STEP</td></tr><tr><td>DIR</td><td>48</td><td>H2 pin 4</td><td>TMC2209 DIR</td></tr>'
             '<tr><td>ENABLE</td><td>0</td><td>H1 pin 17</td><td>TMC2209 EN (and 1 kΩ to 3V3)</td></tr>'
             '<tr><td>UART RX / TX</td><td>15 / 47</td><td>H1 pin 12 / H2 pin 5</td><td>TMC2209 PDN (TX through 1 kΩ)</td></tr>'
             '<tr><td>Speed knob CLK / DT</td><td>38 / 39</td><td>H2 pins 14 / 12</td><td>KY-040 (Panel board); its button goes to the expander</td></tr>'
             '<tr><td>HUE knob CLK / DT</td><td>1 / 40</td><td>H1 pin 16 / H2 pin 11</td><td>KY-040</td></tr>'
             '<tr><td>SAT knob CLK / DT</td><td>43 / 44</td><td>H1 pins 20 / 19</td><td>KY-040</td></tr>'
             '<tr><td>VAL knob CLK / DT</td><td>41 / 42</td><td>H2 pins 10 / 9</td><td>KY-040</td></tr>'
             '<tr><td>TAP button</td><td>21</td><td>H1 pin 6</td><td>Push button to GND</td></tr>'
             '<tr><td>I2C SDA / SCL</td><td>17 / 16</td><td>H1 pins 7 / 9</td><td>MCP23017 pins 13 / 12</td></tr>'
             '<tr><td>LED data / clock</td><td>18 / 2</td><td>H1 pins 10 / 15</td><td>74AHCT125 pins 2 / 5 through 330 Ω</td></tr>'
             '<tr><td>Fan PWM</td><td>45</td><td>H2 pin 7</td><td>2N7000 gate via 1 kΩ</td></tr></table>')
    h.append('<h3>Where each knob button goes</h3><p>The four knob buttons are read by the expander: HUE → GPA0 (pin 21), speed → GPA3 (pin 24), VAL → GPA5 (pin 26), SAT → GPB5 (pin 6), fan tach → GPA6 (pin 27).</p>')
    h.append('<h3>Troubleshooting</h3><ul><li><b>Always check first:</b> is it plugged in firmly? is the wire in the right <i>column</i> and the right <i>half</i> (top or bottom) of the board?</li>'
             '<li><b>Random behaviour:</b> a missing ground. Every board must share ground, with the link wires in.</li>'
             '<li><b>The module gets hot:</b> unplug it now. Something is backwards (a chip, a capacitor or the driver).</li>'
             '<li><b>Useful tool:</b> set a multimeter to "continuity" (the beep symbol) and touch both ends of a wire; it beeps if the connection is good. '
             'Use it to check that a pin and the hole you wired are really connected.</li></ul>')
    h.append('<p class="lead">Source of the wiring: the mainboard schematic. This page is generated by <code>docs/breadboard/build_breadboard_guide.py</code>.</p></section>')
    h.append("</main></body></html>")
    return "".join(h)


if __name__ == "__main__":
    problems, groups = verify()
    if problems:
        print("\n".join(problems))
        raise SystemExit("breadboard does not match the schematic")
    print("verified against the schematic:", len(groups), "nets,", len(WIRES), "wires")
    html = build()
    with open(OUT, "w", encoding="utf-8", newline="\n") as f:
        f.write(html)
    print("wrote", OUT, len(html) // 1024, "KB;", len(WIRES), "wires")
