main
John Lauer software/ 1.2.1 for board 1.2.1: Pico firmware runs the board's controller contract (head DAC121C085 written and read b… 2e755c9
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Print the README's control table from dashboard/assets/controls.json (the
normalised map gen_controls.py writes), so the documentation cannot drift
from what the firmware enforces."""
import json
from pathlib import Path

m = json.loads((Path(__file__).resolve().parent.parent / "dashboard/assets/controls.json").read_text())
CLI = {"laser": "`laser current <mA>`", "offset1": "`offset ch1 <V>`, `offset auto`", "offset2": "`offset ch2 <V>`, `offset auto`",
       "gain1tia": "`gain ch1-tia <ohm>`", "gain1amp": "`gain ch1-amp -5\\|-20`", "gain2tia": "`gain ch2-tia <ohm>`",
       "gain2amp": "`gain ch2-amp -5\\|-20`", "bias": "`bias low\\|mid\\|high`"}


def where(c):
    if c["kind"] == "dac":
        d = next(x for x in m["dacs"] if x["dev"] == c["dac"])
        if d["part"] == "DAC121C085":
            return f"DAC121C085 on the laser head, 0x{d['i2c_addr']:02X}, {d['vref_V']:g} V reference"
        return f"{d['part']} channel {'ABCD'[c['ch']]}"
    return ", ".join(f"MCP23008 bit {x - 32}" if x >= 32 else f"GPIO{x}" for x in c["gpios"])


def key(c):
    if c["role"] in ("laser", "bias"):
        return c["role"]
    return f"{c['role']}{c.get('channel', '')}{c.get('stage', '') if c['role'] == 'gain' else ''}"


rows = ["| Control (map id) | Where | Range | Scaling | Power-on | Firmware limits | CLI |", "|---|---|---|---|---|---|---|"]
for c in m["controls"]:
    if c["kind"] == "dac":
        rng = f"{c['min']:g} to {c['max']:.4g} {c['unit']}"
        sc = f"{c['per_code']:.6g} {c['unit']} per count"
        lim = []
        if c["role"] == "laser":
            top = f"the DAC's top less a {c['guard']}-count guard band" if c.get("guard") else "the DAC's top"
            lim = [f"refuses above {min(c['max'], c['rated']):.2f} mA ({top}; diode rated {c['rated']:g} mA, hardware cutoff {c.get('hw_cutoff_mA') or 0:g} mA)"]
            if c.get("ramp_per_s"):
                lim.append(f"ramps at {c['ramp_per_s']:g} mA/s")
            if c.get("min_write_ms"):
                lim.append(f"each write drops the enable for {c.get('disarm_us', 0) / 1000:g} ms, is read back, and re-arms only on an exact nonzero match (the head's soft-start then ramps the current); at most one write per {c['min_write_ms']} ms")
            if c.get("guard"):
                lim.append(f"counts mode takes the contract's command code: DAC code = max(command - {c['guard']}, 0)")
            lim.append("set-point 0 at boot and on link loss")
        if c["role"] == "offset":
            lim = ["moves the ADC by 1 + \\|K\\| per volt, K = its stage 2 gain"] + (["refused while the laser is on (board rule)"] if c.get("requires_laser_off") else [])
        pon = f"{c['default']:g} {c['unit']}"
    else:
        labels = []
        for s in c["settings"]:
            if s["label"] not in labels:
                labels.append(s["label"])
        rng, sc = " / ".join(labels), "switch"
        pon = next(s["label"] for s in c["settings"] if s["value"] == c["default"])
        lim = ["refused while the laser is on (board rule)"] if c["requires_laser_off"] else []
    rows.append(f"| {c['label']} (`{c['id']}`) | {where(c)} | {rng} | {sc} | {pon} | {'; '.join(lim) or 'none beyond the range'} | {CLI.get(key(c), '')} |")
i = m["isense"]
le, lw = m["laser_enable"], m.get("laser_watch", {})
carrier = f"a {le['carrier_hz'] / 1000:g} kHz carrier" if le.get("carrier_hz") else "active high"
poll = f"; while on, the head DAC is read back every {lw['readback_poll_ms']} ms (a mismatch turns it off; the traffic keeps the head's I2C watchdog fed)" if lw.get("readback_poll_ms") else ""
rows.append(f"| Laser enable | GPIO{le['gpio']}, {carrier} | on / off | | off | needs the interlock key and a checked current zero; off on USB loss or port close, watchdog reset, 3 s without a host command, overcurrent, or a DAC, expander or current-ADC failure{poll} | `laser on --beam-safe`, `laser off` |")
fsma = i["mA_per_code"] * 32767
rows.append(f"| Laser current, measured | ADS1115 at 0x{i['i2c_addr']:02X} on the laser head, {i.get('input') or 'mux ' + str(i['mux'])}, +/-{i['full_scale_V']:g} V, {i['data_rate_sps']} SPS | 0 to {fsma:.0f} mA | {i['mA_per_code']:g} mA per count across the 2 ohm shunt, zero calibrated with the laser off | | read {i['rate_hz']} times a second; three readings above {i['trip_mA']:g} mA turn the laser off | `laser read` |")
if m.get("rail"):
    r = m["rail"]
    rows.append(f"| Main analog rail | ADC2 (GPIO28), 1:{r['scale']:g} divider | 0 to {3.3 * r['scale']:.1f} V | {r['scale'] * 3.3 / 4096 * 1000:.3f} mV per count | | read once a second, shown in the status bar | `status` |")
print(f"Control map `{m['map_version']}`.\n")
print("\n".join(rows))