main
John Lauer Software 1.3.1: test-stage firmware (J4 TMC2209, HOME, limits, self-test), Stage tab and Calibrate in smi-dash (simulat… c0c5c9b
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Turn the board's control map into the firmware's control table and the
dashboard's copy, so both always agree on every channel, scale and limit.

    python3 controls/gen_controls.py controls/control-map.json

Reads the board's own schema ("interferometer/control-map/1", the file the
board design publishes as design/control-map.json) and normalises it. Values
the board map leaves to software (laser ramp rate, the firmware's current trip
level, the DAC reference voltage) are set in SOFTWARE_CHOICES below.

Writes firmware/src/smi_controls_gen.h and dashboard/assets/controls.json.
Both carry the same FNV-1a hash of the normalised map; the firmware reports it
in every STATE frame and the dashboard warns when the two differ.
"""
import json
import re
import math
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
ROOT = HERE.parent
KINDS = {"dac": 1, "switch": 2}
UNITS = ["mA", "V", "ohm", "x", "V/V"]
# DAC parts with a firmware driver. MCP4728 is refused on purpose: it reloads
# EEPROM values at power-up, so the laser set-point would not be zero at boot.
DAC_PARTS = {"DAC7574": 1, "DAC121C085": 2}   # 2: write-then-readback, on the laser head
EXPANDER_PARTS = {"MCP23008": 1}
EXP_BASE = 32   # switch bits >= 32 are MCP23008 bits (32 + bit)
ADS_PGA = {6.144: 0, 4.096: 1, 2.048: 2, 1.024: 3, 0.512: 4, 0.256: 5}
ADS_DR = {8: 0, 16: 1, 32: 2, 64: 3, 128: 4, 250: 5, 475: 6, 860: 7}

SOFTWARE_CHOICES = {
    "vdac_supply_V": 3.3,      # "filtered PICO_3V3"
    "vadc_ref_V": 3.3,         # ADC_VREF, filtered from 3V3 (rail monitor scale)
    "laser_ramp_mA_per_s": 40.0,
    "laser_trip_mA": 116.0,    # above the head DAC's 110.4 mA top, below the 123.9 mA hardware cutoff
    # Laser set-point writes at most this often. On the 1.2.1 head every write
    # disarms it and its soft-start ramps the current up from zero again, so the
    # firmware writes each new target in one step and rate-limits the writes.
    "laser_min_write_ms": 250,
    "laser_disarm_us": 2000,   # GP6 low this long before any head write (board patch LASER_DISARM_US)
    "isense_rate_hz": 50,   # ADS1115 runs at 128 SPS; read the latest conversion at 50 Hz
    # The external TIA's reference is not in the board map; the simulator assumes 0.25 V.
}
MAX_CONTROLS = 12
MAX_SETTINGS = 8


def fail(msg):
    sys.exit(f"ERROR: control map: {msg}")


def fnv1a(data: bytes) -> int:
    h = 0x811C9DC5
    for b in data:
        h ^= b
        h = (h * 0x01000193) & 0xFFFFFFFF
    return h


def _par(a, b):
    return a * b / (a + b)


def _eval_eq(expr, **names):
    """Evaluate a board-map equation ("a || b" is the parallel combination)."""
    import re
    e = expr.split("=", 1)[-1] if "=" in expr and not expr.strip().startswith("1000") else expr
    while "||" in e:
        e2 = re.sub(r"\(\s*([0-9.e+]+)\s*\|\|\s*([0-9.e+]+)\s*\)", r"_par(\1, \2)", e)
        if e2 == e:
            fail(f"cannot parse equation {expr!r}")
        e = e2
    return eval(e, {"__builtins__": {}, "_par": _par}, names)


def from_board_schema(b):
    """interferometer/control-map/1 -> the normalised input form."""
    sc = SOFTWARE_CHOICES
    dev = b["i2c"]["devices"]
    part = dev["dac"]["mpn"]
    part = next((k for k in list(DAC_PARTS) + ["MCP4728"] if part.startswith(k)), part)
    if part == "MCP4728":
        fail("MCP4728 restores EEPROM values at power-up; the laser must be off at boot. Use a DAC that resets to zero.")
    if part not in DAC_PARTS:
        fail(f"DAC {dev['dac']['mpn']} has no firmware driver")
    ctr = b["controls"]
    vd = sc["vdac_supply_V"]
    out = {
        "map_version": f"{b.get('hardwareVersion', '?')}-{b.get('status', '?')}",
        "i2c": {"bus": int(b["i2c"]["controller"][-1]), "sda": b["i2c"]["sda"]["gpio"], "scl": b["i2c"]["scl"]["gpio"], "hz": b["i2c"]["speedHz"]},
        "dacs": [{"dev": 0, "part": part, "i2c_addr": int(dev["dac"]["address"], 16), "bits": dev["dac"]["resolutionBits"], "vref_V": vd}],
        "laser_enable": {"gpio": ctr["laserEnable"]["gpio"], "active_high": True},
        "laser_watch": {},
        "controls": [],
    }
    if "headIo" in dev:
        ep = next((k for k in EXPANDER_PARTS if dev["headIo"]["mpn"].startswith(k)), None)
        if not ep:
            fail(f"expander {dev['headIo']['mpn']} has no firmware driver")
        out["expander"] = {"part": ep, "i2c_addr": int(dev["headIo"]["address"], 16)}
    rb = b["readbacks"]["laserCurrent"]
    if "headDac" in dev:
        hd = dev["headDac"]
        hp = next((k for k in DAC_PARTS if hd["mpn"].startswith(k)), None)
        if hp != "DAC121C085":
            fail(f"head DAC {hd['mpn']} has no firmware driver")
        if int(hd.get("powerOnCode", 1)) != 0:
            fail("the head DAC must power up at code 0")
        ref = 2.5 if "2V5" in hd["reference"] or "2.5" in hd["reference"] else fail("unknown head DAC reference")
        out["dacs"].append({"dev": 1, "part": hp, "i2c_addr": int(hd["address"], 16), "bits": int(hd["resolutionBits"]), "vref_V": ref})
    wd = b.get("cable", {}).get("watchdogs", {})
    eq = str(ctr["laserEnable"].get("equation", ""))
    out["laser_enable"]["carrier_hz"] = int(wd.get("enableCarrier_Hz", 10000 if "carrier" in eq else 0))
    out["laser_watch"] = {"readback_poll_ms": int(wd.get("firmwareReadbackInterval_ms", 0)), "gate_writes": "before writes" in str(ctr["laserEnable"].get("safety", "")) or "before writing" in " ".join(b.get("startup", []))}
    if rb.get("device") == "ADS1115":
        fs = rb["programmedFullScale_V"]
        ma_per_code = _eval_eq(rb["equation"].replace("signed_code - zero_code", "1"), )
        if abs(ma_per_code - 1000 * fs / (32768 * rb["shuntOhms"])) > 1e-9:
            fail("laserCurrent readback equation disagrees with its full scale and shunt")
        rate = int(dev["headAdc"].get("rateSamplesPerSecond", 128))
        chs = rb["channel"].replace("\u2013", "-").replace("–", "-")
        if "differential" in chs:
            pair = chs.split(",")[0].strip()
            mux = {"AIN0-AIN1": 0, "AIN0-AIN3": 1, "AIN1-AIN3": 2, "AIN2-AIN3": 3}.get(pair)
            if mux is None:
                fail(f"ADS1115 differential pair {pair} is not one the chip offers")
        else:
            mux = 4 + int(chs.split()[0][-1])
        out["isense"] = {"device": "ADS1115", "i2c_addr": int(rb["i2cAddress"], 16), "mux": mux, "input": chs.split(",")[0].strip(),
                         "full_scale_V": fs, "data_rate_sps": rate, "mA_per_code": ma_per_code, "offset_mA": 0.0,
                         "zero_calibrated": "zero_code" in rb["equation"], "trip_mA": sc["laser_trip_mA"],
                         "rate_hz": min(sc["isense_rate_hz"], rate // 2), "location": rb.get("location", "")}
    else:
        fail("laser current readback: only the ADS1115 on the head is supported")
    rail = b["readbacks"].get("mainAnalogRail")
    if rail:
        k = _eval_eq(rail["equation"].replace("code * VADC_REF / 4096", "1"))
        out["rail"] = {"adc": rail["adc"], "gpio": rail["gpio"], "scale": k, "adc_vref_V": sc["vadc_ref_V"], "nominal_V": 5.3, "source": rail.get("source", "")}
    chan = {"A": 0, "B": 1, "C": 2, "D": 3}
    lc = ctr["laserCurrent"]
    on_head = lc.get("device") == "headDac"
    ldev, lch = (1, 0) if on_head else (0, chan[lc["dacChannel"]])
    per = _eval_eq(lc["equation"], VDAC_SUPPLY=vd, REF2V5=2.5, code=1, dac_code=1)
    top = per * lc["codeRange"][1]
    if abs(top - lc["nominalRange"][1]) > 0.005 * lc["nominalRange"][1]:
        fail(f"laserCurrent equation gives {top:.2f} mA at full scale, the map says {lc['nominalRange'][1]}")
    # Command mapping (1.2.1): DAC code = max(command - guard, 0).
    cm = lc.get("commandMapping", {})
    guard = 0
    if cm:
        import re
        mm = re.fullmatch(r"\s*max\(\s*command_code\s*-\s*(\d+)\s*,\s*0\s*\)\s*", cm["dacCodeEquation"])
        if not mm:
            fail(f"cannot read the command mapping {cm['dacCodeEquation']!r}")
        guard = int(mm.group(1))
        phys = per * (lc["codeRange"][1] - guard)
        if "nominalPhysicalFullScale_mA" in cm and abs(phys - cm["nominalPhysicalFullScale_mA"]) > 0.005 * phys:
            fail(f"guard band gives {phys:.3f} mA physical full scale, the map says {cm['nominalPhysicalFullScale_mA']}")
        if sorted(cm.get("disarmedCommandCodes", [0, guard])) != [0, guard]:
            fail("disarmed command codes should be 0 and the guard")
        top = phys
    out["controls"].append({"id": "laserCurrent", "label": "Laser current", "kind": "dac", "dac": ldev, "ch": lch, "unit": "mA",
                            "per_code": per, "at_zero": 0.0, "min": 0.0, "max": min(top, lc["limits"]["rating_mA"]), "rated": lc["limits"]["rating_mA"],
                            "default": float(lc["powerOnDefault"]), "ramp_per_s": sc["laser_ramp_mA_per_s"], "role": "laser",
                            "hw_cutoff_mA": lc["limits"].get("nominalIndependentCutoff_mA"),
                            "min_write_ms": sc["laser_min_write_ms"] if out["laser_watch"]["gate_writes"] else 0,
                            "guard": guard, "max_code": lc["codeRange"][1] - guard,
                            "disarm_us": sc["laser_disarm_us"] if out["laser_watch"]["gate_writes"] else 0})
    if out["laser_watch"]["gate_writes"]:
        out["controls"][-1]["ramp_per_s"] = 0.0   # the head's soft-start ramps; see laser_min_write_ms
    gainlink = {"monitorOffset": "monitorSecondStageGain", "externalOffset": "externalSecondStageGain"}
    for cid, label, chn in (("monitorOffset", "Offset, channel 1", 1), ("externalOffset", "Offset, channel 2", 2)):
        c = ctr[cid]
        per = vd / 4096
        out["controls"].append({"id": cid, "label": label, "kind": "dac", "dac": 0, "ch": chan[c["dacChannel"]], "unit": "V",
                                "per_code": per, "at_zero": 0.0, "min": 0.0, "max": round(per * c["codeRange"][1], 6),
                                "default": float(c["powerOnDefault"]), "role": "offset", "channel": chn,
                                "offset_gain": "1 + |K| of " + gainlink[cid], "gain_link": gainlink[cid]})
    def switch(cid, label, role, chn, stage, unit):
        c = ctr[cid]
        if "gpio" in c:
            gp = [c["gpio"]]
        elif "expanderBit" in c:
            gp = [EXP_BASE + c["expanderBit"]]
        else:
            gp = [EXP_BASE + x for x in c["expanderBits"]]
        sets = []
        for code, v in c["values"].items():
            if isinstance(v, dict):
                sets.append({"label": f"{v['label'].title()} {v['V']:g} V", "value": v["V"], "code": int(code)})
            else:
                lab = (f"{v/1000:g} k" if v >= 1000 else f"{v:g}") if unit == "ohm" else f"{v:g} V/V"
                sets.append({"label": lab, "value": v, "code": int(code)})
        d = c["powerOnDefault"]
        if isinstance(d, str):
            d = next(s["value"] for s in sets if s["label"].lower().startswith(d.lower()))
        rule = str(b.get("firmwareCommands", {}).get("selectorAndOffsetWrites", "")).lower()
        n = {"id": cid, "label": label, "kind": "switch", "gpios": gp, "unit": unit, "role": role, "settings": sets, "default": d,
             "requires_laser_off": "laser disabled" in str(c.get("safety", "")).lower() or "disable the laser first" in rule,
             "safety": c.get("safety", "") or b.get("firmwareCommands", {}).get("selectorAndOffsetWrites", "")}
        if chn:
            n["channel"] = chn
        if stage:
            n["stage"] = stage
        out["controls"].append(n)
    rule = str(b.get("firmwareCommands", {}).get("selectorAndOffsetWrites", "")).lower()
    off_rule = "disable the laser first" in rule
    out["writes_need_laser_off"] = off_rule
    if off_rule:
        for c in out["controls"]:
            if c["role"] == "offset":
                c["requires_laser_off"] = True
                c["safety"] = b["firmwareCommands"]["selectorAndOffsetWrites"]
    switch("headTiaGain", "Monitor TIA", "gain", 1, "tia", "ohm")
    switch("monitorSecondStageGain", "Monitor second stage", "gain", 1, "amp", "V/V")
    switch("externalTiaGain", "External TIA", "gain", 2, "tia", "ohm")
    switch("externalSecondStageGain", "External second stage", "gain", 2, "amp", "V/V")
    switch("headMonitorBias", "Monitor bias", "bias", None, None, "V")
    return out


def normalise(m):
    """Validate the map and return the canonical form both sides consume."""
    for k in ("i2c", "dacs", "laser_enable", "isense", "controls"):
        if k not in m:
            fail(f"missing '{k}'")
    dacs = {d["dev"]: d for d in m["dacs"]}
    out = {
        "map_version": str(m.get("map_version", "unversioned")),
        "i2c": {k: int(m["i2c"][k]) for k in ("bus", "sda", "scl", "hz")},
        "dacs": [{"dev": int(d["dev"]), "part": d["part"], "i2c_addr": int(d["i2c_addr"]), "bits": int(d["bits"]), "vref_V": float(d["vref_V"])} for d in m["dacs"]],
        "laser_enable": {"gpio": int(m["laser_enable"]["gpio"]), "active_high": bool(m["laser_enable"]["active_high"]), "carrier_hz": int(m["laser_enable"].get("carrier_hz", 0))},
        "laser_watch": {"readback_poll_ms": int(m.get("laser_watch", {}).get("readback_poll_ms", 0)), "gate_writes": bool(m.get("laser_watch", {}).get("gate_writes", False))},
        "isense": {k: float(m["isense"][k]) for k in ("full_scale_V", "mA_per_code", "offset_mA", "trip_mA")},
        "controls": [],
    }
    i = m["isense"]
    if i.get("device") != "ADS1115":
        fail("laser current readback must be an ADS1115")
    out["isense"].update(device="ADS1115", i2c_addr=int(i["i2c_addr"]), mux=int(i["mux"]), input=i.get("input", ""), data_rate_sps=int(i["data_rate_sps"]),
                         rate_hz=int(i.get("rate_hz", 10)), zero_calibrated=bool(i.get("zero_calibrated", False)))
    if out["isense"]["full_scale_V"] not in ADS_PGA:
        fail(f"ADS1115 full scale {out['isense']['full_scale_V']} V is not a PGA setting")
    if out["isense"]["data_rate_sps"] not in ADS_DR:
        fail(f"ADS1115 data rate {out['isense']['data_rate_sps']} is not a valid rate")
    if not 0 <= out["isense"]["mux"] <= 7:
        fail("ADS1115 input mux must be 0..7")
    if "rail" in m:
        out["rail"] = m["rail"]
        if out["rail"]["adc"] != 2 or out["rail"]["gpio"] != 28:
            fail("the rail monitor must be ADC2 on GPIO28")
    for d in out["dacs"]:
        if d["part"] not in DAC_PARTS:
            fail(f"DAC part {d['part']} has no driver in the firmware (MCP4728 is refused: it restores EEPROM values at power-up)")
    if "expander" in m:
        out["expander"] = {"part": m["expander"]["part"], "i2c_addr": int(m["expander"]["i2c_addr"])}
    if any(d["i2c_addr"] == 0x48 and d["part"] == "DAC121C085" for d in out["dacs"]) or (out["isense"]["i2c_addr"] == 0x48 and any(d["part"] == "DAC121C085" for d in out["dacs"])):
        fail("0x48 is the DAC121C085 broadcast address; nothing may use it on a bus with that DAC")
    addrs = [d["i2c_addr"] for d in out["dacs"]] + [out["isense"]["i2c_addr"]] + ([out["expander"]["i2c_addr"]] if "expander" in out else [])
    if len(set(addrs)) != len(addrs):
        fail(f"two I2C devices share an address: {[hex(a) for a in addrs]}")
    used_gpio = {15: "SYNC", 26: "ADC0", 27: "ADC1", 28: "ADC2", out["i2c"]["sda"]: "I2C SDA", out["i2c"]["scl"]: "I2C SCL"}
    def claim(g, who):
        if g in used_gpio:
            fail(f"GPIO{g} used by both {used_gpio[g]} and {who}")
        if g >= EXP_BASE:
            if "expander" not in m or g - EXP_BASE > 7:
                fail(f"{who}: expander bit {g - EXP_BASE} but no MCP23008 in the map")
        elif not 0 <= g <= 22:
            fail(f"GPIO{g} for {who} is not a free Pico GPIO")
        used_gpio[g] = who
    claim(out["laser_enable"]["gpio"], "laser enable")
    ids = set()
    lasers = 0
    if len(m["controls"]) > MAX_CONTROLS:
        fail(f"more than {MAX_CONTROLS} controls")
    for c in m["controls"]:
        cid = c["id"]
        if cid in ids:
            fail(f"duplicate id {cid}")
        ids.add(cid)
        kind = c["kind"]
        if kind not in KINDS:
            fail(f"{cid}: unknown kind {kind}")
        if c["unit"] not in UNITS:
            fail(f"{cid}: unknown unit {c['unit']}")
        n = {k: c[k] for k in ("id", "label", "kind", "unit")}
        n["role"] = c.get("role", "other")
        n["requires_laser_off"] = bool(c.get("requires_laser_off", False))
        for k in ("channel", "stage", "adc_V_per_unit", "gain_link", "offset_gain", "hw_cutoff_mA", "safety"):
            if k in c:
                n[k] = c[k]
        if kind == "dac":
            if c["dac"] not in dacs:
                fail(f"{cid}: no DAC dev {c['dac']}")
            bits = dacs[c["dac"]]["bits"]
            n.update(dac=int(c["dac"]), ch=int(c["ch"]), per_code=float(c["per_code"]), at_zero=float(c["at_zero"]),
                     min=float(c["min"]), max=float(c["max"]), default=float(c["default"]),
                     ramp_per_s=float(c.get("ramp_per_s", 0.0)), bits=bits)
            if n["per_code"] == 0:
                fail(f"{cid}: per_code is zero")
            if not n["min"] <= n["default"] <= n["max"]:
                fail(f"{cid}: default {n['default']} outside {n['min']}..{n['max']}")
            full = n["at_zero"] + n["per_code"] * ((1 << bits) - 1)
            lo, hi = sorted((n["at_zero"], full))
            if n["min"] < lo - 1e-9 or n["max"] > hi + abs(n["per_code"]):
                fail(f"{cid}: range {n['min']}..{n['max']} is outside what the DAC can produce ({lo:.4g}..{hi:.4g})")
        else:
            gp = [int(g) for g in c["gpios"]]
            for g in gp:
                claim(g, cid)
            sets = c["settings"]
            if not 1 <= len(sets) <= MAX_SETTINGS:
                fail(f"{cid}: 1..{MAX_SETTINGS} settings")
            for s in sets:
                if not 0 <= int(s["code"]) < (1 << len(gp)):
                    fail(f"{cid}: code {s['code']} does not fit {len(gp)} GPIO(s)")
            n.update(gpios=gp, settings=[{"label": s["label"], "value": float(s["value"]), "code": int(s["code"])} for s in sets])
            vals = [s["value"] for s in n["settings"]]
            if float(c["default"]) not in vals:
                fail(f"{cid}: default {c['default']} is not one of its settings {vals}")
            n["default"] = float(c["default"])
            n["min"], n["max"] = min(vals), max(vals)
        if n["role"] == "laser":
            lasers += 1
            if kind != "dac":
                fail("the laser current control must be a DAC channel")
            if n["unit"] != "mA":
                fail(f"{cid}: the laser current must be in mA")
            n["rated"] = float(c["rated"])
            if n["max"] > n["rated"]:
                fail(f"{cid}: max {n['max']} exceeds the rated {n['rated']}")
            if n["ramp_per_s"] <= 0 and not c.get("min_write_ms"):
                fail(f"{cid}: the laser set-point needs a ramp-rate limit or a write-rate limit")
            if n["default"] != 0.0:
                fail(f"{cid}: power-on default must be 0")
            cut = c.get("hw_cutoff_mA")
            if cut and not n["max"] < out["isense"]["trip_mA"] < cut:
                fail(f"firmware trip {out['isense']['trip_mA']} mA must sit between the DAC's top {n['max']:.2f} mA and the hardware cutoff {cut} mA")
            n["min_write_ms"] = int(c.get("min_write_ms", 0))
            n["guard"] = int(c.get("guard", 0))
            n["max_code"] = int(c.get("max_code", 0))
            n["disarm_us"] = int(c.get("disarm_us", 0))
            if out["isense"]["trip_mA"] > n["rated"]:
                fail("isense trip_mA exceeds the laser's rated current")
        out["controls"].append(n)
    if lasers != 1:
        fail("exactly one control must have role 'laser'")
    # Laser first, so its index is 0 on both sides.
    out["controls"].sort(key=lambda c: 0 if c["role"] == "laser" else 1)
    return out


def c_float(v):
    if math.isinf(v) or math.isnan(v):
        fail("non-finite number")
    return f"{v!r}f"


def c_header(n, h):
    L = []
    L.append("// SPDX-License-Identifier: MIT")
    L.append("// GENERATED by controls/gen_controls.py from the board's control map. Do not edit.")
    L.append(f"// map_version {n['map_version']}")
    L.append("#ifndef SMI_CONTROLS_GEN_H\n#define SMI_CONTROLS_GEN_H\n#include \"smi_ctl.h\"\n")
    L.append(f"#define SMI_MAP_HASH 0x{h:08X}u")
    L.append(f"#define SMI_MAP_VERSION \"{n['map_version']}\"")
    i2c = n["i2c"]
    L.append(f"#define SMI_I2C_BUS {i2c['bus']}\n#define SMI_I2C_SDA {i2c['sda']}\n#define SMI_I2C_SCL {i2c['scl']}\n#define SMI_I2C_HZ {i2c['hz']}u")
    L.append(f"#define SMI_LASER_EN_GPIO {n['laser_enable']['gpio']}\n#define SMI_LASER_EN_ACTIVE_HIGH {1 if n['laser_enable']['active_high'] else 0}")
    L.append(f"#define SMI_LASER_EN_CARRIER_HZ {n['laser_enable']['carrier_hz']}u   /* 0 = a static level */")
    L.append(f"#define SMI_LASER_READBACK_POLL_MS {n['laser_watch']['readback_poll_ms']}u   /* 0 = no readback polling */")
    L.append(f"#define SMI_NUM_DACS {len(n['dacs'])}")
    parts = DAC_PARTS
    ex = n.get("expander")
    L.append(f"#define SMI_EXP_PRESENT {1 if ex else 0}\n#define SMI_EXP_ADDR 0x{(ex or {}).get('i2c_addr', 0):02X}\n#define SMI_EXP_BASE {EXP_BASE}")
    L.append("static const smi_dac_def_t smi_dacs[SMI_NUM_DACS] = {")
    for d in n["dacs"]:
        L.append(f"    {{ .part = {parts[d['part']]}, .addr = 0x{d['i2c_addr']:02X}, .bits = {d['bits']}, .vref = {c_float(d['vref_V'])} }},")
    L.append("};")
    s = n["isense"]
    cfg = 0x8000 | (s["mux"] << 12) | (ADS_PGA[s["full_scale_V"]] << 9) | (ADS_DR[s["data_rate_sps"]] << 5) | 0x03
    L.append(f"// Laser current: ADS1115 at 0x{s['i2c_addr']:02X}, {s['input'] or 'mux ' + str(s['mux'])}, +/-{s['full_scale_V']} V, {s['data_rate_sps']} SPS, continuous")
    L.append(f"#define SMI_ADS_ADDR 0x{s['i2c_addr']:02X}\n#define SMI_ADS_CONFIG 0x{cfg:04X}u")
    L.append(f"static const smi_isense_def_t smi_isense = {{ .ma_per_code = {c_float(s['mA_per_code'])}, .offset_ma = {c_float(s['offset_mA'])}, .trip_ma = {c_float(s['trip_mA'])}, .rate_hz = {s['rate_hz']}, .zero_cal = {1 if s['zero_calibrated'] else 0} }};")
    r = n.get("rail")
    L.append(f"#define SMI_RAIL_PRESENT {1 if r else 0}")
    if r:
        L.append(f"#define SMI_RAIL_SCALE {c_float(r['scale'] * r['adc_vref_V'] / 4096)} /* volts per ADC2 code */")
    L.append(f"#define SMI_NUM_CONTROLS {len(n['controls'])}")
    L.append("static const smi_control_def_t smi_controls[SMI_NUM_CONTROLS] = {")
    for c in n["controls"]:
        f = [f".kind = {KINDS[c['kind']]}", f".unit = {UNITS.index(c['unit'])}", f".is_laser = {1 if c['role'] == 'laser' else 0}", f".needs_off = {1 if c['requires_laser_off'] else 0}"]
        f += [f".min = {c_float(c['min'])}", f".max = {c_float(c['max'])}", f".def = {c_float(c['default'])}"]
        if c["kind"] == "dac":
            f += [f".dac = {c['dac']}", f".ch = {c['ch']}", f".bits = {c['bits']}", f".per_code = {c_float(c['per_code'])}", f".at_zero = {c_float(c['at_zero'])}", f".ramp_per_s = {c_float(c['ramp_per_s'])}"]
            if c["role"] == "laser":
                f.append(f".rated = {c_float(c['rated'])}")
                if n["laser_watch"]["gate_writes"]:
                    f.append(f".gate = 1, .min_write_us = {c['min_write_ms'] * 1000}u, .disarm_us = {c['disarm_us']}u, .max_code = {c['max_code']}, .guard = {c['guard']}")
        else:
            g = ", ".join(str(x) for x in c["gpios"])
            sc = ", ".join(str(x["code"]) for x in c["settings"])
            sv = ", ".join(c_float(x["value"]) for x in c["settings"])
            f += [f".ngpio = {len(c['gpios'])}", f".gpio = {{{g}}}", f".nset = {len(c['settings'])}", f".set_code = {{{sc}}}", f".set_value = {{{sv}}}"]
        L.append(f"    /* {c['id']} */ {{ {', '.join(f)} }},")
    L.append("};\n#endif")
    return "\n".join(L) + "\n"


def check_stage(src):
    """The board map's stage entry must match the pins compiled into the stage core."""
    st = src.get("stage")
    if not st:
        return
    hdr = (ROOT / "firmware/src/smi_stage.h").read_text()
    want = {"STEP": "SMI_STAGE_STEP_GPIO", "DIR": "SMI_STAGE_DIR_GPIO", "EN_N": "SMI_STAGE_EN_N_GPIO",
            "UART": "SMI_STAGE_UART_GPIO", "HOME": "SMI_STAGE_HOME_GPIO"}
    for p in st["pins"]:
        if p["signal"] in want:
            m = re.search(r"#define " + want[p["signal"]] + r" (\d+)", hdr)
            if not m or int(m.group(1)) != p["gpio"]:
                sys.exit(f"ERROR: stage {p['signal']} is GP{p['gpio']} in the map but {m.group(1) if m else 'missing'} in smi_stage.h")
    en = next(p for p in st["pins"] if p["signal"] == "EN_N")
    if not en.get("activeLow"):
        sys.exit("ERROR: the stage core assumes EN_N active low")
    print(f"OK: stage pins match the map (J4: STEP GP{want and next(p['gpio'] for p in st['pins'] if p['signal']=='STEP')} .. HOME GP{next(p['gpio'] for p in st['pins'] if p['signal']=='HOME')})")


def main():
    if len(sys.argv) != 2:
        sys.exit("usage: gen_controls.py <control-map.json>")
    src = json.loads(Path(sys.argv[1]).read_text())
    check_stage(src)
    if str(src.get("schema", "")).startswith("interferometer/control-map/"):
        src = from_board_schema(src)
    n = normalise(src)
    text = json.dumps(n, separators=(",", ":"), sort_keys=True)
    h = fnv1a(text.encode())
    (ROOT / "dashboard/assets/controls.json").write_text(text)
    (ROOT / "firmware/src/smi_controls_gen.h").write_text(c_header(n, h))
    print(f"OK: {len(n['controls'])} controls, map {n['map_version']}, hash 0x{h:08X}")


if __name__ == "__main__":
    main()