← Commit history

software/ 1.2.1 for board 1.2.1: Pico firmware runs the board's controller contract (head DAC121C085 written and read back before arming, 45-count guard band, 10 kHz enable carrier, 2 ms readback that feeds the head watchdog, no bus writes while armed, the contract's text commands), smi-dash Controls tab and CLI for every board setting with auto-centre and tune for fringes, simulated board running the firmware's own control code, tests, builds and screenshots; Overview: Software card text

John Lauer ·2e755c9783 · ·parent 869156e
40 files changed +5284−91
README.md+1−1
@@ -106,6 +106,6 @@ Head rear with the laser and optical mounting holes, fitted jumpers, Adom wordma <table> <tr> <td width="104"><a href="software/README.md"><img src="software/software-icon.png" width="112" alt="The interferometer dashboard"></a><br><sub>&nbsp;&nbsp;Dashboard&nbsp;&nbsp;</sub></td>-<td>The Pico firmware samples both photodiode channels at 250 thousand samples a second each and streams them over USB. The dashboard shows the fringes live, reads each fringe's direction and keeps a running position in nanometres, with a physics simulator so you can try it before any board is built. Download the firmware and the app, flash the Pico and run it.<br><br><a href="software/README.md">Firmware and dashboard</a></td>+<td>The Pico firmware samples both photodiode channels at 250 thousand samples a second each and streams them over USB. On board 1.2.1 it also runs the board: it writes the laser set-point to the head and reads it back before arming, sets both offsets, the gains and the monitor bias, and holds to the control map's limits, so nothing needs a screwdriver. The dashboard shows the fringes live, reads each fringe's direction and keeps a running position in nanometres. Its Controls tab and CLI set every board setting, centre both channels and tune for fringes, and a physics simulator lets you try it all before a board is built. Download the firmware and the app, flash the Pico and run it.<br><br><a href="software/README.md">Firmware and dashboard</a></td> </tr> </table>
readme.html+1−1
@@ -151,7 +151,7 @@ aiflow-explorer { display: block; margin: 6px 0 24px; } <table> <tr> <td width="104"><a href="https://wiki.adom.inc/john/self-mixing-interferometer/files/software/README.md" target="_blank" rel="noopener"><img src="https://wiki.adom.inc/john/self-mixing-interferometer/render/software/software-icon.png" width="112" alt="The interferometer dashboard"></a><br><sub>&nbsp;&nbsp;Dashboard&nbsp;&nbsp;</sub></td>-<td>The Pico firmware samples both photodiode channels at 250 thousand samples a second each and streams them over USB. The dashboard shows the fringes live, reads each fringe's direction and keeps a running position in nanometres, with a physics simulator so you can try it before any board is built. Download the firmware and the app, flash the Pico and run it.<br><br><a href="https://wiki.adom.inc/john/self-mixing-interferometer/files/software/README.md" target="_blank" rel="noopener">Firmware and dashboard</a></td>+<td>The Pico firmware samples both photodiode channels at 250 thousand samples a second each and streams them over USB. On board 1.2.1 it also runs the board: it writes the laser set-point to the head and reads it back before arming, sets both offsets, the gains and the monitor bias, and holds to the control map's limits, so nothing needs a screwdriver. The dashboard shows the fringes live, reads each fringe's direction and keeps a running position in nanometres. Its Controls tab and CLI set every board setting, centre both channels and tune for fringes, and a physics simulator lets you try it all before a board is built. Download the firmware and the app, flash the Pico and run it.<br><br><a href="https://wiki.adom.inc/john/self-mixing-interferometer/files/software/README.md" target="_blank" rel="noopener">Firmware and dashboard</a></td> </tr> </table> </section>
software/README.md+110−4
@@ -1,12 +1,13 @@ # Software: Pico firmware and the SMI dashboard -Firmware for the Raspberry Pi Pico that plugs into this board, and a dashboard that shows both photodiode channels live, finds every fringe, reads its lean for direction and keeps a running position in nanometres. With no hardware attached the dashboard runs a physical simulator of the laser, the optics and this board's analog chain, so everything here can be tried today.+Firmware for the Raspberry Pi Pico that plugs into this board, and a dashboard that shows both photodiode channels live, finds every fringe, reads its lean for direction and keeps a running position in nanometres. On board v1.2 every setting that used to need a screwdriver (laser current, both offsets, the amplifier gains, the monitor bias) is set from the dashboard or the CLI, through the Pico, with the firmware enforcing the laser's limits. With no hardware attached the dashboard runs a physical simulator of the laser, the optics and the board, so everything here can be tried today. -![The dashboard with the simulated target moving away at 1 mm/s](software/screenshots/dashboard-constant-speed.png)+![Board v1.2 tuned from software: laser at 96.1 mA on the head DAC, second stage at -20 V/V, both channels centred, fringes counted](software/screenshots/controls-tuned.png)  | Folder | What it is | |---|---|-| [firmware/](software/firmware/README.md) | C, Pico SDK 2.1.1. Round-robin ADC0/ADC1 at 500 ksps total over DMA, SYNC edges on GPIO15, a framed and delta-packed USB CDC stream with CRC. |+| [firmware/](software/firmware/README.md) | C, Pico SDK 2.1.1. Round-robin ADC0/ADC1 at 500 ksps total over DMA, SYNC edges on GPIO15, a framed and delta-packed USB CDC stream with CRC, and the v1.2 command channel on the same link. |+| [controls/](software/controls/gen_controls.py) | The board's control map, the generator that makes the firmware's control table and the dashboard's copy from it, and the README's control table. | | [dashboard/](software/dashboard/README.md) | `smi-dash`, a Rust app with a web UI for a Hydrogen webview, a CLI with the same verbs, the simulator and the fringe detector. | | [dist/](software/dist/SHA256SUMS) | Built files: `smi_pico.uf2`, `smi-dash-linux-x64`, `smi-dash-windows-x64.exe`, with `SHA256SUMS`. | @@ -16,9 +17,103 @@ Firmware for the Raspberry Pi Pico that plugs into this board, and a dashboard t 2. Fit the Pico into the board's socket (USB connector toward the long upper edge) and power the board. 3. Run the dashboard: `smi-dash start`, then `smi-dash show` to open it in a Hydrogen webview tab (or open the printed `http://127.0.0.1:<port>/` in any browser). 4. Click **Pico (USB)** under Source, or run `smi-dash source serial`. Without a Pico, leave it on **Simulator**.+5. Board v1.2: open the **Controls** tab. Tick the interlock box (beam enclosed or eyewear on) and hold **Enable** for a second, or run `smi-dash laser on --beam-safe`. Set a current, then **Tune**, or run `smi-dash tune`.  On Windows use `smi-dash-windows-x64.exe` (CSV recording only): the Pico appears as a COM port. The Linux build needs `libhdf5` and `libudev` at run time (Ubuntu 24.04: `sudo apt install libhdf5-103-1t64 libudev1`). Inside WSL a USB device is only visible after `usbipd attach --wsl --busid <BUSID>`; `smi-dash ports` lists what it can see and marks the Pico. +## Board v1.2: every setting from software++Board v1.2 replaces the trimmers and jumpers with a DAC121C085 on the laser head for the laser set-point, a DAC7574 on the main board for both offsets, analog switches on Pico GPIOs and on the head's MCP23008 for the gains and monitor bias, a laser enable sent as a 10 kHz carrier, and an ADS1115 on the head that measures the laser current. The set-point never crosses the cable as a voltage: the Pico writes it over the cable's I2C and reads it back. The Pico drives all of it, follows the board's controller contract (`design/control-map.json`, revision 1.2.1, and the board's `design/decision8-firmware.patch`), and takes commands on the same USB link that carries the samples.++### The controls++Control map `1.2.0-revision-1.2-controller-contract`.++| Control (map id) | Where | Range | Scaling | Power-on | Firmware limits | CLI |+|---|---|---|---|---|---|---|+| Laser current (`laserCurrent`) | DAC121C085 on the laser head, 0x09, 2.5 V reference | 0 to 109.2 mA | 0.0269538 mA per count | 0 mA | refuses above 109.16 mA (the DAC's top less a 45-count guard band; diode rated 135 mA, hardware cutoff 123.89 mA); each write drops the enable for 2 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 250 ms; counts mode takes the contract's command code: DAC code = max(command - 45, 0); set-point 0 at boot and on link loss | `laser current <mA>` |+| Offset, channel 1 (`monitorOffset`) | DAC7574 channel B | 0 to 3.299 V | 0.000805664 V per count | 0 V | moves the ADC by 1 + \|K\| per volt, K = its stage 2 gain; refused while the laser is on (board rule) | `offset ch1 <V>`, `offset auto` |+| Offset, channel 2 (`externalOffset`) | DAC7574 channel C | 0 to 3.299 V | 0.000805664 V per count | 0 V | moves the ADC by 1 + \|K\| per volt, K = its stage 2 gain; refused while the laser is on (board rule) | `offset ch2 <V>`, `offset auto` |+| Monitor TIA (`headTiaGain`) | MCP23008 bit 0 | 1 k / 4.7 k | switch | 1 k | refused while the laser is on (board rule) | `gain ch1-tia <ohm>` |+| Monitor second stage (`monitorSecondStageGain`) | GPIO7 | -5 V/V / -20 V/V | switch | -5 V/V | refused while the laser is on (board rule) | `gain ch1-amp -5\|-20` |+| External TIA (`externalTiaGain`) | GPIO9 | 46.836 k / 150 k | switch | 46.836 k | refused while the laser is on (board rule) | `gain ch2-tia <ohm>` |+| External second stage (`externalSecondStageGain`) | GPIO8 | -5 V/V / -20 V/V | switch | -5 V/V | refused while the laser is on (board rule) | `gain ch2-amp -5\|-20` |+| Monitor bias (`headMonitorBias`) | MCP23008 bit 1, MCP23008 bit 2 | Low 0.252 V / Mid 2.488 V / High 4.649 V | switch | Low 0.252 V | refused while the laser is on (board rule) | `bias low\|mid\|high` |+| Laser enable | GPIO6, a 10 kHz 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; while on, the head DAC is read back every 2 ms (a mismatch turns it off; the traffic keeps the head's I2C watchdog fed) | `laser on --beam-safe`, `laser off` |+| Laser current, measured | ADS1115 at 0x49 on the laser head, AIN0-AIN1, +/-0.512 V, 128 SPS | 0 to 256 mA | 0.0078125 mA per count across the 2 ohm shunt, zero calibrated with the laser off | | read 50 times a second; three readings above 116 mA turn the laser off | `laser read` |+| Main analog rail | ADC2 (GPIO28), 1:2 divider | 0 to 6.6 V | 1.611 mV per count | | read once a second, shown in the status bar | `status` |++The table is printed by `controls/control_table.py` from the same normalised map the firmware is built from. The values the board map leaves to software are set in `controls/gen_controls.py`: at most four laser set-point writes a second, a 116 mA firmware trip (above the 109.2 mA top and below the 123.9 mA hardware cutoff; the generator refuses a map where that order does not hold), 50 current readings a second, a 3 s host heartbeat and a 300 ms watchdog. The head's own shunt cutoff, its resistor-set ceiling and its I2C watchdog are hardware and do not rely on any of this.++### Safety, in the firmware as well as the hardware++- **Off by default.** The enable pin is driven low before anything else at power-up, and the head DAC is written to zero and read back before any other control. The laser stays off after a watchdog reset, when the host closes the port or USB goes away, and when no command has arrived for 3 s. The dashboard sends a heartbeat every second while the laser is on, so if the dashboard dies or is killed, the laser goes off.+- **Write, read back, then arm.** Every set-point write drops the enable, waits 2 ms for the head's disable path and soft-start reset, writes the head DAC, reads the register back, and restarts the 10 kHz carrier only on an exact match with a nonzero code; then it reads the register once more, because the head's watchdog wants fresh I2C traffic right after enable. The head's soft-start ramps the current up from zero on every arm. That is the board's ramp; the firmware does not step the set-point (each step would restart the soft-start) and writes at most four set-points a second.+- **Guard band.** Command codes reach the head DAC as `max(command - 45, 0)`, so codes 0 to 45 keep the head disarmed and positive DAC offset error cannot make current. The top set-point is 109.16 mA.+- **Readback while armed.** Every 2 ms the firmware reads the head DAC back; a wrong code, a power-down mode or a failed read latches a fault and turns the laser off. The same traffic keeps the head's I2C watchdog fed, and it runs between USB frames and while waiting on USB, not only in the main loop.+- **No writes while armed.** The contract allows only reads on the bus while the laser is armed, apart from set-point writes, which disarm first. Offsets and every gain and bias selector are refused while the laser is on, and the head ADC's configuration and pointer are written only while disarmed. `smi-dash offset auto` and `smi-dash tune` therefore turn the laser off for each offset or gain write and back on at the same set-point; they never turn on a laser that was off.+- **An interlock to turn it on.** The binary enable command carries a fixed key that the dashboard sends only after an explicit confirmation: the page's interlock box plus a one-second hold on Enable, or `--beam-safe` on the CLI.+- **Checked readback.** The current-readback zero is calibrated with the laser off, and the laser cannot be enabled until it is. Three readings above the trip latch an overcurrent fault. Current with the laser disabled latches a fault, and three missed ADS1115 reads with the laser on turn it off. A DAC or expander that stops acknowledging is a fault too. Faults stay latched until `smi-dash board clear-fault`.++### The board's text commands++The firmware also takes the contract's text commands, one per line on the same port: `laser CODE` (0 to 4095, with the guard band), `laser off`, `laser current` (answered in an INFO frame with the signed ADS1115 code, the command code and the DAC code), `head MASK` (MCP23008 GP0 to GP2), `gain MASK` (Pico GP7 to GP9), `offset B CODE`, `offset C CODE`, plus `hb MS` to set the heartbeat timeout. They run through the same control code as the binary commands, so every limit, refusal and fault applies; selector and offset commands disarm the laser first and it stays off until a new laser command, as the contract says. A text-only host must send a command at least every 3 s while the laser is on (or raise it with `hb 30000`). These lines bypass the dashboard's interlock confirmation, so a host that uses them must ask for it itself.++### Controls tab++![Power-up: laser off, every output at its power-on default, the interlock not yet ticked](software/screenshots/controls-laser-off.png)++The Controls tab is built from the control map, so it follows the board without code changes. **Laser**: the interlock box, hold-to-enable and an always-ready Laser off; the current slider (sent when released, since each write restarts the soft-start) and numeric entry; the target, the set-point the head DAC holds, and the current the head measures, with 20 s of history. **Offsets**: one slider per channel with its mean in ADC codes, locked while the laser is on, and **Auto-centre**, which servoes each channel's mean to mid-scale (code 2048) using the board's stage equation `Vstage = (1 + K) Voffset - K Vbuffer` for the first step and the measured slope after that, cycling the laser for each write. **Gains and bias**: every switch, locked while the laser is on. **Tune**, below.++### Tune for fringes++![Tuning in progress: the current steps, each step re-centred and scored](software/screenshots/controls-tuning.png)++`smi-dash tune` (or **Tune**) steps the laser current across its range, waits for the head's soft-start, re-centres channel 1, and scores the fringes for 0.4 s: the 1st-to-99th percentile swing of the lightly filtered signal over its robust noise, with clipping penalised. It then refines around the best current, tries each second-stage gain, centres both channels, and returns every step's score. It takes about 10 s. **Move the target while it runs.** On this board the laser current cannot be dithered to make fringes with a still target (every write restarts the soft-start), so with a still target Tune reports that it saw no fringes and puts the current back where it was.++Accuracy through the simulated board, `smi-dash eval --board` (target at 400 um/s, 2 s per case, both channels centred the way `offset auto` does it, with the laser cycled for each offset write):++| Laser current | Stage 2 gain | Fringe swing | Noise | Score | True fringes | Detected | Final error | RMS error |+|---|---|---|---|---|---|---|---|---|+| 65 mA | -5 V/V | 16 codes | 1.39 codes | 12 | 2430 | 0 | -2 nm | 115789 nm |+| 65 mA | -20 V/V | 63 codes | 1.39 codes | 46 | 2430 | 2432 | -2 nm | 283 nm |+| 80 mA | -5 V/V | 28 codes | 1.39 codes | 20 | 2430 | 1237 | -393157 nm | 253494 nm |+| 80 mA | -20 V/V | 111 codes | 1.48 codes | 75 | 2430 | 2432 | -2 nm | 244 nm |+| 95 mA | -5 V/V | 34 codes | 1.39 codes | 24 | 2430 | 2431 | -331 nm | 377 nm |+| 95 mA | -20 V/V | 135 codes | 1.48 codes | 91 | 2430 | 2431 | -331 nm | 377 nm |+| 104 mA | -5 V/V | 32 codes | 1.48 codes | 22 | 2430 | 2365 | -431321 nm | 316633 nm |+| 104 mA | -20 V/V | 128 codes | 1.67 codes | 76 | 2430 | 3628 | -81594 nm | 91339 nm |+| 109 mA | -5 V/V | 38 codes | 1.39 codes | 28 | 2430 | 2429 | -331 nm | 398 nm |+| 109 mA | -20 V/V | 153 codes | 1.48 codes | 103 | 2430 | 2429 | -331 nm | 398 nm |++At the power-on gain (-5 V/V) the fringe swing at low current falls under the detector's 24-code minimum and fringes go uncounted; the page then says "signal small" above channel 1. At -20 V/V counting is within a fringe except at 104 mA, where the measured current (about 105.6 mA) sits in the simulated laser's mode-hop window around 106 mA and the two competing modes make the detector over-count. Tune scores that current lower and avoids it.++### CLI for the board++Every control is a verb, and every verb takes `--json`, so an AI in an Adom workcell can tune the board:++```+smi-dash laser on --beam-safe | laser off | laser current 95 --wait | laser read+smi-dash offset ch1 0.52 | offset ch2 650 --counts | offset auto [ch1|ch2|both]     # offsets: laser off, except auto+smi-dash gain ch1-amp -20 | gain ch1-tia 4700 | gain ch2-tia 150k | bias mid        # laser off+smi-dash ctl <map id> <value> [--counts | --index]+smi-dash board | board map | board clear-fault | board config --isense-hz 50 --hb-timeout-ms 3000+smi-dash tune [--channel 1] [--min-ma 50] [--max-ma 109] [--steps 8] [--no-gains] | tune --status | tune --stop+smi-dash eval --board+```++Refusals name the reason and the fix, for example `ERROR: Laser current (mA) out of range` with `Hint: laserCurrent accepts 0.0000 to 109.1627 mA`, or `ERROR: the board map says change this only with the laser off` with the board's own rule quoted.++### Command channel++Commands use the stream's own frame (sync word, type, length, sequence, CRC-16): the host sends type 0x10 frames, the Pico answers each with a 0x11 ACK carrying the command's sequence number and a status, and pushes a 0x12 STATE frame four times a second. The ops are get_state, laser_enable (with the key), set (control, unit mode: physical units, DAC counts or setting index, value), read_laser_current, heartbeat, clear_fault, get_map and config. Every op is idempotent, so the dashboard retries a lost ACK. The STATE frame carries the control map's hash; the dashboard warns if the Pico was built from a different map. Layouts are in `firmware/src/smi_ctl.h`.++The control logic (limits, the gated write sequence, guard band, interlock, heartbeat, trips) is one portable C file, `firmware/src/smi_ctl.c`, and the text commands are another, `firmware/src/smi_text.c`. The firmware runs them, the host tests run them, and the dashboard's simulator compiles `smi_ctl.c` in, so the simulated board enforces exactly what the Pico does.++### The simulated board++With **Board v1.2 model** on (the default), the simulator's laser current comes from the simulated head DAC through the head's soft-start (modelled as a 25 ms rise on every arm) and a 1.2 % driver gain error, the firmware core's 2 ms readback polls run against it, and the ADS1115 measures the current with its own noise and zero offset. A modelled 658 nm Fabry-Perot diode sets the rest. The threshold is 60 mA, with 0.45 mW/mA above it. The self-mixing depth is largest just above threshold. Thermal tuning is 0.006 nm/mA, so a change of current makes fringes with the target still. Mode hops come every 18 mA, with two-mode competition and partition noise near each hop. These are model values chosen to be plausible, not datasheet figures. Each channel follows the board map's stage equation with the TIA gain, second-stage gain, DAC offset and monitor bias, then the anti-alias filter and the RP2040 ADC. The external TIA's reference is not in the map; the simulator assumes 0.25 V.+ ## What the numbers are  | Quantity | Value | Where it comes from |@@ -30,6 +125,8 @@ On Windows use `smi-dash-windows-x64.exe` (CSV recording only): the Pico appears | SYNC | GPIO15, pin 20 | SN74LVC1G17 Schmitt buffer, non-inverting, 100 k pull-down at its input | | Anti-alias filter | 40.8 kHz pole plus a 44.4 kHz Sallen-Key (Q 0.98) | `design/calcs.json` | | Multimode beat | 1.46 mm | Breaking Taps' first laser; the simulator reproduces it with two longitudinal modes |+| Laser current set-point | 0 to 109.2 mA, 0.027 mA per DAC count, 45-count guard band | DAC121C085 on the laser head, 2.5 V reference, written and read back over I2C (control map) |+| Laser current readback | 0.0078 mA per count, 50 readings a second | ADS1115 on the laser head across the 2 ohm shunt (control map) |  ## The dashboard @@ -75,6 +172,8 @@ smi-dash settings get | settings set fps=30 record_format=h5 smi-dash eval --suite ``` +The board verbs (`laser`, `offset`, `gain`, `bias`, `ctl`, `board`, `tune`, `eval --board`) are listed under board v1.2 above.+ ## Fringe detection, and how well it works  The detector is classical DSP on channel 1:@@ -129,11 +228,18 @@ The 16-bit raw stream that dropped packets in the video would need 1 MB/s. This - The firmware's packer (`firmware/src/smi_frame.c`) round-trips 40,000 blocks exactly in `firmware/test/test_pack.c`, including noise that forces raw blocks, constant blocks and wrapping ramps, and its CRC matches the CRC-16/CCITT-FALSE check value. - The dashboard's Rust decoder decodes the C packer's reference stream exactly, resynchronises after garbage and drops a corrupted frame with the gap counted (`cargo test`). - End to end over a serial port: 4 s of simulated samples packed by the firmware's C code and replayed in real time through a pseudo-terminal into `smi-dash source serial` arrived as 797 frames with no CRC errors, gaps or drops at 498 ksps.-- **Not yet run on a physical Pico or board.** No hardware was available. The DMA ring, the SYNC capture timing and the USB throughput on the RP2040 itself are untested; check the STATUS frame's dropped-buffer count (shown in the dashboard's status bar) on first use.+- v1.2 control core: `firmware/test/test_ctl.c` runs the firmware's control code against the generated control table, 293 checks: boot defaults and the off state, the interlock key, refusals above the limit and of NaN, the gated write sequence (enable dropped and 2 ms waited before every laser write, the carrier only after a verified nonzero code, the readback right after arming, a failure there tripping), one write per change with the latest request winning and at most four writes a second, the guard band (command 45 disarmed, 46 is DAC code 1, 4095 is 4050), readback mismatches, heartbeat timeout, the overcurrent glitch filter and trip, the zero check before enable, a negative zero code, current-ADC loss, the laser-off-only controls, an expander that does not answer, and a DAC failure.+- v1.2 text commands: `firmware/test/text_cmd_test.py` sends the contract's text lines through `firmware/test/ctl_pty.c` (the firmware's control, text and frame code behind a pseudo-terminal) and checks the STATE frames: `laser 2000` arms at DAC code 1955, `laser current` reports the codes, `offset B` and `head` and `gain` disarm first and set their codes, `laser 45` stays disarmed and `laser 46` is DAC code 1, and an out-of-range code or an over-long line disarms (11 checks).+- v1.2 serial command path: the same stand-in, polling the DAC readback every 2 ms like the firmware, driven by `smi-dash source serial`: laser on with the key, a set-point waited on with `--wait` (60.00 mA set and read back), an offset refused while armed with the board's rule quoted, 115 mA refused at the 109.16 mA limit, a DAC-counts command mapped through the guard band, about 1,300 readback polls while armed, and killing the dashboard with the laser on turned it off by heartbeat timeout.+- v1.2 dashboard: the simulated board runs the firmware's own control code; every CLI verb and the Controls tab were exercised against it, including auto-centre and Tune cycling the laser for their writes, and the screenshots above are from that run. The Windows build's `eval --board` output is identical to the Linux build's.+- **Not yet run on a physical Pico or board.** No hardware was available. The DMA ring, the SYNC capture timing and the USB throughput on the RP2040 itself are untested; check the STATUS frame's dropped-buffer count (shown in the dashboard's status bar) on first use. The DAC121C085, DAC7574, MCP23008 and ADS1115 drivers follow their datasheets, the control map and the board's own controller patch, but have not talked to real parts: check `smi-dash board` (head_io and head_adc in the INFO line, the measured current at zero) at first power-up, before enabling the laser. The firmware keeps the 2 ms readback going during USB waits, but its timing on the RP2040 under full streaming load is untested, and the head watchdog's timeout is still being qualified by the board design.  ## Building from source  ```+# control table, from the board's control map (writes firmware/src/smi_controls_gen.h and dashboard/assets/controls.json)+python3 controls/gen_controls.py controls/control-map.json+ # firmware export PICO_SDK_PATH=/path/to/pico-sdk        # 2.1.1, with lib/tinyusb cmake -S firmware -B firmware/build -DCMAKE_BUILD_TYPE=Release
software/controls/control-map.jsonadded+357
@@ -0,0 +1,357 @@+{+  "schema": "interferometer/control-map/1",+  "hardwareVersion": "1.2.0",+  "status": "revision-1.2-controller-contract",+  "i2c": {+    "controller": "I2C0",+    "sda": {+      "gpio": 4,+      "modulePin": 6+    },+    "scl": {+      "gpio": 5,+      "modulePin": 7+    },+    "speedHz": 100000,+    "devices": {+      "dac": {+        "mpn": "DAC7574IDGSR",+        "address": "0x4c",+        "addressPins": {+          "A0": 0,+          "A1": 0+        },+        "resolutionBits": 12,+        "reference": "filtered PICO_3V3",+        "location": "main",+        "populatedControls": {+          "B": "monitorOffset",+          "C": "externalOffset"+        }+      },+      "headIo": {+        "mpn": "MCP23008T-E/SS",+        "address": "0x20",+        "resetDirection": "inputs; external pulldowns establish selector defaults"+      },+      "headAdc": {+        "mpn": "ADS1115IDGSR",+        "address": "0x49",+        "location": "laser head",+        "rateSamplesPerSecond": 128,+        "addressStrap": "ADDR to HEAD_3V3"+      },+      "headDac": {+        "mpn": "DAC121C085CIMM/NOPB",+        "address": "0x09",+        "broadcastAddress": "0x48 (reserved, do not use)",+        "addressStrap": "ADR0 and ADR1 to GND",+        "location": "laser head",+        "resolutionBits": 12,+        "reference": "REF2V5 from head REF5025",+        "powerOnCode": 0,+        "wireFormat": "two bytes, high byte first, bits 13:12 = 0, bits 11:0 = code"+      }+    }+  },+  "controls": {+    "laserCurrent": {+      "units": "mA",+      "codeRange": [+        0,+        4095+      ],+      "nominalRange": [+        0,+        110.376+      ],+      "equation": "1000 * REF2V5 * dac_code/4096 * (1000 || 1010000) / (10200 + (1000 || 1010000)) / 2 * (1000000/1010000)",+      "powerOnDefault": 0,+      "limits": {+        "rating_mA": 135,+        "nominalIndependentCutoff_mA": 123.89,+        "enablingInterlocks": [+          "GP6 asserted through protected enable receiver",+          "head I2C activity watchdog asserted",+          "head supply supervisor good",+          "head independent shunt cutoff clear",+          "Head cuts off and discharges anode before pass-gate reset on a window or enable fault."+        ],+        "fixedDividerOhms": {+          "top": 10200,+          "bottom": 1000+        },+        "faultCeiling": "min(135 mA, 1.01 * commanded current); off and disabled must stay off"+      },+      "driverLocation": "laser head",+      "signal": "HEAD_DAC_LOCAL remains entirely on the head; commands use I2C on RJ45 contacts 7 and 8.",+      "device": "headDac",+      "commandMapping": {+        "dacCodeEquation": "max(command_code - 45, 0)",+        "disarmedCommandCodes": [+          0,+          45+        ],+        "requestedFullScale_mA": 110.376,+        "nominalPhysicalFullScale_mA": 109.163,+        "reason": "Reserve 45 counts (nominally 1.213 mA) for positive DAC offset and transient error. Read back the physical current separately at the head ADC.",+        "evidenceStatus": "Screened against the linked power-contact model at the selected corners. Full two-port acceptance remains open."+      }+    },+    "laserEnable": {+      "gpio": 6,+      "modulePin": 9,+      "units": "boolean",+      "range": [+        0,+        1+      ],+      "equation": "GP6 emits a 10 kHz carrier only after a verified nonzero head DAC command.",+      "powerOnDefault": 0,+      "safety": "Hardware defaults off. Head bus watchdog, undervoltage supervisor and shunt cutoff override the request. Drop GP6 before writes and start the 10 kHz carrier only after a matching readback. Poll the DAC readback at 2 ms intervals while armed.",+      "cablePin": 2+    },+    "monitorOffset": {+      "dacChannel": "B",+      "units": "V",+      "codeRange": [+        0,+        4095+      ],+      "nominalRange": [+        0,+        3.2992+      ],+      "equation": "Voffset = VDAC_SUPPLY * code / 4096; Vstage = (1 + K) * Voffset - K * Vbuffer",+      "powerOnDefault": 0,+      "limits": "Software must keep the stage within the ADC rails; trim with laser disabled and after settling."+    },+    "externalOffset": {+      "dacChannel": "C",+      "units": "V",+      "codeRange": [+        0,+        4095+      ],+      "nominalRange": [+        0,+        3.2992+      ],+      "equation": "Voffset = VDAC_SUPPLY * code / 4096; Vstage = (1 + K) * Voffset - K * Vbuffer",+      "powerOnDefault": 0,+      "limits": "Software must keep the stage within the ADC rails; trim with laser disabled and after settling."+    },+    "headTiaGain": {+      "expanderBit": 0,+      "units": "ohm",+      "values": {+        "0": 1000,+        "1": 4700+      },+      "equation": "Vout = Vbias +/- Iphoto * Rf; sign set by diode orientation",+      "powerOnDefault": 1000,+      "safety": "Permanent 4.7 kΩ / 22 pF feedback, plus 1.27 kΩ / 24 pF when GP0 is low. Keep the laser disabled when changing."+    },+    "headMonitorBias": {+      "expanderBits": [+        1,+        2+      ],+      "units": "V",+      "values": {+        "0": {+          "label": "LOW",+          "V": 0.252+        },+        "1": {+          "label": "MID",+          "V": 2.488+        },+        "2": {+          "label": "HIGH",+          "V": 4.649+        },+        "3": {+          "label": "HIGH",+          "V": 4.649+        }+      },+      "equation": "Vbias = V(PROTECTED_HEAD_5V) * Rbottom/(Rtop + Rbottom); listed values use a 5.3 V reference rail.",+      "powerOnDefault": "LOW",+      "safety": "Select a bias compatible with the installed diode and pinout. Change with laser disabled."+    },+    "monitorSecondStageGain": {+      "gpio": 7,+      "modulePin": 10,+      "units": "V/V",+      "values": {+        "0": -5,+        "1": -20+      },+      "equation": "-Rfeedback / 1000",+      "powerOnDefault": -5,+      "safety": "Set channel offset again after changing gain."+    },+    "externalSecondStageGain": {+      "gpio": 8,+      "modulePin": 11,+      "units": "V/V",+      "values": {+        "0": -5,+        "1": -20+      },+      "equation": "-Rfeedback / 1000",+      "powerOnDefault": -5,+      "safety": "Set channel offset again after changing gain."+    },+    "externalTiaGain": {+      "gpio": 9,+      "modulePin": 12,+      "units": "ohm",+      "values": {+        "0": 46836,+        "1": 150000+      },+      "equation": "GP9 low enables the 68.1 kΩ switched branch in parallel with the permanent 150 kΩ feedback.",+      "powerOnDefault": 46836+    }+  },+  "readbacks": {+    "monitorSignal": {+      "gpio": 26,+      "modulePin": 31,+      "adc": 0,+      "units": "V",+      "equation": "code * VADC_REF / 4096"+    },+    "externalSignal": {+      "gpio": 27,+      "modulePin": 32,+      "adc": 1,+      "units": "V",+      "equation": "code * VADC_REF / 4096"+    },+    "laserCurrent": {+      "device": "ADS1115",+      "location": "laser head",+      "i2cAddress": "0x49",+      "channel": "AIN0–AIN1, differential Kelvin shunt",+      "units": "mA",+      "programmedFullScale_V": 0.512,+      "shuntOhms": 2,+      "equation": "1000 * (signed_code - zero_code) * 0.512 / (32768 * 2)",+      "safety": "Diagnostic readback; hardware cutoff senses the Kelvin shunt independently.",+      "firmwareConfig": "ADS1115 at 0x49, differential AIN0–AIN1, ±0.512 V, 128 SPS, continuous. Configure and set conversion pointer while disarmed; armed access is read-only."+    },+    "mainAnalogRail": {+      "gpio": 28,+      "modulePin": 34,+      "adc": 2,+      "units": "V",+      "source": "Main 5.3 V analog rail",+      "dividerOhms": {+        "upper": 10000,+        "lower": 10000+      },+      "equation": "2 * code * VADC_REF / 4096",+      "filter": "100 nF from ADC2 to ground"+    },+    "laserSetpointRegister": {+      "i2cAddress": "0x09",+      "format": "read two bytes; check power-down bits 13:12 and code bits 11:0",+      "scope": "Register confirmation of the transmitted DAC code. The ADS1115 measures physical current."+    }+  },+  "reserved": {+    "syncGpio": 15,+    "dacChannelD": "unconnected",+    "mainDacChannelA": "unconnected"+  },+  "requiredTestPoints": {+    "retained": "existing TP1 through TP13 and any other populated release test points",+    "added": [+      "HEAD_DAC_LOCAL",+      "DAC_B",+      "DAC_C",+      "LASER_ENABLE"+    ]+  },+  "startup": [+    "Drive laser-enable low.",+    "Write zero to the head DAC at 0x09 and verify the complete mode/code readback.",+    "Validate differential head current at zero.",+    "Configure gains, monitor bias and the main offset channels while disarmed.",+    "For each laser setpoint, drive GP6 low before writing and verify the mapped DAC code. Assert GP6 only when that code is nonzero and poll the DAC during operation.",+    "Drop GP6 on command or mode mismatch, I2C error or disconnect; a hardware watchdog also drops the head gate when SCL traffic stops."+  ],+  "cable": {+    "type": "straight-through shielded Cat6 F/UTP, 1–2 m",+    "pairs": [+      {+        "pins": [+          1,+          2+        ],+        "signals": [+          "NC_SPARE",+          "LASER_EN"+        ]+      },+      {+        "pins": [+          3,+          6+        ],+        "signals": [+          "MONITOR_AMP_OUT",+          "ANALOG_RETURN"+        ]+      },+      {+        "pins": [+          4,+          5+        ],+        "signals": [+          "HEAD_5V",+          "HEAD_POWER_RETURN"+        ]+      },+      {+        "pins": [+          7,+          8+        ],+        "signals": [+          "SDA",+          "SCL"+        ]+      }+    ],+    "shieldTermination": "Chassis at main only; isolate head shield from its ground and mechanical bracket.",+    "requiredSilkscreen": "NOT ETHERNET",+    "protectionStatus": "Decision 9 covers modeled IEEE 802.3af/at/bt PSE detection, classification, power transitions, hot plug and unplug. A directly connected bench supply or battery is unsupported and can damage the boards.",+    "candidateJackMpn": "Molex 85505-5113",+    "referenceNote": "Pin 1 is left open on both boards. Pin 6 is the protected monitor return. No laser terminal or analog laser command connects to the cable.",+    "protectionReview": "design-review/two-port-qualification.md",+    "cableSideI2cPullUpOhms": 4700,+    "draftI2cTransientLimitSeriesOhmsPerEnd": 270,+    "watchdogs": {+      "enableCarrier_Hz": 10000,+      "firmwareReadbackInterval_ms": 2,+      "busMonostableTiming": "100 kΩ and 100 nF; exact guaranteed timeout pending component and circuit qualification"+    },+    "headFeedNominal_V": 5.296,+    "candidateJackRating_VDC": 125,+    "headFeedQualification": "Nominal regulated cable feed is 5.296 V in the modeled forced-PWM design. The reviewed PoE fixtures, boundary conditions and modeled component stress are linked from the qualification report."+  },+  "firmwareCommands": {+    "transport": "One text command per USB CDC line with the revision 1.2 Pico controller patch.",+    "laser": "laser CODE (0–4095) or laser off",+    "head": "head MASK (0–7, MCP23008 GP0–2)",+    "gain": "gain MASK (0–7, Pico GP7–9)",+    "offset": "offset B CODE or offset C CODE (0–4095)",+    "selectorAndOffsetWrites": "disable the laser first; it stays disarmed until a fresh verified laser command",+    "current": "laser current returns the signed ADS1115 conversion code, requested command code and transmitted DAC code in an INFO frame"+  }+}
software/controls/control_table.pyadded+69
@@ -0,0 +1,69 @@+#!/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))
software/controls/gen_controls.pyadded+429
@@ -0,0 +1,429 @@+#!/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 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 main():+    if len(sys.argv) != 2:+        sys.exit("usage: gen_controls.py <control-map.json>")+    src = json.loads(Path(sys.argv[1]).read_text())+    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()
software/dashboard/Cargo.lock+2−1
@@ -1285,9 +1285,10 @@ checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59"  [[package]] name = "smi-dash"-version = "1.0.0"+version = "1.2.1" dependencies = [  "axum",+ "cc",  "chrono",  "clap",  "futures",
software/dashboard/Cargo.toml+4−1
@@ -1,6 +1,6 @@ [package] name = "smi-dash"-version = "1.0.0"+version = "1.2.1" edition = "2021" license = "MIT" description = "Dashboard, simulator and CLI for a self-mixing laser interferometer read by a Raspberry Pi Pico"@@ -29,6 +29,9 @@ rand_distr = "0.4" chrono = { version = "0.4", default-features = false, features = ["clock"] } hdf5 = { package = "hdf5-metno", version = "0.9", optional = true } +[build-dependencies]+cc = "1"+ [profile.release] opt-level = 3 lto = "thin"
software/dashboard/README.md+12−4
@@ -4,13 +4,15 @@ One binary. `smi-dash start` runs a small local web server (Rust, axum) that own  | File | Role | |---|---|-| `src/sim.rs` | Lang-Kobayashi self-mixing model, target motions, multimode beat, the board's analog chain and the RP2040 ADC |+| `src/sim.rs` | Lang-Kobayashi self-mixing model, target motions, multimode beat, the board's analog chain and the RP2040 ADC; with board v1.2, the laser's current dependence (power, tuning, mode hops) |+| `src/controls.rs` | Board v1.2: the control map, the command protocol, and the simulated board, which runs the firmware's `smi_ctl.c` (compiled in by `build.rs`) and models the driver, the ADS1115, the DAC and the switches |+| `src/tune.rs` | Commands to the simulated board or the Pico, auto-centre, tune for fringes | | `src/dsp.rs` | Fringe detector (low-pass, envelope, edge detection, direction) and the spectrum | | `src/proto.rs` | Decoder for the firmware's framed stream, with resync and CRC | | `src/engine.rs` | Sample rings, displacement history, display frames, acquisition and serial threads | | `src/record.rs` | CSV (streamed) and HDF5 (written on stop) recording | | `src/server.rs` | HTTP API, SSE live channel, settings, page console |-| `src/eval.rs` | Offline accuracy suite against the simulator's ground truth |+| `src/eval.rs` | Offline accuracy suites against the simulator's ground truth (`--suite`, and `--board` through the simulated v1.2 board) | | `src/main.rs` | CLI |  ## Use@@ -39,13 +41,19 @@ Run `smi-dash --help` or `smi-dash <verb> --help` for every flag. Each answer st | `GET/POST /settings` | Persisted settings | | `POST /ui/{toast,click,reveal,cursor,reload}` | Drive the open page | | `GET/POST /console` | The page's console, readable by the CLI |+| `GET /board` | Board state joined with the control map, the map and its hash, tune progress |+| `POST /board/laser` | `{on: false}`, or `{on: true, confirm: "beam-safe"}` |+| `POST /board/set` | `{id, value, unit: units\|counts\|index}`; id is a map id or an alias (laser, ch1-offset, ch2-amp, bias, ...) |+| `POST /board/read_current`, `/board/auto_centre`, `/board/clear_fault`, `/board/config` | Readback, centring, faults, current-sense rate and heartbeat timeout |+| `GET/POST /board/tune`, `POST /board/tune/stop` | Tune for fringes | -Settings persist in `~/.adom/instances/smi-dash/settings.json`; each thread's simulator and view settings are restored from `snapshots/` on the next start. An idle server saves and exits after 24 h (Settings, or `--keep-alive`). `View > keep_awake` (`smi-dash view --keep-awake on`) makes the page hold a screen wake lock for unattended recordings; it is off by default.+Settings persist in `~/.adom/instances/smi-dash/settings.json`; each thread's simulator and view settings are restored from `snapshots/` on the next start. An idle server saves and exits after 24 h (Settings, or `--keep-alive`). While the laser is on, the server sends the firmware a heartbeat every second; if the server stops, the firmware turns the laser off after 3 s. `View > keep_awake` (`smi-dash view --keep-awake on`) makes the page hold a screen wake lock for unattended recordings; it is off by default.  ## Build  ```-cargo build --release                                                        # Linux, needs libudev-dev, libhdf5-dev+python3 ../controls/gen_controls.py ../controls/control-map.json             # after any change to the control map+cargo build --release                                                        # Linux, needs libudev-dev, libhdf5-dev (and a C compiler: build.rs compiles smi_ctl.c) cargo build --release --target x86_64-pc-windows-gnu --no-default-features   # Windows, CSV only cargo test --release ```
software/dashboard/SKILL.md+20−5
@@ -3,9 +3,11 @@ name: smi-dash description: >-   Drive the self-mixing interferometer dashboard (smi-dash): live ADC0/ADC1 fringes from the   Raspberry Pi Pico or the built-in simulator, fringe counting with direction, displacement in-  nm and um, velocity, spectrum, SYNC markers, CSV/HDF5 recording, and an accuracy suite against-  simulated ground truth. Use when asked to show the interferometer, simulate a moving target,-  count fringes, record the photodiode channels, or check the detector's error.+  nm and um, velocity, spectrum, SYNC markers, CSV/HDF5 recording, an accuracy suite against+  simulated ground truth, and on board v1.2 every board setting: laser enable and current, offsets,+  gains, monitor bias, auto-centre and tune for fringes. Use when asked to show the interferometer,+  simulate a moving target, count fringes, record the photodiode channels, set or tune the laser,+  centre a channel, change a gain, or check the detector's error. ---  # smi-dash@@ -21,10 +23,23 @@ smi-dash --ai-thread "<your thread>" show Every verb answers `OK:`/`ERROR:` with `Hint:` lines; follow the hints. Verbs: `status`, `source sim|serial`, `sim --profile constant|sine|step|hand|hold ...`, `detect --lp-hz --threshold --invert`, `view --window-ms --history-s --pause --resume --keep-awake`, `zero`, `record start|stop|status`, `ui toast|click|reveal|cursor|reload`,-`settings get|set`, `console`, `eval --suite`, `stop`.+`settings get|set`, `console`, `eval --suite|--board`, `stop`.++Board v1.2: `laser on --beam-safe|off|current <mA> [--wait]|read`, `offset ch1|ch2 <V> [--counts]`,+`offset auto [ch1|ch2|both]`, `gain ch1-tia|ch1-amp|ch2-tia|ch2-amp <value>`, `bias low|mid|high`,+`ctl <map id> <value>`, `board [map|clear-fault|config]`, `tune [--status|--stop]`.++Laser rules for an AI: only turn the laser on with `--beam-safe` when the human has said the beam is+enclosed or they wear eyewear. Tuning never turns it on. Offsets, gains and bias change only with the+laser off (board rule; the firmware refuses otherwise); `offset auto` and `tune` cycle the laser for+their writes themselves. Each set-point write restarts the head's soft-start, so set the current once,+with `--wait`, rather than in small steps. Tune needs a moving target. After a gain change run+`offset auto`. If `board` shows a fault, report it to the human before `board clear-fault`.  Selectors for `ui click`: `#btn-pause #btn-zero #btn-record #btn-settings #src-sim #src-serial-[data-profile=sine] #mm-toggle #s-close`. A toast you raise with `ui toast` appears on the user's screen.+[data-profile=sine] #mm-toggle #s-close #tab-board #tab-sim #btn-centre #btn-tune #btn-tune-stop+#laser-off [data-ctl=<map id>][data-v=<value>]`. Enabling the laser needs a real one-second hold on the+page, so use the CLI for that. `ui tab board|sim` switches the side panel. A toast you raise with `ui toast` appears on the user's screen.  ## Displaying this app (REQUIRED, read before showing anything) 
software/dashboard/assets/controls.jsonadded+1
@@ -0,0 +1 @@+{"controls":[{"at_zero":0.0,"bits":12,"ch":0,"dac":1,"default":0.0,"disarm_us":2000,"guard":45,"hw_cutoff_mA":123.89,"id":"laserCurrent","kind":"dac","label":"Laser current","max":109.16269930424299,"max_code":4050,"min":0.0,"min_write_ms":250,"per_code":0.0269537529146279,"ramp_per_s":0.0,"rated":135.0,"requires_laser_off":false,"role":"laser","unit":"mA"},{"at_zero":0.0,"bits":12,"ch":1,"channel":1,"dac":0,"default":0.0,"gain_link":"monitorSecondStageGain","id":"monitorOffset","kind":"dac","label":"Offset, channel 1","max":3.299194,"min":0.0,"offset_gain":"1 + |K| of monitorSecondStageGain","per_code":0.0008056640625,"ramp_per_s":0.0,"requires_laser_off":true,"role":"offset","safety":"disable the laser first; it stays disarmed until a fresh verified laser command","unit":"V"},{"at_zero":0.0,"bits":12,"ch":2,"channel":2,"dac":0,"default":0.0,"gain_link":"externalSecondStageGain","id":"externalOffset","kind":"dac","label":"Offset, channel 2","max":3.299194,"min":0.0,"offset_gain":"1 + |K| of externalSecondStageGain","per_code":0.0008056640625,"ramp_per_s":0.0,"requires_laser_off":true,"role":"offset","safety":"disable the laser first; it stays disarmed until a fresh verified laser command","unit":"V"},{"channel":1,"default":1000.0,"gpios":[32],"id":"headTiaGain","kind":"switch","label":"Monitor TIA","max":4700.0,"min":1000.0,"requires_laser_off":true,"role":"gain","safety":"Permanent 4.7 k\u03a9 / 22 pF feedback, plus 1.27 k\u03a9 / 24 pF when GP0 is low. Keep the laser disabled when changing.","settings":[{"code":0,"label":"1 k","value":1000.0},{"code":1,"label":"4.7 k","value":4700.0}],"stage":"tia","unit":"ohm"},{"channel":1,"default":-5.0,"gpios":[7],"id":"monitorSecondStageGain","kind":"switch","label":"Monitor second stage","max":-5.0,"min":-20.0,"requires_laser_off":true,"role":"gain","safety":"Set channel offset again after changing gain.","settings":[{"code":0,"label":"-5 V/V","value":-5.0},{"code":1,"label":"-20 V/V","value":-20.0}],"stage":"amp","unit":"V/V"},{"channel":2,"default":46836.0,"gpios":[9],"id":"externalTiaGain","kind":"switch","label":"External TIA","max":150000.0,"min":46836.0,"requires_laser_off":true,"role":"gain","safety":"disable the laser first; it stays disarmed until a fresh verified laser command","settings":[{"code":0,"label":"46.836 k","value":46836.0},{"code":1,"label":"150 k","value":150000.0}],"stage":"tia","unit":"ohm"},{"channel":2,"default":-5.0,"gpios":[8],"id":"externalSecondStageGain","kind":"switch","label":"External second stage","max":-5.0,"min":-20.0,"requires_laser_off":true,"role":"gain","safety":"Set channel offset again after changing gain.","settings":[{"code":0,"label":"-5 V/V","value":-5.0},{"code":1,"label":"-20 V/V","value":-20.0}],"stage":"amp","unit":"V/V"},{"default":0.252,"gpios":[33,34],"id":"headMonitorBias","kind":"switch","label":"Monitor bias","max":4.649,"min":0.252,"requires_laser_off":true,"role":"bias","safety":"Select a bias compatible with the installed diode and pinout. Change with laser disabled.","settings":[{"code":0,"label":"Low 0.252 V","value":0.252},{"code":1,"label":"Mid 2.488 V","value":2.488},{"code":2,"label":"High 4.649 V","value":4.649},{"code":3,"label":"High 4.649 V","value":4.649}],"unit":"V"}],"dacs":[{"bits":12,"dev":0,"i2c_addr":76,"part":"DAC7574","vref_V":3.3},{"bits":12,"dev":1,"i2c_addr":9,"part":"DAC121C085","vref_V":2.5}],"expander":{"i2c_addr":32,"part":"MCP23008"},"i2c":{"bus":0,"hz":100000,"scl":5,"sda":4},"isense":{"data_rate_sps":128,"device":"ADS1115","full_scale_V":0.512,"i2c_addr":73,"input":"AIN0-AIN1","mA_per_code":0.0078125,"mux":0,"offset_mA":0.0,"rate_hz":50,"trip_mA":116.0,"zero_calibrated":true},"laser_enable":{"active_high":true,"carrier_hz":10000,"gpio":6},"laser_watch":{"gate_writes":true,"readback_poll_ms":2},"map_version":"1.2.0-revision-1.2-controller-contract","rail":{"adc":2,"adc_vref_V":3.3,"gpio":28,"nominal_V":5.3,"scale":2,"source":"Main 5.3 V analog rail"}}\ No newline at end of file
software/dashboard/assets/index.html+217−4
@@ -105,8 +105,60 @@ footer{display:flex;align-items:center;gap:14px;padding:0 12px;background:var(-- .srow label{font:12px var(--f-body);color:var(--text-body)} .srow input[type=text],.srow input[type=number]{font:12px var(--f-mono);background:var(--bg);color:var(--text);border:1px solid var(--border);border-radius:6px;padding:4px 6px;width:100%} .ver{font:11px var(--f-mono);color:var(--text-3)}-@media (max-width:900px){main{grid-template-columns:1fr}aside{display:none}}+@media (max-width:900px){main{grid-template-columns:minmax(0,1fr) 250px}.slider{grid-template-columns:64px 1fr 64px}.sw-row{grid-template-columns:80px 1fr}}+/* narrow panes: the side panel becomes a drawer opened from the header */+#btn-panel{display:none}+@media (max-width:620px){main{grid-template-columns:1fr}aside{display:none}#btn-panel{display:grid}+  aside.open{display:flex;position:fixed;right:0;top:44px;bottom:24px;width:min(330px,94vw);z-index:60;background:var(--bg);padding:8px;border-left:1px solid var(--border);box-shadow:-12px 0 24px rgba(0,0,0,.45)}} @media (max-height:520px){.plots{grid-template-rows:1.3fr .8fr 1fr 0fr}#card-spec{display:none}}+/* aside tabs and the board Controls panel */+.ro-line{display:none;font:600 13px var(--f-mono);color:var(--text);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}+aside.board-mode #p-readout{flex-direction:row;align-items:baseline;gap:10px;padding:5px 9px}+aside.board-mode #p-readout .big,aside.board-mode #p-readout .sub2,aside.board-mode #p-readout .grid2{display:none}+aside.board-mode #p-readout .ro-line{display:block}+aside.board-mode #p-readout>.lbl{display:none}+aside.board-mode .panel{padding:5px 9px;gap:4px}+.tabs{display:flex;gap:2px;background:var(--bg);border:1px solid var(--border);border-radius:7px;padding:2px}+.tabs button{flex:1;padding:4px 6px;border-radius:5px;font:600 12px var(--f-head);color:var(--text-2)}+.tabs button.is-on{background:var(--elevated);color:var(--text);box-shadow:inset 0 -2px 0 var(--accent)}+.tabbody{display:flex;flex-direction:column;gap:8px;min-height:0}+.ph{display:flex;align-items:center;gap:8px}+.ph .lbl{font:600 12px var(--f-head);color:var(--text)}+.pill{margin-left:auto;font:600 10px var(--f-mono);letter-spacing:.4px;padding:1px 7px;border-radius:10px;border:1px solid var(--border);color:var(--text-3)}+.pill.on{color:#ffb4a8;border-color:var(--red);background:color-mix(in srgb,var(--red) 18%,transparent)}+.pill.ramp{color:var(--yellow);border-color:var(--yellow)}+.pill.fault{color:#fff;background:var(--red);border-color:var(--red)}+.ilock{display:flex;align-items:center;gap:7px;font:12px var(--f-body);color:var(--text-body);cursor:pointer;user-select:none}+.ilock .box{width:15px;height:15px;border-radius:4px;border:1.5px solid var(--text-3);display:grid;place-items:center;flex:none}+.ilock.is-on .box{border-color:var(--yellow);background:color-mix(in srgb,var(--yellow) 25%,transparent)}+.ilock.is-on .box::after{content:"";width:7px;height:4px;border-left:2px solid var(--yellow);border-bottom:2px solid var(--yellow);transform:rotate(-45deg) translate(1px,-1px)}+.lrow{display:grid;grid-template-columns:1fr 1fr;gap:6px}+.hold{position:relative;overflow:hidden;padding:7px 8px;border-radius:6px;border:1px solid var(--red);background:color-mix(in srgb,var(--red) 10%,var(--elevated));font:600 12px var(--f-body);color:#ffd0c9}+.hold:disabled{opacity:.4;cursor:not-allowed}+.hold .fill{position:absolute;inset:0;width:0;background:color-mix(in srgb,var(--red) 45%,transparent);transition:width .05s linear}+.hold span{position:relative}+.btn.off{border-color:var(--border);background:var(--elevated)}+.kv3{display:grid;grid-template-columns:repeat(3,1fr);gap:4px}+.kv3 .v{font:600 12px var(--f-mono);color:var(--text)}+.kv3 .v.meas{color:var(--accent-bright)}+.numrow{display:grid;grid-template-columns:96px 1fr 66px;align-items:center;gap:6px}+.numrow span{font:11px var(--f-body);color:var(--text-2);white-space:nowrap}+.numrow input[type=number]{font:12px var(--f-mono);background:var(--bg);color:var(--text);border:1px solid var(--border);border-radius:5px;padding:2px 5px;width:100%}+.spark{height:24px;position:relative}.spark canvas{position:absolute;inset:0;width:100%;height:100%}+.sw-row{display:grid;grid-template-columns:78px 1fr;align-items:center;gap:6px}+.sw-row>span{font:11px var(--f-body);color:var(--text-2);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}+.sw-row .seg button{font-size:11px;padding:1px 2px}+#switch-rows{display:flex;flex-direction:column;gap:2px}+aside.board-mode .seg{padding:1px}+aside.board-mode .tunebar{display:none}+aside.board-mode #tune-msg{display:none}+#tune-t{font:11px var(--f-mono);color:var(--text-2);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;min-width:0}+#offset-rows{display:flex;flex-direction:column;gap:3px}+.sw-row.locked .seg{opacity:.45}+.sw-row.locked>span{color:var(--text-3)}+.tunebar{height:4px;border-radius:2px;background:var(--border);overflow:hidden}.tunebar i{display:block;height:100%;width:0;background:var(--accent);transition:width .3s}+.warnline{font:11px var(--f-body);color:var(--yellow)}+.faultline{display:flex;align-items:center;gap:8px;font:12px var(--f-body);color:#ffb4a8} /* ?frame=16x9: an exact 16:9 stage, letterboxed in black, for screen recordings */ html.framed,html.framed body{background:#000} html.framed #app{position:absolute;inset:0;margin:auto;width:min(100vw,177.7778vh);height:min(56.25vw,100vh);background:var(--bg)}@@ -128,6 +180,8 @@ html.framed #app{position:absolute;inset:0;margin:auto;width:min(100vw,177.7778v       <svg viewBox="0 0 16 16"><circle cx="8" cy="8" r="5"/><path d="M8 1v3M8 12v3M1 8h3M12 8h3"/></svg></button>     <button class="ib" id="btn-record" data-tip="Record both channels, SYNC, fringes and displacement. Format and folder are in Settings. Click again to stop and save." aria-pressed="false">       <svg viewBox="0 0 16 16"><circle cx="8" cy="8" r="4.5"/></svg></button>+    <button class="ib" id="btn-panel" data-tip="Show the side panel: readouts, the board Controls, source and simulator." aria-pressed="false">+      <svg viewBox="0 0 16 16"><rect x="2" y="3" width="12" height="10" rx="1.5"/><path d="M10 3v10"/></svg></button>     <button class="ib" id="btn-settings" data-tip="Settings: frame rate, units, recording format and folder, detector tuning, idle shutdown.">       <svg viewBox="0 0 16 16"><circle cx="8" cy="8" r="2.2"/><path d="M8 1.5v2M8 12.5v2M1.5 8h2M12.5 8h2M3.4 3.4l1.4 1.4M11.2 11.2l1.4 1.4M3.4 12.6l1.4-1.4M11.2 4.8l1.4-1.4"/></svg></button>   </div>@@ -158,8 +212,9 @@ html.framed #app{position:absolute;inset:0;margin:auto;width:min(100vw,177.7778v     </div>   </section>   <aside>-    <div class="panel">+    <div class="panel" id="p-readout">       <div class="lbl">Displacement</div>+      <div class="ro-line" id="ro-line" data-tip="Counted displacement, velocity and direction. The full readouts are on the Source and simulator tab."></div>       <div class="big" id="ro-disp">0 nm</div>       <div class="sub2" id="ro-disp2">0.000 µm</div>       <div class="grid2">@@ -169,6 +224,47 @@ html.framed #app{position:absolute;inset:0;margin:auto;width:min(100vw,177.7778v         <div class="kv"><div class="lbl">Direction</div><div class="v"><span class="dirpill" id="ro-dir">none</span></div></div>       </div>     </div>+    <div class="tabs" role="tablist">+      <button id="tab-board" class="is-on" data-tip="Board v1.2: laser, offsets, gains and bias, set from software. Every control is also a CLI verb (smi-dash laser, offset, gain, bias, tune).">Controls</button>+      <button id="tab-sim" data-tip="Data source, fringe detector and the simulated target.">Source and simulator</button>+    </div>+    <div class="tabbody" id="body-board">+      <div class="panel" id="p-laser">+        <div class="ph"><span class="lbl">Laser</span><span class="hint" id="laser-why"></span><span class="pill" id="laser-pill">OFF</span></div>+        <div class="ilock" id="laser-interlock" role="checkbox" aria-checked="false" data-tip="Interlock. The HL6501MG is a class 3B laser: enclose the beam path or wear 658 nm eyewear before enabling. Ticking this arms the Enable button; it clears itself when the laser goes off.">+          <span class="box"></span><span>Beam path enclosed or eyewear on</span></div>+        <div class="lrow">+          <button class="hold" id="laser-hold" disabled data-tip="Hold for one second to enable the laser. The firmware writes the set-point to the head DAC, reads it back, and only then starts the enable carrier; the head's soft-start ramps the current."><i class="fill" id="laser-fill"></i><span id="laser-hold-t">Hold to enable</span></button>+          <button class="btn off" id="laser-off" data-tip="Laser off at once: the hardware enable drops and the set-point returns to 0 mA.">Laser off</button>+        </div>+        <div class="numrow" data-tip="Laser current set-point, sent when you release the slider or press Enter. Each write disarms the head, is read back, and re-arms; the head's soft-start ramps the current. The firmware refuses anything above its limit (the head DAC's top less its guard band)."><span>Current</span><input type="range" id="cur-slider" min="0" max="119" step="0.1"><input type="number" id="cur-input" min="0" step="0.5"></div>+        <div class="kv3">+          <div class="kv" data-tip="What you asked for."><div class="lbl">Target</div><div class="v" id="ro-target">0 mA</div></div>+          <div class="kv" data-tip="The set-point the head DAC holds now (verified by readback every 2 ms while on)."><div class="lbl">Set-point</div><div class="v" id="ro-setp">0 mA</div></div>+          <div class="kv" data-tip="Laser current measured on the laser head by its ADS1115 across the 2 ohm shunt (0.0078 mA per code), read by the Pico over I2C; zero code calibrated with the laser off."><div class="lbl">Measured</div><div class="v meas" id="ro-meas">n/a</div></div>+        </div>+        <div class="spark" data-tip="Last 20 s: set-point (grey) and measured current (teal)."><canvas id="cv-cur"></canvas></div>+        <div class="faultline hide" id="fault-line"><span id="fault-text"></span><button class="btn" id="btn-clear-fault">Clear fault</button></div>+        <div class="warnline hide" id="map-warn">The firmware's control map differs from this dashboard's. Flash the matching smi_pico.uf2.</div>+      </div>+      <div class="panel" id="p-offsets">+        <div class="ph"><span class="lbl">Offsets</span><button class="btn" id="btn-centre" style="margin-left:auto;padding:3px 9px" data-tip="Servo each channel's mean to mid-scale (code 2048) with its offset DAC. Uses the board's stage equation, Vstage = (1 + K) Voffset - K Vbuffer, then refines on the measured slope. With the laser on it turns it off for each offset write and back on at the same set-point (board rule).">Auto-centre</button></div>+        <div id="offset-rows"></div>+      </div>+      <div class="panel" id="p-gains">+        <div class="ph"><span class="lbl">Gains and bias</span></div>+        <div id="switch-rows"></div>+      </div>+      <div class="panel" id="p-tune">+        <div class="ph"><span class="lbl">Tune</span><span id="tune-t"></span>+          <button class="btn primary" style="margin-left:auto;padding:3px 12px" id="btn-tune" data-tip="Steps the laser current, re-centres, scores fringe contrast (swing over noise, clipping penalised), then tries the second-stage gains. Move the target while it runs: this board's laser current cannot be dithered. Needs the laser on; never turns it on.">Tune</button>+          <button class="btn" style="padding:3px 9px" id="btn-tune-stop" data-tip="Stop tuning; the last setting stays.">Stop</button>+        </div>+        <div class="tunebar"><i id="tune-bar"></i></div>+        <div class="hint" id="tune-msg" data-tip="Score = fringe swing / noise, clipping penalised. TIA gain and bias are left to you: the board says change them with the laser off.">Steps current and stage-2 gain; TIA and bias stay yours.</div>+      </div>+    </div>+    <div class="tabbody hide" id="body-sim">     <div class="panel" id="p-truth" data-tip="Only with the simulator: the counted displacement compared with the simulated target's true position. Counting resolves one fringe, 329 nm, so errors up to that size are expected.">       <div class="grid2">         <div class="kv"><div class="lbl">Simulator truth</div><div class="v" id="ro-truth">0</div></div>@@ -198,6 +294,8 @@ html.framed #app{position:absolute;inset:0;margin:auto;width:min(100vw,177.7778v       <div class="slider" data-tip="Optical feedback strength C. Below 1 the fringes are near-sinusoidal; above 1 they become sawteeth that lean with the direction of motion."><span>Feedback C</span><input type="range" id="c-slider" min="0" max="8" step="0.05"><output id="c-out"></output></div>       <div class="slider" data-tip="Extra intensity and mechanical noise, times a clean bench."><span>Noise</span><input type="range" id="noise-slider" min="0" max="20" step="0.5"><output id="noise-out"></output></div>       <div class="toggle" id="mm-toggle" role="switch" aria-pressed="false" data-tip="Add a second longitudinal mode. The two fringe patterns beat and the signal fades every 1.46 mm of travel, the problem a single-mode laser like the HL6501MG removes."><span>Multimode laser (1.46 mm beat)</span><span class="sw"></span></div>+      <div class="toggle" id="board-toggle" role="switch" aria-pressed="true" data-tip="Model board v1.2: the laser current, gains, offsets and bias come from the Controls tab, through the firmware's own control code. Off: the v1.1 board with screwdriver trims."><span>Board v1.2 model</span><span class="sw"></span></div>+    </div>     </div>   </aside> </main>@@ -205,6 +303,7 @@ html.framed #app{position:absolute;inset:0;margin:auto;width:min(100vw,177.7778v   <span><span class="led" id="led"></span><span id="st-link">connecting</span></span>   <span id="st-rate"></span><span id="st-frames"></span><span id="st-err"></span><span id="st-fps"></span>   <span id="rec-hint">Not recording</span>+  <span id="st-rail" data-tip="Main board 5.3 V analog rail, read by the Pico on ADC2 (GPIO28) through a 1:2 divider, once a second."></span>   <span style="margin-left:auto" id="st-ver"></span> </footer> </div>@@ -365,6 +464,11 @@ function drawChannel(id,ch,key,color,withMarks){       g.fill();     }   }+  if(withMarks&&F.board&&!F.board.laser.on){+    const msg="Laser off · enable it in Controls"; g.font="600 13px "+css("--f-head"); const tw=g.measureText(msg).width;+    g.fillStyle=css("--surface"); g.globalAlpha=.88; g.fillRect(x0+pw/2-tw/2-12,y0+ph/2-14,tw+24,28); g.globalAlpha=1;+    g.strokeStyle=css("--border"); g.strokeRect(x0+pw/2-tw/2-12+.5,y0+ph/2-14+.5,tw+24,28);+    g.fillStyle=css("--text-2"); g.textAlign="center"; g.textBaseline="middle"; g.fillText(msg,x0+pw/2,y0+ph/2) }   g.restore(); } @@ -406,6 +510,7 @@ function render(){   $("#ro-disp").textContent=fmtDisp(r.disp_nm);   $("#ro-disp2").textContent=Math.abs(r.disp_nm)<10000?(r.disp_nm/1000).toFixed(3)+" µm":Math.round(r.disp_nm).toLocaleString("en-US")+" nm";   $("#ro-vel").textContent=fmtVel(r.vel_um_s);+  $("#ro-line").textContent=fmtDisp(r.disp_nm)+"  "+fmtVel(r.vel_um_s);   $("#ro-rate").textContent=fmtHz(r.fringe_rate_hz);   $("#ro-count").textContent=r.count.toLocaleString("en-US");   const dp=$("#ro-dir"), moving=Math.abs(r.vel_um_s)>0.4*r.half_wave_nm/1000*10;@@ -414,7 +519,8 @@ function render(){   else {dp.innerHTML='<svg viewBox="0 0 10 10"><path d="M5 9L1 2h8z"/></svg>towards';dp.style.color="var(--toward)";dp.style.borderColor="var(--toward)"}   const hasT=r.truth_nm!=null; $("#p-truth").classList.toggle("hide",!hasT); $("#lg-truth").classList.toggle("hide",!hasT);   if(hasT){ $("#ro-truth").textContent=fmtDisp(r.truth_nm); $("#ro-err").textContent=Math.round(r.err_nm)+" nm"; $("#ro-rms").textContent=Math.round(r.rms_err_nm)+" nm"; $("#ro-max").textContent=Math.round(r.max_err_nm)+" nm" }-  $("#ch1-r").textContent=F.win_ms.toFixed(F.win_ms<1?2:F.win_ms<10?1:0)+" ms window"+(F.paused?" · frozen":"");+  const weak=F.board&&F.board.laser.on&&F.swing&&F.swing[0]<1.25*F.min_pp_codes;+  $("#ch1-r").innerHTML=(weak?`<span style="color:var(--yellow)" data-tip="The fringe swing is ${F.swing[0]} codes; the detector needs at least ${F.min_pp_codes}. Raise the second-stage gain or run Tune.">signal small · raise gain or Tune</span> · `:"")+F.win_ms.toFixed(F.win_ms<1?2:F.win_ms<10?1:0)+" ms window"+(F.paused?" · frozen":"");   $("#ch2-r").textContent=(F.ch2.mx.length?"":"");   $("#disp-r").textContent=F.disp.span_s.toFixed(1)+" s";   $("#spec-r").textContent=F.spec&&F.spec.peak_hz?"peak "+fmtHz(F.spec.peak_hz)+" · "+fmtVel(F.spec.peak_hz*r.half_wave_nm/1000):"";@@ -426,9 +532,11 @@ function render(){   $("#st-frames").textContent=serial?("frames "+L.frames):"";   $("#st-err").textContent=serial?("crc "+L.crc_errors+" · gaps "+L.gaps+" · dropped "+L.dropped_bufs):"";   $("#st-fps").textContent=fpsEMA.toFixed(0)+" fps";+  $("#st-rail").textContent=F.rail_v!=null?("analog rail "+F.rail_v.toFixed(2)+" V"+(serial?"":" (sim)")):"";   const rec=F.rec, rb=$("#btn-record"); rb.classList.toggle("rec-on",!!rec); rb.setAttribute("aria-pressed",!!rec);   $("#rec-hint").textContent=rec?("Recording "+rec.seconds.toFixed(1)+" s"+(rec.limit_seconds?" of "+rec.limit_seconds.toFixed(0):"")+" to "+rec.path.split(/[\\/]/).pop()):(F.rec_error?("Recording error: "+F.rec_error):"Not recording");   const pb=$("#btn-pause"); pb.classList.toggle("is-on",F.paused); pb.setAttribute("aria-pressed",F.paused);+  renderBoard(); }  // motion sliders per profile@@ -461,14 +569,16 @@ function applyState(){   const sim=S.sim, serial=S.source.kind==="serial";   $("#src-sim").classList.toggle("is-on",!serial); $("#src-serial").classList.toggle("is-on",serial);   $("#p-sim").classList.toggle("hide",serial);+  buildControls();   $("#subj").textContent=serial?"Pico on "+S.source.port:"Simulator";-  $("#subj-meta").textContent=`250 ksps per channel · λ ${sim.wavelength_nm} nm · 1 fringe = ${sim.wavelength_nm/2} nm`+(serial?"":` · C ${sim.c}`+(sim.multimode?" · multimode":""));+  $("#subj-meta").textContent=`250 ksps per channel · λ ${sim.wavelength_nm} nm · 1 fringe = ${sim.wavelength_nm/2} nm`+(serial?"":` · C ${sim.c}`+(sim.multimode?" · multimode":"")+(sim.board?" · board v1.2":" · board v1.1"));   for(const b of document.querySelectorAll("[data-profile]")) b.classList.toggle("is-on",b.dataset.profile===sim.profile);   buildMotion(sim.profile);   for(const i of document.querySelectorAll("#motion-sliders input")) i._sync&&i._sync();   if(dragging!==$("#c-slider")){ $("#c-slider").value=sim.c; } $("#c-out").textContent=(+sim.c).toFixed(2);   if(dragging!==$("#noise-slider")){ $("#noise-slider").value=sim.noise; } $("#noise-out").textContent="x"+(+sim.noise).toFixed(1);   const mm=$("#mm-toggle"); mm.classList.toggle("is-on",sim.multimode); mm.setAttribute("aria-pressed",sim.multimode);+  const bt=$("#board-toggle"); bt.classList.toggle("is-on",!!sim.board); bt.setAttribute("aria-pressed",!!sim.board);   if(dragging!==$("#lp-slider")) $("#lp-slider").value=LPMAP.to(S.detect.lp_hz); $("#lp-out").textContent=fmtHz(S.detect.lp_hz);   const st=S.settings; $("#s-fps").value=st.fps; $("#s-units").value=st.units; $("#s-format").value=st.record_format; $("#s-dir").value=st.record_dir;   $("#s-thr").value=S.detect.threshold; $("#s-ttl").value=st.ttl_hours; $("#s-surface").value=st.surface;@@ -503,6 +613,7 @@ $("#btn-pause").onclick=()=>post("view",{paused:!F.paused}); $("#btn-zero").onclick=()=>post("zero",{}); $("#btn-record").onclick=()=>{ if(F&&F.rec) post("record/stop",{}); else post("record/start",{}) }; $("#btn-settings").onclick=()=>$("#modal").classList.add("show");+$("#btn-panel").onclick=()=>{ const a=document.querySelector("aside"), o=!a.classList.contains("open"); a.classList.toggle("open",o); $("#btn-panel").classList.toggle("is-on",o); $("#btn-panel").setAttribute("aria-pressed",o) }; $("#s-close").onclick=()=>$("#modal").classList.remove("show"); $("#modal").onclick=e=>{ if(e.target.id==="modal") $("#modal").classList.remove("show") }; const setS=(k,v)=>post("settings",{[k]:v}).then(j=>{ if(j&&j.status==="ok") toast("Saved: "+k.replace("_"," ")) });@@ -515,6 +626,104 @@ $("#s-surface").onchange=e=>setS("surface",e.target.value); $("#s-thr").onchange=e=>post("detect",{threshold:+e.target.value}).then(()=>toast("Saved: detector threshold")); $("#s-invert").onclick=()=>post("detect",{invert:!S.detect.invert}).then(()=>toast("Saved: direction "+(S.detect.invert?"normal":"inverted"))); ++// ---------------------------------------------------------------- Controls --+const BS=()=>F&&F.board, MAP=()=>S&&S.board_map;+function ctlIdx(role,ch,stage){const m=MAP(); if(!m) return -1; return m.controls.findIndex(c=>c.role===role&&(ch==null||c.channel===ch)&&(stage==null||c.stage===stage))}+function setTab(t){ $("#tab-board").classList.toggle("is-on",t==="board"); $("#tab-sim").classList.toggle("is-on",t==="sim");+  $("#body-board").classList.toggle("hide",t!=="board"); $("#body-sim").classList.toggle("hide",t!=="sim"); document.querySelector("aside").classList.toggle("board-mode",t==="board"); localStorage.setItem("smi-tab",t) }+$("#tab-board").onclick=()=>setTab("board"); $("#tab-sim").onclick=()=>setTab("sim"); setTab(localStorage.getItem("smi-tab")||"board");+const setCtl=(id,value,unit)=>post("board/set",{id,value,unit:unit||"units"});+let builtMap=null;+function buildControls(){+  const m=MAP(); if(!m||builtMap===S.board_map_hash) return; builtMap=S.board_map_hash;+  const li=ctlIdx("laser"), L=m.controls[li];+  const lim=Math.min(L.max,L.rated||L.max); $("#cur-slider").max=lim.toFixed(2); $("#cur-input").max=lim.toFixed(2);+  // Every set-point write on this board disarms the head and restarts its+  // soft-start, so the slider sends once, on release.+  $("#cur-slider").oninput=e=>{dragging=e.target; $("#cur-input").value=(+e.target.value).toFixed(1)};+  $("#cur-slider").onchange=e=>{dragging=null; setCtl(L.id,+e.target.value)};+  $("#cur-input").onchange=e=>{ const v=+e.target.value; setCtl(L.id,v).then(j=>{ if(j&&j.status==="ok") toast(L.ramp_per_s?("Laser set-point "+v.toFixed(2)+" mA, ramping at "+L.ramp_per_s+" mA/s"):("Laser set-point "+v.toFixed(2)+" mA; the head's soft-start ramps it")) }) };+  const box=$("#offset-rows"); box.innerHTML="";+  for(const ch of [1,2]){ const i=ctlIdx("offset",ch); if(i<0) continue; const c=m.controls[i];+    const d=document.createElement("div"); d.className="numrow"; d.dataset.tip=`${c.label}: offset DAC, ${c.min} to ${c.max.toFixed(3)} V. Mean of the channel shown on the right (mid-scale is 2048).`;+    d.innerHTML=`<span>Ch ${ch} <b id="off${ch}-mean" style="font:500 10px var(--f-mono);color:var(--text-3);white-space:nowrap"></b></span><input type="range" min="${c.min}" max="${c.max}" step="${c.per_code}" id="off${ch}-slider"><output id="off${ch}-out" style="font:11px var(--f-mono);color:var(--text);text-align:right"></output>`;+    const inp=d.querySelector("input"); inp.oninput=()=>{dragging=inp}; inp.onchange=()=>{dragging=null; setCtl(c.id,+inp.value)};+    d.dataset.ctlOffset=c.id;+    box.appendChild(d) }+  const sw=$("#switch-rows"); sw.innerHTML="";+  for(const c of m.controls){ if(c.kind!=="switch") continue;+    const seen=new Set(), sets=c.settings.filter(x=>{ if(seen.has(x.value)) return false; seen.add(x.value); return true });+    const r=document.createElement("div"); r.className="sw-row"; r.dataset.ctl=c.id;+    r.dataset.tip=c.label+(c.safety?". Board note: "+c.safety:"")+(c.requires_laser_off?" Locked while the laser is on.":"");+    const short=c.role==="bias"?"Mon. bias":`Ch ${c.channel} ${c.stage==="tia"?"TIA":"stage 2"}`;+    r.innerHTML=`<span>${short}</span><div class="seg">${sets.map(x=>`<button data-ctl="${c.id}" data-v="${x.value}" data-tip="${c.label}: ${x.label}">${c.role==="bias"?x.label.split(" ")[0]:x.label}</button>`).join("")}</div>`;+    for(const b of r.querySelectorAll("button")) b.onclick=()=>{ if(r.classList.contains("locked")){toast(c.label+": turn the laser off first (board rule)","error");return}+      setCtl(c.id,+b.dataset.v).then(j=>{ if(j&&j.status==="ok"&&c.stage==="amp") toast(c.label+" "+b.textContent+". Auto-centre to re-centre the channel.") }) };+    sw.appendChild(r) }+}+// interlock + hold-to-enable+let armed=false, holdT=0, holdRaf=0;+function setArmed(a){ armed=a; const il=$("#laser-interlock"); il.classList.toggle("is-on",a); il.setAttribute("aria-checked",a); $("#laser-hold").disabled=!a }+$("#laser-interlock").onclick=()=>setArmed(!armed);+const hb=$("#laser-hold");+function holdStop(){ cancelAnimationFrame(holdRaf); holdT=0; $("#laser-fill").style.width="0" }+hb.addEventListener("pointerdown",e=>{ if(hb.disabled) return; holdT=performance.now(); hb.setPointerCapture(e.pointerId);+  const step=()=>{ const k=(performance.now()-holdT)/1000; $("#laser-fill").style.width=Math.min(100,k*100)+"%";+    if(k>=1){ holdStop(); post("board/laser",{on:true,confirm:"beam-safe"}) } else holdRaf=requestAnimationFrame(step) }; holdRaf=requestAnimationFrame(step) });+hb.addEventListener("pointerup",holdStop); hb.addEventListener("pointercancel",holdStop);+hb.addEventListener("click",e=>{ if(!e.isTrusted) toast("Enabling needs a one-second hold (or `smi-dash laser on --beam-safe`)","error") });+$("#laser-off").onclick=()=>post("board/laser",{on:false});+$("#btn-clear-fault").onclick=()=>post("board/clear_fault",{});+$("#btn-centre").onclick=()=>{ $("#btn-centre").textContent="Centring…"; post("board/auto_centre",{channels:[1,2]}).finally(()=>{$("#btn-centre").textContent="Auto-centre"}) };+$("#btn-tune").onclick=()=>post("board/tune",{}).then(j=>{ if(j&&j.status==="ok") toast("Tuning: stepping the laser current and scoring fringes") });+$("#btn-tune-stop").onclick=()=>post("board/tune/stop",{});+$("#board-toggle").onclick=()=>post("sim",{board:!S.sim.board});+const curHist=[];+function drawCur(lim){+  const {g,w,h}=ctxOf("cv-cur"); if(curHist.length<2) return;+  const t1=curHist[curHist.length-1][0], t0=t1-20000, X=t=>(t-t0)/20000*w, Y=v=>h-2-(v/lim)*(h-4);+  g.strokeStyle=css("--border"); g.beginPath(); g.moveTo(0,Y(0)+.5); g.lineTo(w,Y(0)+.5); g.stroke();+  for(const [k,col,lw] of [[1,css("--text-3"),1.2],[2,css("--accent-bright"),1.5]]){ g.strokeStyle=col; g.lineWidth=lw; g.beginPath(); let st=false;+    for(const p of curHist){ if(p[k]==null){st=false;continue} const x=X(p[0]),y=Y(p[k]); st?g.lineTo(x,y):g.moveTo(x,y); st=true } g.stroke() }+}+function renderBoard(){+  const b=BS(), has=!!b; $("#p-laser").style.opacity=has?1:.5;+  for(const id of ["#p-offsets","#p-gains","#p-tune"]) $(id).style.opacity=has?1:.5;+  if(!has){ $("#laser-pill").textContent="NO BOARD"; $("#laser-pill").className="pill"; $("#laser-why").textContent=S&&S.source.kind==="sim"?"v1.1 model":"no STATE from the Pico"; return }+  buildControls();+  const m=MAP(), li=ctlIdx("laser"), L=m.controls[li], l=b.laser, lim=Math.min(L.max,L.rated||L.max);+  const pill=$("#laser-pill");+  if(b.fault){pill.textContent="FAULT";pill.className="pill fault"} else if(l.on&&l.ramping){pill.textContent="WRITING";pill.className="pill ramp"} else if(l.on){pill.textContent="ON";pill.className="pill on"} else {pill.textContent="OFF";pill.className="pill"}+  $("#laser-why").textContent=l.on?"":l.state.replace(/^off: /,"").replace("off since power-up","since power-up");+  if(!l.on&&armed&&!holdT&&lastOn) setArmed(false); lastOn=l.on;+  $("#laser-hold-t").textContent=l.on?"Laser is on":"Hold to enable"; if(l.on) $("#laser-hold").disabled=true; else $("#laser-hold").disabled=!armed;+  $("#ro-target").textContent=l.target_mA.toFixed(2)+" mA"; $("#ro-setp").textContent=l.setpoint_mA.toFixed(2)+" mA";+  $("#ro-meas").textContent=l.measured_mA==null?"n/a":l.measured_mA.toFixed(2)+" mA";+  if(dragging!==$("#cur-slider")) $("#cur-slider").value=l.target_mA;+  if(document.activeElement!==$("#cur-input")) $("#cur-input").value=l.target_mA.toFixed(1);+  const now=performance.now(); if(!curHist.length||now-curHist[curHist.length-1][0]>100){ curHist.push([now,l.on?l.setpoint_mA:0,l.measured_mA]); while(curHist.length&&curHist[0][0]<now-21000) curHist.shift() }+  drawCur(Math.max(lim,1));+  $("#fault-line").classList.toggle("hide",!b.fault); $("#fault-text").textContent="Fault: "+b.fault_text;+  $("#map-warn").classList.toggle("hide",b.map_match!==false);+  for(const ch of [1,2]){ const i=ctlIdx("offset",ch); if(i<0) continue; const c=b.controls[i], sl=$("#off"+ch+"-slider"); if(!sl) continue;+    if(dragging!==sl) sl.value=c.applied;+    const lockO=!!(m.controls[i].requires_laser_off&&l.on); sl.disabled=lockO; sl.closest(".numrow").style.opacity=lockO?.5:1;+    sl.closest(".numrow").dataset.tip=lockO?"Locked while the laser is on (board rule: no writes while armed). Auto-centre turns it off, writes and turns it back on.":sl.closest(".numrow").dataset.tip; $("#off"+ch+"-out").textContent=c.applied.toFixed(3)+" V"; $("#off"+ch+"-mean").textContent=F.means?"mean "+F.means[ch-1]:"" }+  for(const r of document.querySelectorAll(".sw-row")){ const i=m.controls.findIndex(c=>c.id===r.dataset.ctl); const c=b.controls[i]; const mc=m.controls[i];+    r.classList.toggle("locked",!!(mc.requires_laser_off&&l.on));+    for(const btn of r.querySelectorAll("button")) btn.classList.toggle("is-on",Math.abs(+btn.dataset.v-c.target)<=Math.abs(c.target)*1e-3+1e-9) }+  const t=F.tune||{}, n=(t.steps||[]).length;+  $("#tune-bar").style.width=(t.status==="done"?100:t.status==="running"?Math.min(95,n/19*100):0)+"%";+  if(t.status==="running"&&t.last) $("#tune-msg").textContent=`${t.phase}: ${t.last.set_mA.toFixed(1)} mA, score ${t.last.score}`+(t.last.gain!=null?`, gain ${t.last.gain}`:"");+  else if(t.status==="done") $("#tune-msg").textContent=`Best ${t.best_mA.toFixed(2)} mA, score ${t.final_score.toFixed(1)}`+(t.gain&&t.gain.label?`, ${t.gain.label}`:"")+` (${n} steps, ${t.seconds.toFixed(1)} s)`;+  else if(t.status==="failed") $("#tune-msg").textContent="Stopped: "+t.error;+  $("#tune-t").textContent=t.status==="running"&&t.last?`${t.last.set_mA.toFixed(1)} mA`:t.status==="done"?`${t.best_mA.toFixed(1)} mA`+(t.gain&&t.gain.label?` · ${t.gain.label}`:""):t.status==="failed"?"stopped":"";+  $("#tune-t").dataset.tip=$("#tune-msg").textContent;+  $("#btn-tune").disabled=!l.on||t.status==="running"; $("#btn-tune").style.opacity=$("#btn-tune").disabled?.5:1;+}+let lastOn=false;+ // zoom and pan function wheelOn(id,fn){ document.getElementById(id).parentElement.addEventListener("wheel",e=>{e.preventDefault();fn(e.deltaY>0?1.25:0.8)},{passive:false}) } let pendingWin=null;@@ -540,6 +749,10 @@ function connect(){   es.addEventListener("cursor",e=>{ const d=JSON.parse(e.data); aiCursor(d.selector,d.label||"AI") });   es.addEventListener("reveal",e=>{ const d=JSON.parse(e.data); const el=document.querySelector(d.selector); if(!el) return console.warn("reveal: no "+d.selector); if(el.closest("#modal")) $("#modal").classList.add("show"); el.scrollIntoView({block:"nearest"}); aiCursor(d.selector,d.label||"here") });   es.addEventListener("reload",()=>location.reload());+  es.addEventListener("tab",e=>setTab(JSON.parse(e.data).tab==="sim"?"sim":"board"));+  es.addEventListener("fullscreen",e=>{ const on=JSON.parse(e.data).on;+    const p=on?document.documentElement.requestFullscreen():(document.fullscreenElement?document.exitFullscreen():Promise.resolve());+    p.then(()=>console.log("fullscreen "+(on?"on":"off"))).catch(err=>console.warn("fullscreen refused: "+err.message)) });   es.onerror=()=>{ $("#led").className="led bad"; $("#st-link").textContent="server not reachable, retrying" }; } window.addEventListener("resize",()=>requestAnimationFrame(render));
software/dashboard/build.rsadded+12
@@ -0,0 +1,12 @@+// SPDX-License-Identifier: MIT+// Compiles the firmware's control core into the dashboard so the simulator+// enforces exactly the limits the Pico does.+fn main() {+    let fw = "../firmware/src";+    for f in ["smi_ctl.c", "smi_ctl.h", "smi_controls_gen.h"] {+        println!("cargo:rerun-if-changed={fw}/{f}");+    }+    println!("cargo:rerun-if-changed=csrc/ctl_shim.c");+    println!("cargo:rerun-if-changed=assets/controls.json");+    cc::Build::new().file(format!("{fw}/smi_ctl.c")).file("csrc/ctl_shim.c").include(fw).opt_level(2).warnings(true).compile("smi_ctl");+}
software/dashboard/csrc/ctl_shim.cadded+16
@@ -0,0 +1,16 @@+// SPDX-License-Identifier: MIT+// Lets the dashboard's simulator run the firmware's own control core+// (firmware/src/smi_ctl.c) with the same generated control table.+#include "smi_ctl.h"+#include "smi_controls_gen.h"++size_t smi_shim_size(void) { return sizeof(smi_ctl_t); }+uint32_t smi_shim_hash(void) { return SMI_MAP_HASH; }++void smi_shim_init(smi_ctl_t *c, void *ctx, bool (*dac)(void *, uint8_t, uint8_t, uint16_t),+                   bool (*gp)(void *, uint8_t, bool), void (*wait)(void *, uint32_t),+                   bool (*rd)(void *, uint8_t, uint16_t *), uint8_t reason, uint32_t now_us) {+    smi_hal_t hal = { .ctx = ctx, .dac_write = dac, .wait_us = wait, .dac_read = rd, .gpio_put = gp };+    smi_ctl_init(c, smi_controls, SMI_NUM_CONTROLS, &smi_isense, SMI_MAP_HASH, SMI_MAP_VERSION,+                 SMI_LASER_EN_GPIO, SMI_LASER_EN_ACTIVE_HIGH, &hal, reason, now_us);+}
software/dashboard/src/controls.rsadded+739
@@ -0,0 +1,739 @@+// SPDX-License-Identifier: MIT+//! Board v1.2 controls: the control map (shared with the firmware through+//! controls/gen_controls.py), the command protocol (firmware/src/smi_ctl.h),+//! and the simulated board, which runs the firmware's own control core over FFI+//! and models the laser driver, the current sense, the DAC and the switches.++#![allow(non_snake_case)] // field names follow the board map (mA_per_code, full_scale_V)++use serde::{Deserialize, Serialize};+use serde_json::{json, Value};+use std::os::raw::c_void;++pub const MAP_JSON: &str = include_str!("../assets/controls.json");++#[allow(dead_code)] // protocol constant, used by other hosts+pub const OP_GET_STATE: u8 = 0x01;+pub const OP_LASER_ENABLE: u8 = 0x02;+pub const OP_SET: u8 = 0x03;+pub const OP_READ_ISENSE: u8 = 0x04;+pub const OP_HEARTBEAT: u8 = 0x05;+pub const OP_CLEAR_FAULT: u8 = 0x06;+#[allow(dead_code)]+pub const OP_GET_MAP: u8 = 0x07;+pub const OP_CONFIG: u8 = 0x08;+pub const LASER_KEY: u32 = 0x4C41_5345;++#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct Setting {+    pub label: String,+    pub value: f64,+    pub code: u32,+}++#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct Control {+    pub id: String,+    pub label: String,+    pub kind: String,+    pub unit: String,+    pub role: String,+    #[serde(default)]+    pub channel: Option<u8>,+    #[serde(default)]+    pub stage: Option<String>,+    #[serde(default)]+    pub adc_V_per_unit: Option<f64>,+    /// Offsets: the gain switch whose |K| sets the offset's gain, 1 + |K| (board v1.2).+    #[serde(default)]+    pub gain_link: Option<String>,+    #[serde(default)]+    pub hw_cutoff_mA: Option<f64>,+    #[serde(default)]+    pub requires_laser_off: bool,+    /// Laser on the head DAC: the ramp writes at most this often (each write+    /// drops the enable carrier for its write-and-readback).+    #[serde(default)]+    pub min_write_ms: Option<u32>,+    /// Command-code guard band (1.2.1: DAC code = max(command - guard, 0)) and the top DAC code.+    #[serde(default)]+    pub guard: Option<u32>,+    #[serde(default)]+    pub max_code: Option<u32>,+    #[serde(default)]+    pub safety: Option<String>,+    pub min: f64,+    pub max: f64,+    pub default: f64,+    #[serde(default)]+    pub dac: Option<u8>,+    #[serde(default)]+    pub ch: Option<u8>,+    #[serde(default)]+    pub bits: Option<u32>,+    #[serde(default)]+    pub per_code: Option<f64>,+    #[serde(default)]+    pub at_zero: Option<f64>,+    #[serde(default)]+    pub ramp_per_s: Option<f64>,+    #[serde(default)]+    pub rated: Option<f64>,+    #[serde(default)]+    pub gpios: Vec<u8>,+    #[serde(default)]+    pub settings: Vec<Setting>,+}++impl Control {+    pub fn value_of(&self, code: u32) -> f64 {+        self.at_zero.unwrap_or(0.0) + code as f64 * self.per_code.unwrap_or(1.0)+    }+    pub fn limit(&self) -> f64 {+        self.rated.map(|r| r.min(self.max)).unwrap_or(self.max)+    }+    pub fn setting_label(&self, v: f64) -> Option<String> {+        self.settings.iter().find(|s| (s.value - v).abs() <= s.value.abs() * 1e-3).map(|s| s.label.clone())+    }+}++/// Laser current readback: an ADS1115 on the laser head across the 2 ohm shunt.+#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct Isense {+    pub device: String,+    pub i2c_addr: u8,+    /// ADS1115 input multiplexer code (0 = AIN0 - AIN1 differential).+    pub mux: u8,+    #[serde(default)]+    pub input: String,+    pub full_scale_V: f64,+    pub data_rate_sps: u32,+    pub mA_per_code: f64,+    pub offset_mA: f64,+    pub trip_mA: f64,+    pub rate_hz: u32,+    #[serde(default)]+    pub zero_calibrated: bool,+}++#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct ControlMap {+    pub map_version: String,+    pub controls: Vec<Control>,+    pub isense: Isense,+    pub laser_enable: Value,+    pub i2c: Value,+    pub dacs: Value,+    #[serde(default)]+    pub expander: Option<Value>,+    /// Head DAC readback polling and write gating (board decision 8).+    #[serde(default)]+    pub laser_watch: Option<Value>,+    /// Main-board analog rail on ADC2 (GPIO28).+    #[serde(default)]+    pub rail: Option<Value>,+}++pub fn fnv1a(b: &[u8]) -> u32 {+    let mut h: u32 = 0x811C_9DC5;+    for &x in b {+        h ^= x as u32;+        h = h.wrapping_mul(0x0100_0193);+    }+    h+}++impl ControlMap {+    pub fn load() -> Self {+        serde_json::from_str(MAP_JSON).expect("assets/controls.json is generated by gen_controls.py")+    }+    pub fn hash() -> u32 {+        fnv1a(MAP_JSON.as_bytes())+    }+    pub fn index(&self, id: &str) -> Option<usize> {+        self.controls.iter().position(|c| c.id == id)+    }+    pub fn laser(&self) -> usize {+        self.controls.iter().position(|c| c.role == "laser").unwrap_or(0)+    }+    /// The control with this role on this channel (offset ch1, gain stage amp on ch2, ...).+    pub fn find(&self, role: &str, channel: Option<u8>, stage: Option<&str>) -> Option<usize> {+        self.controls.iter().position(|c| c.role == role && (channel.is_none() || c.channel == channel) && (stage.is_none() || c.stage.as_deref() == stage))+    }+}++// ------------------------------------------------------------------ protocol --++pub fn status_text(s: u8) -> &'static str {+    match s {+        0 => "ok",+        1 => "command too short",+        2 => "unknown command",+        3 => "no such control",+        4 => "value out of range",+        5 => "laser interlock key missing",+        6 => "a fault is latched; clear it first",+        7 => "the DAC did not respond",+        8 => "that unit does not apply to this control",+        9 => "current readback not yet validated at zero; wait a second with the laser off",+        10 => "the board map says change this only with the laser off",+        _ => "unknown status",+    }+}++pub fn off_reason_text(r: u8) -> &'static str {+    match r {+        0 => "on",+        1 => "off since power-up",+        2 => "turned off by the host",+        3 => "off: USB disconnected or port closed",+        4 => "off: watchdog reset",+        5 => "off: host heartbeat timed out",+        6 => "off: overcurrent trip",+        7 => "off: DAC write failed",+        _ => "off",+    }+}++pub fn fault_text(f: u8) -> &'static str {+    match f {+        0 => "none",+        1 => "overcurrent",+        2 => "DAC not responding",+        3 => "current flowing with the laser disabled",+        4 => "laser current readback (head ADS1115) not answering",+        5 => "laser DAC readback mismatch (head DAC121C085)",+        _ => "unknown",+    }+}++fn f32le(b: &[u8]) -> f32 {+    f32::from_le_bytes([b[0], b[1], b[2], b[3]])+}+fn u16le(b: &[u8]) -> u16 {+    u16::from_le_bytes([b[0], b[1]])+}+fn u32le(b: &[u8]) -> u32 {+    u32::from_le_bytes([b[0], b[1], b[2], b[3]])+}++pub fn cmd_laser(on: bool) -> Vec<u8> {+    let mut p = vec![OP_LASER_ENABLE, on as u8];+    p.extend_from_slice(&(if on { LASER_KEY } else { 0 }).to_le_bytes());+    p+}+/// mode 0 = physical units, 1 = DAC counts, 2 = setting index.+pub fn cmd_set(idx: usize, mode: u8, v: f32) -> Vec<u8> {+    let mut p = vec![OP_SET, idx as u8, mode];+    p.extend_from_slice(&v.to_le_bytes());+    p+}+pub fn cmd_config(isense_hz: u8, hb_ms: u16) -> Vec<u8> {+    let mut p = vec![OP_CONFIG, isense_hz];+    p.extend_from_slice(&hb_ms.to_le_bytes());+    p+}++/// Frame a host-to-Pico command (same frame as the stream, type CMD).+pub fn frame_cmd(seq: u16, payload: &[u8]) -> Vec<u8> {+    let mut f = vec![0xA5, 0x5A, 0x10, 0];+    f.extend_from_slice(&(payload.len() as u16).to_le_bytes());+    f.extend_from_slice(&seq.to_le_bytes());+    f.extend_from_slice(payload);+    let crc = crate::proto::crc16(&f[2..]);+    f.extend_from_slice(&crc.to_le_bytes());+    f+}++#[derive(Clone, Debug, Serialize)]+pub struct Ack {+    pub cmd_seq: u16,+    pub op: u8,+    pub status: u8,+    pub data: Vec<u8>,+}++impl Ack {+    pub fn parse(p: &[u8]) -> Option<Ack> {+        if p.len() < 4 {+            return None;+        }+        Some(Ack { cmd_seq: u16le(p), op: p[2], status: p[3], data: p[4..].to_vec() })+    }+    pub fn ok(&self) -> bool {+        self.status == 0+    }+    /// For SMI_E_RANGE: the allowed min and max.+    pub fn range(&self) -> Option<(f32, f32)> {+        (self.status == 4 && self.data.len() >= 8).then(|| (f32le(&self.data), f32le(&self.data[4..])))+    }+}++#[derive(Clone, Debug, Serialize, Default)]+pub struct BoardState {+    pub map_hash: u32,+    pub laser_on: bool,+    pub ramping: bool,+    pub fault: u8,+    pub isense_valid: bool,+    pub track_warn: bool,+    pub boot_reason: u8,+    pub off_reason: u8,+    pub laser_target_ma: f32,+    pub laser_now_ma: f32,+    pub isense_ma: f32,+    pub isense_raw: i16,+    pub isense_age_ms: u16,+    pub hb_timeout_ms: u16,+    pub isense_hz: u8,+    pub codes: Vec<u16>,+    pub targets: Vec<f32>,+    /// Calibrated zero code of the current sense (None until calibrated).+    pub zero_code: Option<f32>,+}++impl BoardState {+    pub fn parse(p: &[u8]) -> Option<BoardState> {+        if p.len() < 28 {+            return None;+        }+        let n = p[27] as usize;+        if p.len() < 28 + 6 * n {+            return None;+        }+        let f = p[4];+        let mut s = BoardState {+            map_hash: u32le(p),+            laser_on: f & 1 != 0,+            ramping: f & 2 != 0,+            fault: p[5],+            isense_valid: f & 8 != 0,+            track_warn: f & 16 != 0,+            boot_reason: p[6],+            off_reason: p[7],+            laser_target_ma: f32le(&p[8..]),+            laser_now_ma: f32le(&p[12..]),+            isense_ma: f32le(&p[16..]),+            isense_raw: u16le(&p[20..]) as i16,+            isense_age_ms: u16le(&p[22..]),+            hb_timeout_ms: u16le(&p[24..]),+            isense_hz: p[26],+            codes: vec![],+            targets: vec![],+            zero_code: None,+        };+        for i in 0..n {+            let o = 28 + 6 * i;+            s.codes.push(u16le(&p[o..]));+            s.targets.push(f32le(&p[o + 2..]));+        }+        let z = 28 + 6 * n;+        if p.len() >= z + 2 {+            let v = u16le(&p[z..]) as i16;+            s.zero_code = (v != i16::MIN).then(|| v as f32 / 16.0);+        }+        Some(s)+    }++    /// A readable view, joined with the map.+    pub fn view(&self, map: &ControlMap) -> Value {+        let ctrls: Vec<Value> = map+            .controls+            .iter()+            .enumerate()+            .map(|(i, c)| {+                let code = self.codes.get(i).copied().unwrap_or(0) as u32;+                let target = self.targets.get(i).copied().unwrap_or(0.0) as f64;+                let applied = if c.kind == "dac" { if c.role == "laser" { self.laser_now_ma as f64 } else { c.value_of(code) } } else { target };+                json!({"id": c.id, "code": code, "target": target, "applied": applied, "label": c.setting_label(target)})+            })+            .collect();+        json!({+            "map_hash": format!("{:08X}", self.map_hash),+            "map_match": self.map_hash == ControlMap::hash(),+            "laser": {+                "on": self.laser_on, "ramping": self.ramping,+                "target_mA": self.laser_target_ma, "setpoint_mA": self.laser_now_ma,+                "measured_mA": if self.isense_valid { json!(self.isense_ma) } else { Value::Null },+                "isense_code": self.isense_raw, "isense_age_ms": self.isense_age_ms,+                "tracking_warning": self.track_warn,+                "state": off_reason_text(if self.laser_on { 0 } else { self.off_reason }),+            },+            "fault": self.fault, "fault_text": fault_text(self.fault),+            "boot": if self.boot_reason == 4 { "watchdog reset" } else { "power-on" },+            "hb_timeout_ms": self.hb_timeout_ms, "isense_hz": self.isense_hz, "isense_zero_code": self.zero_code,+            "controls": ctrls,+        })+    }+}++// ------------------------------------------------------------- serial link --++/// Commands to a real Pico: the serial thread writes the frames and hands+/// every ACK back to the caller waiting on its sequence number.+#[derive(Default)]+pub struct CmdLink {+    pub tx: std::sync::Mutex<Option<std::sync::mpsc::Sender<Vec<u8>>>>,+    pending: std::sync::Mutex<std::collections::HashMap<u16, std::sync::mpsc::Sender<Vec<u8>>>>,+    seq: std::sync::atomic::AtomicU16,+}++impl CmdLink {+    pub fn next_seq(&self) -> u16 {+        self.seq.fetch_add(1, std::sync::atomic::Ordering::SeqCst)+    }+    /// Called by the serial thread for each ACK frame.+    pub fn deliver(&self, payload: Vec<u8>) {+        if let Some(a) = Ack::parse(&payload) {+            if let Some(tx) = self.pending.lock().unwrap().remove(&a.cmd_seq) {+                let _ = tx.send(payload);+            }+        }+    }+    /// Send one command and wait for its ACK: 400 ms per try, three tries.+    /// Every op is idempotent, so a retry after a lost ACK is safe.+    pub fn call(&self, payload: &[u8]) -> Result<Ack, String> {+        for _ in 0..3 {+            let seq = self.next_seq();+            let (tx, rx) = std::sync::mpsc::channel();+            self.pending.lock().unwrap().insert(seq, tx);+            let sent = match self.tx.lock().unwrap().as_ref() {+                Some(t) => t.send(frame_cmd(seq, payload)).is_ok(),+                None => false,+            };+            if !sent {+                self.pending.lock().unwrap().remove(&seq);+                return Err("the Pico is not connected".into());+            }+            match rx.recv_timeout(std::time::Duration::from_millis(400)) {+                Ok(p) => return Ack::parse(&p).ok_or_else(|| "malformed ACK".to_string()),+                Err(_) => {+                    self.pending.lock().unwrap().remove(&seq);+                }+            }+        }+        Err("the Pico did not answer the command (3 tries)".into())+    }+}++// ----------------------------------------------------------- simulated board --++extern "C" {+    fn smi_shim_size() -> usize;+    fn smi_shim_hash() -> u32;+    fn smi_shim_init(+        c: *mut c_void,+        ctx: *mut c_void,+        dac: extern "C" fn(*mut c_void, u8, u8, u16) -> bool,+        gp: extern "C" fn(*mut c_void, u8, bool) -> bool,+        wait: extern "C" fn(*mut c_void, u32),+        rd: extern "C" fn(*mut c_void, u8, *mut u16) -> bool,+        reason: u8,+        now_us: u32,+    );+    fn smi_ctl_command(c: *mut c_void, p: *const u8, n: usize, seq: u16, now_us: u32, resp: *mut u8) -> usize;+    fn smi_ctl_tick(c: *mut c_void, now_us: u32);+    fn smi_ctl_isense(c: *mut c_void, raw: i32, now_us: u32);+    fn smi_ctl_laser_readback(c: *mut c_void, ok: bool, reg: u16, now_us: u32);+    fn smi_ctl_state(c: *const c_void, now_us: u32, resp: *mut u8) -> usize;+}++/// What the firmware core has written to the (simulated) hardware.+pub struct Pins {+    pub dac: [[u16; 8]; 4],+    /// Pico GPIOs 0..31, then the head's MCP23008 bits at 32..39.+    pub gpio: [bool; 64],+    pub writes: u64,+}++impl Default for Pins {+    fn default() -> Self {+        Self { dac: [[0; 8]; 4], gpio: [false; 64], writes: 0 }+    }+}++extern "C" fn hal_dac(ctx: *mut c_void, dev: u8, ch: u8, code: u16) -> bool {+    // SAFETY: ctx is the Box<Pins> owned by the SimBoard that registered it.+    let p = unsafe { &mut *(ctx as *mut Pins) };+    if dev as usize >= 4 || ch as usize >= 8 {+        return false;+    }+    p.dac[dev as usize][ch as usize] = code;+    p.writes += 1;+    true+}+/// Simulated time does not advance inside a command, so the disarm wait is a no-op.+extern "C" fn hal_wait(_ctx: *mut c_void, _us: u32) {}++/// The simulated head DAC reads back exactly what was written.+extern "C" fn hal_read(ctx: *mut c_void, dev: u8, reg: *mut u16) -> bool {+    // SAFETY: ctx is the Box<Pins> owned by the SimBoard; reg points at a u16 in the core.+    let p = unsafe { &*(ctx as *const Pins) };+    if dev as usize >= 4 {+        return false;+    }+    unsafe { *reg = p.dac[dev as usize][0] & 0x0FFF };+    true+}++extern "C" fn hal_gpio(ctx: *mut c_void, g: u8, v: bool) -> bool {+    // SAFETY: as above.+    let p = unsafe { &mut *(ctx as *mut Pins) };+    if (g as usize) < 64 {+        p.gpio[g as usize] = v;+    }+    true+}++/// The analog state of the simulated board for one chunk of samples, in the+/// board map's terms: each channel's stage output is+///     Vstage = (1 + K) * Voffset - K * Vbuffer,   Vbuffer = Vref + Iphoto * Rf+/// with K the second-stage gain magnitude (5 or 20).+#[derive(Clone, Debug, Serialize)]+pub struct BoardAnalog {+    /// Actual laser current at the start and end of the chunk, mA.+    pub i0_ma: f64,+    pub i1_ma: f64,+    pub rf1: f64,+    pub rf2: f64,+    pub k1: f64,+    pub k2: f64,+    pub off1_v: f64,+    pub off2_v: f64,+    /// Monitor TIA reference (the head's bias selector), V.+    pub bias_v: f64,+}++/// Simulated v1.2 board: the firmware's control core plus the analog parts it drives.+pub struct SimBoard {+    core: Vec<u64>,+    pins: Box<Pins>,+    pub map: ControlMap,+    /// Laser current actually flowing, mA (the driver loop lags the DAC).+    pub i_act: f64,+    next_isense_us: u64,+    next_conv_us: u64,+    was_on: bool,+    soft_start_us: u64,+    next_poll_us: u64,+    /// Readback polls made (simulated head watchdog traffic).+    pub polls: u64,+    ads_code: i32,+    rng: u64,+    /// Driver model: gain error and offset of the current loop.+    gain_err: f64,+    offset_ma: f64,+}++impl SimBoard {+    pub fn new(now_us: u64) -> Self {+        // SAFETY: plain C struct sizes; the buffer is u64-aligned.+        let n = unsafe { smi_shim_size() };+        let mut b = SimBoard { core: vec![0u64; n.div_ceil(8) + 1], pins: Box::new(Pins::default()), map: ControlMap::load(), i_act: 0.0, next_isense_us: 0, next_conv_us: 0, was_on: false, soft_start_us: 0, next_poll_us: 0, polls: 0, ads_code: 0, rng: 0x9E37_79B9_7F4A_7C15, gain_err: 1.012, offset_ma: 0.35 };+        let ctx = &mut *b.pins as *mut Pins as *mut c_void;+        // SAFETY: core is large enough for smi_ctl_t; ctx outlives the core (both owned here).+        unsafe { smi_shim_init(b.core.as_mut_ptr() as *mut c_void, ctx, hal_dac, hal_gpio, hal_wait, hal_read, 1, now_us as u32) };+        b+    }++    pub fn firmware_hash() -> u32 {+        // SAFETY: returns a constant.+        unsafe { smi_shim_hash() }+    }++    pub fn command(&mut self, payload: &[u8], seq: u16, now_us: u64) -> Vec<u8> {+        let mut r = vec![0u8; 256];+        // SAFETY: r has room for the largest ACK (4 + 28 + 6 * 12 bytes).+        let n = unsafe { smi_ctl_command(self.core.as_mut_ptr() as *mut c_void, payload.as_ptr(), payload.len(), seq, now_us as u32, r.as_mut_ptr()) };+        r.truncate(n);+        r+    }++    pub fn state(&self, now_us: u64) -> BoardState {+        let mut r = vec![0u8; 256];+        // SAFETY: as above.+        let n = unsafe { smi_ctl_state(self.core.as_ptr() as *const c_void, now_us as u32, r.as_mut_ptr()) };+        BoardState::parse(&r[..n]).unwrap_or_default()+    }++    fn noise(&mut self) -> f64 {+        // xorshift, two uniforms summed: cheap, roughly normal, sigma 0.41.+        let mut u = || {+            self.rng ^= self.rng << 13;+            self.rng ^= self.rng >> 7;+            self.rng ^= self.rng << 17;+            (self.rng >> 11) as f64 / (1u64 << 53) as f64 - 0.5+        };+        u() + u()+    }++    fn value(&self, i: usize) -> f64 {+        let c = &self.map.controls[i];+        if c.kind == "dac" {+            let d = self.pins.dac[c.dac.unwrap_or(0) as usize][c.ch.unwrap_or(0) as usize];+            c.value_of(d as u32)+        } else {+            let mut code = 0u32;+            for (b, g) in c.gpios.iter().enumerate() {+                if self.pins.gpio[*g as usize] {+                    code |= 1 << b;+                }+            }+            c.settings.iter().find(|s| s.code == code).map(|s| s.value).unwrap_or(c.default)+        }+    }++    fn laser_enabled(&self) -> bool {+        let g = self.map.laser_enable["gpio"].as_u64().unwrap_or(0) as usize;+        let hi = self.map.laser_enable["active_high"].as_bool().unwrap_or(true);+        self.pins.gpio[g] == hi+    }++    /// Advance the board by `dt_us` of simulated time ending at `now_us`: run the+    /// firmware core, move the laser current through the driver's lag, feed the+    /// current sense back, and return the analog state for the samples.+    pub fn advance(&mut self, now_us: u64, dt_us: u64) -> BoardAnalog {+        let core = self.core.as_mut_ptr() as *mut c_void;+        // SAFETY: core initialised in new().+        unsafe { smi_ctl_tick(core, now_us as u32) };+        let li = self.map.laser();+        let cmd_ma = if self.laser_enabled() { (self.value(li) * self.gain_err + self.offset_ma).max(0.0) } else { 0.0 };+        // Head driver: every arm restarts the head's soft-start, modelled as a+        // 25 ms rise; a disarm cuts the current within about half a millisecond;+        // changes while armed follow a 2 ms loop. The head's shunt cutoff caps+        // the current at its nominal 123.9 mA whatever the DAC says.+        let i0 = self.i_act;+        let on = self.laser_enabled();+        if on && !self.was_on {+            self.soft_start_us = 0;+        }+        self.was_on = on;+        self.soft_start_us = self.soft_start_us.saturating_add(dt_us);+        let tau = if !on { 500.0 } else if self.soft_start_us < 150_000 { 25_000.0 } else { 2_000.0 };+        let a = 1.0 - (-(dt_us as f64) / tau).exp();+        let cutoff = self.map.controls[li].hw_cutoff_mA.unwrap_or(151.0);+        self.i_act = (self.i_act + (cmd_ma - self.i_act) * a).min(cutoff);+        // Current sense: the head's ADS1115 converts the shunt voltage at its+        // data rate (the firmware reads the latest conversion at isense_hz).+        // 2 codes rms of noise, a zero code of +6 (offset of the input), signed+        // 16-bit at the map's full scale.+        let s = self.map.isense.clone();+        let conv_us = 1_000_000 / s.data_rate_sps.max(1) as u64;+        if now_us >= self.next_conv_us {+            self.next_conv_us = now_us + conv_us;+            let nz = self.noise();+            self.ads_code = ((self.i_act - s.offset_mA) / s.mA_per_code + 6.0 + 2.0 * nz / 0.41).round().clamp(-32768.0, 32767.0) as i32;+        }+        // Armed: poll the laser DAC's register like the firmware does (every+        // readback_poll_ms), through the same core check. The simulated DAC+        // always reads back what was written.+        let poll_ms = self.map.laser_watch.as_ref().and_then(|w| w["readback_poll_ms"].as_u64()).unwrap_or(0);+        let st0 = self.state(now_us);+        if poll_ms > 0 && st0.laser_on {+            while self.next_poll_us <= now_us {+                self.next_poll_us += poll_ms * 1000;+                let lc = &self.map.controls[li];+                let reg = self.pins.dac[lc.dac.unwrap_or(0) as usize][lc.ch.unwrap_or(0) as usize] & 0x0FFF;+                self.polls += 1;+                // SAFETY: as above.+                unsafe { smi_ctl_laser_readback(core, true, reg, now_us as u32) };+            }+        } else {+            self.next_poll_us = now_us;+        }+        let hz = st0.isense_hz.max(1) as u64;+        if now_us >= self.next_isense_us {+            self.next_isense_us = now_us + 1_000_000 / hz;+            // SAFETY: as above.+            unsafe { smi_ctl_isense(core, self.ads_code, now_us as u32) };+        }+        let get = |role: &str, ch: u8, stage: Option<&str>, dflt: f64| self.map.find(role, Some(ch), stage).map(|i| self.value(i)).unwrap_or(dflt);+        BoardAnalog {+            i0_ma: i0,+            i1_ma: self.i_act,+            rf1: get("gain", 1, Some("tia"), 1000.0),+            rf2: get("gain", 2, Some("tia"), 46800.0),+            k1: get("gain", 1, Some("amp"), -5.0).abs(),+            k2: get("gain", 2, Some("amp"), -5.0).abs(),+            off1_v: get("offset", 1, None, 0.0),+            off2_v: get("offset", 2, None, 0.0),+            bias_v: self.map.find("bias", None, None).map(|i| self.value(i)).unwrap_or(0.252),+        }+    }+}++#[cfg(test)]+mod tests {+    use super::*;++    #[test]+    fn map_hash_matches_firmware_table() {+        assert_eq!(ControlMap::hash(), SimBoard::firmware_hash(), "regenerate with controls/gen_controls.py");+    }++    #[test]+    fn sim_board_runs_the_firmware_core() {+        let mut b = SimBoard::new(0);+        let li = b.map.laser();+        let lim = b.map.controls[li].limit() as f32;+        let st = b.state(0);+        assert!(!st.laser_on && st.off_reason == 1);+        // No key: refused. With key: on.+        let mut p = cmd_laser(true);+        p[2] = 0;+        assert_eq!(Ack::parse(&b.command(&p, 1, 0)).unwrap().status, 5);+        assert_eq!(Ack::parse(&b.command(&cmd_laser(true), 2, 0)).unwrap().status, 9, "refused before the zero check");+        for ms in 1..=1500u64 {+            b.advance(ms * 1000, 1000);+        }+        let t0 = 1_500_000u64;+        b.command(&[OP_HEARTBEAT], 9, t0);+        assert!(b.state(t0).zero_code.is_some_and(|z| (z - 6.0).abs() < 1.5), "zero {:?}", b.state(t0).zero_code);+        assert!(Ack::parse(&b.command(&cmd_laser(true), 2, t0)).unwrap().ok());+        let a = Ack::parse(&b.command(&cmd_set(li, 0, lim + 5.0), 3, t0)).unwrap();+        assert_eq!(a.status, 4);+        assert!((a.range().unwrap().1 - lim).abs() < 1e-3);+        assert!(Ack::parse(&b.command(&cmd_set(li, 0, 100.0), 4, t0)).unwrap().ok());+        // 1 s with heartbeats: a stepped ramp moves at its rate; a gated head DAC+        // (1.2.1) is written in one step and its soft-start does the ramping.+        let rate = match b.map.controls[li].ramp_per_s.unwrap_or(0.0) { r if r > 0.0 => r, _ => f64::INFINITY };+        for ms in 1..=1000u64 {+            b.advance(t0 + ms * 1000, 1000);+            if ms % 500 == 0 {+                b.command(&[OP_HEARTBEAT], 10, t0 + ms * 1000);+            }+        }+        let st = b.state(t0 + 1_000_000);+        assert!((st.laser_now_ma as f64 - rate.min(100.0)).abs() < 0.01, "set-point {}", st.laser_now_ma);+        if b.map.laser_watch.as_ref().and_then(|w| w["readback_poll_ms"].as_u64()).unwrap_or(0) == 2 {+            assert!(b.polls >= 490, "readback polls in 1 s: {}", b.polls);+        }+        // Hold there; the measured current (driver gain error 1.2 %, offset 0.35 mA) follows.+        b.command(&cmd_set(li, 0, st.laser_now_ma), 11, t0 + 1_000_000);+        for ms in 1001..=1400u64 {+            b.advance(t0 + ms * 1000, 1000);+        }+        let st = b.state(t0 + 1_400_000);+        assert!(st.isense_valid);+        assert!((st.isense_ma - st.laser_now_ma).abs() < 2.0, "measured {} vs {}", st.isense_ma, st.laser_now_ma);+        // Heartbeat stops: off after the timeout.+        for ms in 1401..=5000u64 {+            b.advance(t0 + ms * 1000, 1000);+        }+        let st = b.state(t0 + 5_000_000);+        assert!(!st.laser_on && st.off_reason == 5);+        assert!(b.i_act < 1.0);+    }++    #[test]+    fn command_frame_round_trips_through_the_decoder() {+        let f = frame_cmd(77, &cmd_set(2, 1, 1234.0));+        let mut d = crate::proto::Decoder::default();+        let mut out = vec![];+        d.push(&f, &mut out);+        assert_eq!(out.len(), 1);+        let crate::proto::Frame::Cmd { seq, payload } = &out[0] else { panic!() };+        assert_eq!(*seq, 77);+        assert_eq!(payload[0], OP_SET);+    }+}
software/dashboard/src/engine.rs+164−6
@@ -3,6 +3,7 @@ //! the running displacement and the recorder. Sources (simulator or Pico over //! USB serial) feed it chunks; the server reads display snapshots from it. +use crate::controls::{BoardState, CmdLink, ControlMap, SimBoard}; use crate::dsp::{spectrum, DetectParams, Detector, Fringe}; use crate::proto::{Decoder, Frame}; use crate::record::{Format, Meta, RecStatus, Recorder};@@ -96,6 +97,34 @@ pub struct Engine {     rate_t0: Instant,     rate_p0: u64,     pub rec_error: Option<String>,+    /// Board v1.2 controls.+    pub map: ControlMap,+    pub simboard: SimBoard,+    /// Simulated time of the board, us (advances with the simulated samples).+    pub board_us: u64,+    sim_cmd_seq: u16,+    pub cmdlink: Arc<CmdLink>,+    /// Latest STATE frame from a real Pico and when it arrived.+    pub pico_state: Option<(BoardState, Instant)>,+    pub isense_pauses: u32,+    /// Main 5.3 V analog rail from ADC2 (Pico STATUS), volts.+    pub rail_v: Option<f64>,+    /// Progress of the tune-for-fringes routine (see tune.rs).+    pub tune: Value,+}++/// Summary of one channel over a window of recent samples, ADC codes.+#[derive(Clone, Debug, Serialize)]+pub struct ChanStats {+    pub n: usize,+    pub mean: f64,+    /// p99 - p1 of the 16-sample average: the fringe swing.+    pub swing: f64,+    /// Robust rms of raw minus the 16-sample average: the broadband noise.+    pub noise: f64,+    pub clip: f64,+    pub min: u16,+    pub max: u16, }  impl Engine {@@ -130,9 +159,93 @@ impl Engine {             rate_t0: Instant::now(),             rate_p0: 0,             rec_error: None,+            map: ControlMap::load(),+            simboard: SimBoard::new(0),+            board_us: 0,+            sim_cmd_seq: 0,+            cmdlink: Arc::new(CmdLink::default()),+            pico_state: None,+            isense_pauses: 0,+            rail_v: None,+            tune: json!({"status": "idle"}),+        }+    }++    /// Run one command on the simulated board (its firmware core).+    pub fn sim_command(&mut self, payload: &[u8]) -> Vec<u8> {+        self.sim_cmd_seq = self.sim_cmd_seq.wrapping_add(1);+        let now = self.board_us;+        self.simboard.command(payload, self.sim_cmd_seq, now)+    }++    /// The board's control state: the simulated board, or the Pico's last+    /// STATE frame (None if none arrived in the last 2 s).+    pub fn board_state(&self) -> Option<BoardState> {+        match &self.source {+            SourceKind::Sim if self.sim_p.board => Some(self.simboard.state(self.board_us)),+            SourceKind::Sim => None,+            SourceKind::Serial { .. } => self.pico_state.as_ref().filter(|(_, t)| t.elapsed() < Duration::from_secs(2)).map(|(s, _)| s.clone()),         }     } +    pub fn board_view(&self) -> Value {+        match self.board_state() {+            Some(st) => {+                let mut v = st.view(&self.map);+                v["source"] = json!(if matches!(self.source, SourceKind::Sim) { "simulated board" } else { "pico" });+                v+            }+            None => json!(null),+        }+    }++    /// Statistics of channel `ch` (1 or 2) over the last `n` pairs.+    pub fn chan_stats(&self, ch: u8, n: usize) -> ChanStats {+        let n = n.min(self.head as usize).min(RING - 1000).max(1);+        let buf = if ch == 2 { &self.ch2 } else { &self.ch1 };+        let start = self.head - n as u64;+        let raw: Vec<u16> = (start..self.head).map(|p| buf[(p & MASK) as usize]).collect();+        let mut sum = 0.0;+        let mut clip = 0usize;+        let (mut mn, mut mx) = (u16::MAX, 0u16);+        for &v in &raw {+            sum += v as f64;+            if v <= 1 || v >= 4094 {+                clip += 1;+            }+            mn = mn.min(v);+            mx = mx.max(v);+        }+        let mean = sum / raw.len() as f64;+        let k = 16usize;+        let mut avg = Vec::with_capacity(raw.len());+        let mut acc = 0.0;+        let mut res = Vec::with_capacity(raw.len());+        for (i, &v) in raw.iter().enumerate() {+            acc += v as f64;+            if i >= k {+                acc -= raw[i - k] as f64;+            }+            if i + 1 >= k {+                let a = acc / k as f64;+                avg.push(a);+                res.push((raw[i + 1 - k / 2] as f64 - a).abs());+            }+        }+        // Median absolute residual x 1.4826 = rms for Gaussian noise, and the+        // sawtooth's sparse sharp edges do not move a median.+        let noise = if res.is_empty() {+            0.0+        } else {+            let m = res.len() / 2;+            res.select_nth_unstable_by(m, |a, b| a.partial_cmp(b).unwrap());+            res[m] * 1.4826+        };+        avg.sort_by(|a, b| a.partial_cmp(b).unwrap());+        let swing = if avg.len() > 10 { avg[avg.len() * 99 / 100] - avg[avg.len() / 100] } else { 0.0 };+        ChanStats { n: raw.len(), mean, swing, noise, clip: clip as f64 / raw.len() as f64, min: mn, max: mx }+    }+     /// Forget all buffered data (used when the source changes).     pub fn reset_stream(&mut self) {         self.head = 0;@@ -414,6 +527,7 @@ impl Engine {                 });             }         }+        let (s1, s2) = (self.chan_stats(1, 12_500), self.chan_stats(2, 12_500));         json!({             "head": self.head,             "start": start,@@ -432,6 +546,14 @@ impl Engine {             "last_rec": self.last_rec.as_ref().map(|r| serde_json::to_value(r).unwrap()),             "rec_error": self.rec_error,             "sync_level": self.sync_level,+            "board": self.board_view(),+            "means": [s1.mean.round(), s2.mean.round()],+            "swing": [s1.swing.round(), s2.swing.round()],+            "min_pp_codes": self.det.p.min_pp_codes,+            "tune": self.tune,+            "isense_pauses": self.isense_pauses,+            // The simulated board's rail is ideal; a Pico reports the measured one.+            "rail_v": match self.source { SourceKind::Sim => if self.sim_p.board { json!(5.3) } else { Value::Null }, _ => json!(self.rail_v) },         })     } }@@ -467,7 +589,8 @@ pub fn run_acquisition(engine: Arc<Mutex<Engine>>) {                         stop.store(true, std::sync::atomic::Ordering::SeqCst);                     }                     if let SourceKind::Serial { port } = &kind {-                        serial = Some(spawn_serial(port.clone()));+                        let link = engine.lock().unwrap().cmdlink.clone();+                        serial = Some(spawn_serial(port.clone(), link));                     }                 }                 match kind {@@ -486,7 +609,15 @@ pub fn run_acquisition(engine: Arc<Mutex<Engine>>) {                             continue;                         }                         let n = ((due - sim_pairs) as usize).min(2_500);-                        let ch = sim.generate(n);+                        // The simulated board advances on the samples' clock (4 us per pair).+                        let analog = {+                            let mut e = engine.lock().unwrap();+                            let dt = n as u64 * 4;+                            e.board_us += dt;+                            let now = e.board_us;+                            if e.sim_p.board { Some(e.simboard.advance(now, dt)) } else { None }+                        };+                        let ch = sim.generate_with(n, analog.as_ref());                         let base = sim.tick / 2 - n as u64;                         let mut e = engine.lock().unwrap();                         let first = e.head;@@ -517,11 +648,19 @@ pub fn run_acquisition(engine: Arc<Mutex<Engine>>) {                                             e.ingest(first_pair, &ch1, &ch2, None, &sync);                                         }                                         Frame::Sync { pair, level, .. } => pending_sync.push((pair, level)),-                                        Frame::Status { dropped_bufs, sync_lost, .. } => {+                                        Frame::Status { dropped_bufs, sync_lost, isense_pauses, rail_mv, .. } => {+                                            e.rail_v = rail_mv.map(|m| m as f64 / 1000.0);                                             e.link.dropped_bufs = dropped_bufs;                                             e.link.sync_lost = sync_lost;+                                            e.isense_pauses = isense_pauses.unwrap_or(0);                                         }                                         Frame::Info { text, .. } => e.link.info = text,+                                        Frame::State { payload, .. } => {+                                            if let Some(st) = BoardState::parse(&payload) {+                                                e.pico_state = Some((st, Instant::now()));+                                            }+                                        }+                                        Frame::Ack { .. } | Frame::Cmd { .. } => {}                                     }                                 }                                 if !pending_sync.is_empty() {@@ -548,14 +687,14 @@ pub enum SerialMsg {     Error(String), } -fn spawn_serial(port: String) -> (String, mpsc::Receiver<SerialMsg>, Arc<std::sync::atomic::AtomicBool>) {+fn spawn_serial(port: String, link: Arc<CmdLink>) -> (String, mpsc::Receiver<SerialMsg>, Arc<std::sync::atomic::AtomicBool>) {     let (tx, rx) = mpsc::channel();     let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));     let stop2 = stop.clone();     let p2 = port.clone();     std::thread::spawn(move || {         while !stop2.load(std::sync::atomic::Ordering::SeqCst) {-            let opened = serialport::new(&p2, 115_200).timeout(Duration::from_millis(200)).open();+            let opened = serialport::new(&p2, 115_200).timeout(Duration::from_millis(10)).open();             let mut sp = match opened {                 Ok(s) => s,                 Err(e) => {@@ -567,20 +706,39 @@ fn spawn_serial(port: String) -> (String, mpsc::Receiver<SerialMsg>, Arc<std::sy             // DTR starts the stream on the Pico.             let _ = sp.write_data_terminal_ready(true);             let _ = sp.write_all(b"start\n");+            let (ctx, crx) = mpsc::channel::<Vec<u8>>();+            *link.tx.lock().unwrap() = Some(ctx);             let mut dec = Decoder::default();             let mut buf = vec![0u8; 65536];             let mut frames = vec![];             let mut last_send = Instant::now();             loop {                 if stop2.load(std::sync::atomic::Ordering::SeqCst) {+                    *link.tx.lock().unwrap() = None;                     let _ = sp.write_data_terminal_ready(false);                     return;                 }+                while let Ok(f) = crx.try_recv() {+                    if let Err(e) = sp.write_all(&f) {+                        let _ = tx.send(SerialMsg::Error(format!("write error on {p2}: {e}")));+                    }+                }                 match sp.read(&mut buf) {                     Ok(0) => {}-                    Ok(n) => dec.push(&buf[..n], &mut frames),+                    Ok(n) => {+                        dec.push(&buf[..n], &mut frames);+                        // ACKs go straight to whoever is waiting for them.+                        frames.retain_mut(|f| match f {+                            Frame::Ack { payload, .. } => {+                                link.deliver(std::mem::take(payload));+                                false+                            }+                            _ => true,+                        });+                    }                     Err(e) if e.kind() == std::io::ErrorKind::TimedOut => {}                     Err(e) => {+                        *link.tx.lock().unwrap() = None;                         let _ = tx.send(SerialMsg::Error(format!("read error on {p2}: {e}")));                         break;                     }
software/dashboard/src/eval.rs+153
@@ -132,3 +132,156 @@ pub fn markdown(rows: &[EvalRow]) -> String {     }     s }++// ------------------------------------------------------------ board v1.2 --++/// One steady-state case through the simulated v1.2 board: laser at `i_ma`,+/// channel 1 second stage at `gain`, both offsets centred the way+/// `smi-dash offset auto` does it, then counting error against truth.+#[derive(Serialize, Clone)]+pub struct BoardRow {+    pub current_ma: f64,+    pub gain: f64,+    pub speed_um_s: f64,+    pub swing_codes: f64,+    pub noise_codes: f64,+    pub score: f64,+    pub true_fringes: u64,+    pub detected: u64,+    pub final_err_nm: f64,+    pub rms_err_nm: f64,+}++pub fn board_case(i_ma: f64, gain: f64, speed: f64, seconds: f64) -> BoardRow {+    use crate::controls::{cmd_laser, cmd_set, SimBoard, OP_HEARTBEAT};+    let p = SimParams { profile: Profile::Constant, speed_um_s: speed, range_um: 400.0, board: true, ..SimParams::default() };+    let half = p.wavelength_nm / 2.0;+    let mut sim = Simulator::new(p);+    let mut b = SimBoard::new(0);+    let map = b.map.clone();+    let li = map.laser();+    let gi = map.find("gain", Some(1), Some("amp")).unwrap();+    let oi = [map.find("offset", Some(1), None).unwrap(), map.find("offset", Some(2), None).unwrap()];+    let gi2 = map.find("gain", Some(2), Some("amp")).unwrap();+    let mut t = 0u64;+    let mut seq = 0u16;+    let mut run = |b: &mut SimBoard, sim: &mut Simulator, pairs: usize, t: &mut u64| {+        let mut out = crate::sim::Chunk::default();+        let mut done = 0;+        while done < pairs {+            let n = 1000.min(pairs - done);+            *t += n as u64 * 4;+            let a = b.advance(*t, n as u64 * 4);+            let c = sim.generate_with(n, Some(&a));+            out.ch1.extend_from_slice(&c.ch1);+            out.ch2.extend_from_slice(&c.ch2);+            out.truth_nm.extend_from_slice(&c.truth_nm);+            done += n;+            seq = seq.wrapping_add(1);+            b.command(&[OP_HEARTBEAT], seq, *t);+        }+        out+    };+    run(&mut b, &mut sim, 375_000, &mut t); // 1.5 s: current-readback zero check+    // Board rule: selectors and offsets are written with the laser off.+    b.command(&cmd_set(gi, 0, gain as f32), 2, t);+    b.command(&cmd_laser(true), 1, t);+    let ack = crate::controls::Ack::parse(&b.command(&cmd_set(li, 0, i_ma as f32), 3, t)).unwrap();+    assert!(ack.ok(), "the firmware refused {i_ma} mA (status {})", ack.status);+    while b.state(t).ramping {+        run(&mut b, &mut sim, 25_000, &mut t);+    }+    run(&mut b, &mut sim, 50_000, &mut t);+    // Centre both channels: Vstage = (1 + K) Voffset - K Vbuffer. Measure with+    // the laser on, then (board rule) turn it off to write the offsets, back on+    // at the same set-point, and let the head's soft-start settle.+    let lsb = 3.3 / 4096.0;+    for _ in 0..5 {+        let c = run(&mut b, &mut sim, 5_000, &mut t);+        let st = b.state(t);+        b.command(&cmd_laser(false), 9, t);+        for (k, ch) in [&c.ch1, &c.ch2].into_iter().enumerate() {+            let mean = ch.iter().map(|&v| v as f64).sum::<f64>() / ch.len() as f64;+            let kk = 1.0 + st.targets[if k == 0 { gi } else { gi2 }].abs() as f64;+            let cur = st.targets[oi[k]] as f64;+            let want = (cur - (mean - 2048.0) * lsb / kk).clamp(0.0, map.controls[oi[k]].max);+            let ack = crate::controls::Ack::parse(&b.command(&cmd_set(oi[k], 0, want as f32), 10, t)).unwrap();+            assert!(ack.ok(), "offset write refused (status {})", ack.status);+        }+        b.command(&cmd_laser(true), 11, t);+        run(&mut b, &mut sim, 75_000, &mut t); // 0.3 s: write, soft-start, settle+    }+    run(&mut b, &mut sim, 25_000, &mut t);+    let mut det = Detector::new(DetectParams::default(), FS);+    let c = run(&mut b, &mut sim, (seconds * FS) as usize, &mut t);+    let t0 = c.truth_nm[0];+    let (mut se, mut ns, mut events) = (0.0, 0u64, 0u64);+    for (i, &v) in c.ch1.iter().enumerate() {+        if det.push(v, i as u64).is_some() {+            events += 1;+        }+        if i % 250 == 0 && i > 2500 {+            let e = det.displacement_nm() - (c.truth_nm[i] - t0);+            se += e * e;+            ns += 1;+        }+    }+    let mut true_fr = 0u64;+    for w in c.truth_nm.windows(2) {+        true_fr += (((w[1] - t0) / half).floor() as i64 - ((w[0] - t0) / half).floor() as i64).unsigned_abs();+    }+    // Swing and noise as the tuner measures them (last 0.4 s).+    let tail: Vec<u16> = c.ch1[c.ch1.len().saturating_sub(100_000)..].to_vec();+    let k = 16;+    let mut avg = vec![];+    let mut res = vec![];+    for i in k..tail.len() {+        let a = tail[i - k..i].iter().map(|&v| v as f64).sum::<f64>() / k as f64;+        avg.push(a);+        res.push((tail[i - k / 2] as f64 - a).abs());+    }+    avg.sort_by(|a, b| a.partial_cmp(b).unwrap());+    res.sort_by(|a, b| a.partial_cmp(b).unwrap());+    let swing = avg[avg.len() * 99 / 100] - avg[avg.len() / 100];+    let noise = res[res.len() / 2] * 1.4826;+    BoardRow {+        current_ma: i_ma,+        gain,+        speed_um_s: speed,+        swing_codes: swing,+        noise_codes: noise,+        score: swing / noise.max(0.5),+        true_fringes: true_fr,+        detected: events,+        final_err_nm: det.displacement_nm() - (c.truth_nm.last().unwrap() - t0),+        rms_err_nm: if ns > 0 { (se / ns as f64).sqrt() } else { 0.0 },+    }+}++/// Laser current x channel 1 second-stage gain, 400 um/s, 2 s each, in parallel.+/// A set-point the firmware refuses would leave the laser at 0, so the case+/// panics rather than report a meaningless row.+pub fn board_suite() -> Vec<BoardRow> {+    let mut hs = vec![];+    // Currents across the map's range, from just above threshold to the limit.+    let map = crate::controls::ControlMap::load();+    let lim = map.controls[map.laser()].limit();+    let currents = [65.0, 80.0, 95.0, (lim - 5.0).floor(), (lim * 10.0).floor() / 10.0];+    for &i in &currents {+        for &g in &[-5.0, -20.0] {+            hs.push(std::thread::spawn(move || board_case(i, g, 400.0, 2.0)));+        }+    }+    hs.into_iter().map(|h| h.join().unwrap()).collect()+}++pub fn board_markdown(rows: &[BoardRow]) -> String {+    let mut s = String::from("| Laser current | Stage 2 gain | Fringe swing | Noise | Score | True fringes | Detected | Final error | RMS error |\n|---|---|---|---|---|---|---|---|---|\n");+    for r in rows {+        s += &format!(+            "| {:.0} mA | {} V/V | {:.0} codes | {:.2} codes | {:.0} | {} | {} | {:.0} nm | {:.0} nm |\n",+            r.current_ma, r.gain, r.swing_codes, r.noise_codes, r.score, r.true_fringes, r.detected, r.final_err_nm, r.rms_err_nm+        );+    }+    s+}
software/dashboard/src/main.rs+309−5
@@ -5,7 +5,9 @@ //! `{status, data, hints}`. The CLI talks to the running server over the same //! HTTP endpoints the page uses, so anything the page can do, a command can do. +mod controls; mod dsp;+mod tune; mod engine; mod eval; mod proto;@@ -110,6 +112,89 @@ enum Cmd {         multimode: Option<String>,         #[arg(long = "wavelength-nm")]         wavelength_nm: Option<f64>,+        /// on | off: model board v1.2 (laser current, gains, offsets, bias from the Controls).+        #[arg(long)]+        board: Option<String>,+    },+    /// Laser (board v1.2): laser on --beam-safe | off | current <mA> [--wait] | read.+    ///+    /// Turning it on needs --beam-safe (the interlock: beam enclosed or eyewear on).+    /// The firmware writes each set-point to the laser head's DAC with the enable+    /// dropped, reads it back, re-arms (the head's soft-start ramps the current),+    /// limits set-point writes to four a second, refuses+    /// anything above the rated current, and turns the laser off if the dashboard+    /// stops sending heartbeats.+    Laser {+        action: String,+        value: Option<f64>,+        #[arg(long = "beam-safe")]+        beam_safe: bool,+        /// With `current`: wait until the set-point is written and the measured current has arrived.+        #[arg(long)]+        wait: bool,+    },+    /// Offsets: offset ch1|ch2 <V> [--counts] | offset auto [ch1|ch2|both].+    ///+    /// auto servoes each channel's mean to mid-scale (2048) with its offset DAC.+    Offset {+        target: String,+        #[arg(allow_hyphen_values = true)]+        value: Option<String>,+        /// The value is DAC counts instead of volts.+        #[arg(long)]+        counts: bool,+    },+    /// Gain switches: gain ch1-tia|ch1-amp|ch2-tia|ch2-amp|<id> <value or label>, e.g. `gain ch1-amp -20`.+    Gain {+        stage: String,+        #[arg(allow_hyphen_values = true)]+        value: String,+    },+    /// Monitor photodiode bias: bias low|mid|high or a value in volts (laser off).+    Bias { value: String },+    /// Any control by id: ctl <id> <value> [--counts | --index].+    Ctl {+        id: String,+        #[arg(allow_hyphen_values = true)]+        value: String,+        #[arg(long)]+        counts: bool,+        #[arg(long)]+        index: bool,+    },+    /// Board state and map: board [state | map | clear-fault | config --isense-hz N --hb-timeout-ms N].+    Board {+        action: Option<String>,+        #[arg(long = "isense-hz")]+        isense_hz: Option<u64>,+        #[arg(long = "hb-timeout-ms")]+        hb_timeout_ms: Option<u64>,+    },+    /// Tune for fringes: step the laser current, re-centre, score fringe contrast, try the second-stage gains.+    ///+    /// Needs the laser on; it never turns it on itself. On board 1.2.1 the head+    /// DAC cannot be dithered, so move the target while tuning; changing an+    /// offset or gain briefly turns the laser off and back on at the same+    /// set-point (board rule: no writes while armed). Returns every step's score.+    Tune {+        #[arg(long, default_value_t = 1)]+        channel: u8,+        #[arg(long = "min-ma")]+        min_ma: Option<f64>,+        #[arg(long = "max-ma")]+        max_ma: Option<f64>,+        #[arg(long, default_value_t = 8)]+        steps: usize,+        /// Leave the second-stage gain as it is.+        #[arg(long = "no-gains")]+        no_gains: bool,+        /// Return at once instead of waiting for the result.+        #[arg(long = "no-wait")]+        no_wait: bool,+        #[arg(long)]+        status: bool,+        #[arg(long)]+        stop: bool,     },     /// Fringe detector parameters.     Detect {@@ -149,7 +234,8 @@ enum Cmd {         #[arg(long)]         dir: Option<String>,     },-    /// Drive the open page: ui toast TEXT | ui click SEL | ui reveal SEL | ui cursor SEL | ui reload.+    /// Drive the open page: ui toast TEXT | ui click SEL | ui reveal SEL | ui cursor SEL | ui reload |+    /// ui fullscreen on|off (Hydrogen shows it as a 90% dialog) | ui tab board|sim.     ///     /// Selectors: #btn-pause #btn-zero #btn-record #btn-settings #src-sim #src-serial     /// [data-profile=constant|sine|step|hand|hold] #mm-toggle #c-slider #speed-slider@@ -171,6 +257,9 @@ enum Cmd {         /// Run the standard suite used for the published error table.         #[arg(long)]         suite: bool,+        /// Board v1.2 suite: laser current x stage-2 gain through the simulated board.+        #[arg(long)]+        board: bool,         #[arg(long, default_value = "constant")]         profile: String,         #[arg(long, default_value_t = 2.0)]@@ -247,7 +336,9 @@ fn find_port(cli: &Cli, out: &Out) -> u16 { fn call(out: &Out, port: u16, method: &str, path: &str, body: Option<Value>) -> Value {     let url = format!("http://127.0.0.1:{port}{path}");     let ua = format!("smi-dash-cli/{}", env!("CARGO_PKG_VERSION"));-    let req = ureq::request(method, &url).set("User-Agent", &ua).timeout(std::time::Duration::from_secs(10));+    // Auto-centre with the laser on cycles it for every offset write, so allow it time.+    let secs = if path.starts_with("/board/auto_centre") { 120 } else { 10 };+    let req = ureq::request(method, &url).set("User-Agent", &ua).timeout(std::time::Duration::from_secs(secs));     let res = match body {         Some(b) => req.send_json(b),         None => req.call(),@@ -362,7 +453,8 @@ fn main() {             let v = call(&out, port, "POST", "/source", Some(b));             out.ok(&format!("source is now {}", kind), v["data"].clone(), &hints_of(&v));         }-        Cmd::Sim { profile, speed_um_s, range_um, amp_um, freq_hz, step_um, jitter_um, c, alpha, m, noise, multimode, wavelength_nm } => {+        Cmd::Laser { .. } | Cmd::Offset { .. } | Cmd::Gain { .. } | Cmd::Bias { .. } | Cmd::Ctl { .. } | Cmd::Board { .. } | Cmd::Tune { .. } => board_cli(&cli, &out),+        Cmd::Sim { profile, speed_um_s, range_um, amp_um, freq_hz, step_um, jitter_um, c, alpha, m, noise, multimode, wavelength_nm, board } => {             let port = find_port(&cli, &out);             let mut b = json!({});             if let Some(p) = profile {@@ -379,6 +471,9 @@ fn main() {             if let Some(mm) = multimode {                 b["multimode"] = json!(onoff(mm, &out));             }+            if let Some(bd) = board {+                b["board"] = json!(onoff(bd, &out));+            }             let v = call(&out, port, "POST", "/sim", Some(b));             let d = &v["data"];             out.ok(&format!("simulator: profile {}, C {}, multimode {}", d["profile"].as_str().unwrap_or("?"), d["c"], d["multimode"]), d.clone(), &[]);@@ -445,6 +540,8 @@ fn main() {             let body = match verb.as_str() {                 "toast" => json!({"text": arg.clone().unwrap_or_default(), "kind": kind}),                 "reload" => json!({}),+                "fullscreen" => json!({"on": onoff(arg.as_deref().unwrap_or("on"), &out)}),+                "tab" => json!({"tab": arg.clone().unwrap_or("board".into())}),                 _ => match arg {                     Some(sel) => json!({"selector": sel}),                     None => out.err(&format!("ui {verb} needs a selector"), &[format!("e.g. `smi-dash ui {verb} '#btn-zero'`")]),@@ -480,8 +577,12 @@ fn main() {             let lines: Vec<String> = v["data"].as_array().map(|a| a.iter().map(|e| format!("[{}] {}", e["level"].as_str().unwrap_or(""), e["text"].as_str().unwrap_or(""))).collect()).unwrap_or_default();             out.ok(&format!("{} console lines\n{}", lines.len(), lines.join("\n")), v["data"].clone(), &[]);         }-        Cmd::Eval { suite, profile, seconds, c, speed_um_s, multimode, noise, lp_hz } => {-            if *suite {+        Cmd::Eval { suite, board, profile, seconds, c, speed_um_s, multimode, noise, lp_hz } => {+            if *board {+                let t = Instant::now();+                let rows = eval::board_suite();+                out.ok(&format!("board suite of {} cases in {:.1} s\n{}", rows.len(), t.elapsed().as_secs_f64(), eval::board_markdown(&rows)), json!(rows), &[]);+            } else if *suite {                 let t = Instant::now();                 let rows = eval::suite();                 let table = eval::markdown(&rows);@@ -634,3 +735,206 @@ fn show(cli: &Cli, out: &Out, surface: Option<String>) {         s => out.err(&format!("unknown surface '{s}'"), &["Valid surfaces: wv, pup".into()]),     } }++fn laser_line(st: &Value) -> String {+    if st.is_null() {+        return "no board state".into();+    }+    let l = &st["laser"];+    let meas = l["measured_mA"].as_f64().map(|m| format!("{m:.2} mA")).unwrap_or("n/a".into());+    let mut m = if l["on"].as_bool() == Some(true) {+        format!("laser ON, set-point {:.2} mA (target {:.2}{}), measured {meas}", l["setpoint_mA"].as_f64().unwrap_or(0.0), l["target_mA"].as_f64().unwrap_or(0.0), if l["ramping"].as_bool() == Some(true) { ", writing" } else { "" })+    } else {+        format!("laser {}, measured {meas}", l["state"].as_str().unwrap_or("off"))+    };+    if st["fault"].as_u64().unwrap_or(0) != 0 {+        m += &format!("; FAULT: {}", st["fault_text"].as_str().unwrap_or(""));+    }+    if st["map_match"] == json!(false) {+        m += "; WARNING: firmware control map differs from the dashboard's";+    }+    m+}++fn controls_lines(st: &Value, map: &Value) -> String {+    let mut lines = vec![];+    if let (Some(cs), Some(ms)) = (st["controls"].as_array(), map["controls"].as_array()) {+        for (c, m) in cs.iter().zip(ms) {+            let v = c["applied"].as_f64().unwrap_or(0.0);+            let lab = c["label"].as_str().map(|l| format!(" ({l})")).unwrap_or_default();+            lines.push(format!("  {:<26} {:>10.4} {}{}  code {}", m["id"].as_str().unwrap_or(""), v, m["unit"].as_str().unwrap_or(""), lab, c["code"]));+        }+    }+    lines.join("\n")+}++fn board_cli(cli: &Cli, out: &Out) {+    let port = find_port(cli, out);+    let set = |id: &str, value: Value, unit: &str| -> Value { call(out, port, "POST", "/board/set", Some(json!({"id": id, "value": value, "unit": unit}))) };+    let num_or_str = |v: &str| -> Value { v.parse::<f64>().map(|x| json!(x)).unwrap_or(json!(v)) };+    let state = || call(out, port, "GET", "/board", None)["data"].clone();+    match &cli.cmd {+        Cmd::Laser { action, value, beam_safe, wait } => match action.as_str() {+            "on" => {+                let mut b = json!({"on": true});+                if *beam_safe {+                    b["confirm"] = json!("beam-safe");+                }+                let v = call(out, port, "POST", "/board/laser", Some(b));+                out.ok(&laser_line(&v["data"]), v["data"].clone(), &hints_of(&v));+            }+            "off" => {+                let v = call(out, port, "POST", "/board/laser", Some(json!({"on": false})));+                out.ok(&laser_line(&v["data"]), v["data"].clone(), &[]);+            }+            "current" => {+                let Some(ma) = value else { out.err("laser current needs a value in mA", &["e.g. `smi-dash laser current 95 --wait`".into()]) };+                let v = set("laser", json!(ma), "units");+                let mut h = hints_of(&v);+                if *wait {+                    let t = Instant::now();+                    loop {+                        let d = state();+                        let l = &d["state"]["laser"];+                        let sp = l["setpoint_mA"].as_f64().unwrap_or(0.0);+                        let arrived = l["measured_mA"].as_f64().is_some_and(|m| (m - sp).abs() < (0.03 * sp).max(1.0));+                        if l["on"].as_bool() != Some(true) || (l["ramping"].as_bool() != Some(true) && (arrived || t.elapsed().as_secs() > 3)) {+                            h.clear();+                            break;+                        }+                        if t.elapsed().as_secs() > 30 {+                            out.err("the set-point did not settle within 30 s", &[]);+                        }+                        std::thread::sleep(std::time::Duration::from_millis(100));+                    }+                }+                let d = state();+                if d["state"]["laser"]["on"].as_bool() != Some(true) {+                    h.push("The laser is off: the set-point is stored and applies when it is enabled".into());+                }+                out.ok(&laser_line(&d["state"]), v["data"].clone(), &h);+            }+            "read" => {+                let v = call(out, port, "POST", "/board/read_current", Some(json!({})));+                let d = &v["data"];+                out.ok(&format!("measured {:.2} mA (head ADS1115 code {}, {} ms old), set-point {:.2} mA", d["measured_mA"].as_f64().unwrap_or(f64::NAN), d["ads1115_code"], d["age_ms"], d["setpoint_mA"].as_f64().unwrap_or(0.0)), d.clone(), &[]);+            }+            a => out.err(&format!("unknown laser action '{a}'"), &["Use `smi-dash laser on --beam-safe | off | current <mA> | read`".into()]),+        },+        Cmd::Offset { target, value, counts } => {+            if target == "auto" {+                let chans: Vec<u8> = match value.as_deref() {+                    Some("ch1") | Some("1") => vec![1],+                    Some("ch2") | Some("2") => vec![2],+                    None | Some("both") => vec![1, 2],+                    Some(x) => out.err(&format!("unknown channel '{x}'"), &["Use ch1, ch2 or both".into()]),+                };+                let v = call(out, port, "POST", "/board/auto_centre", Some(json!({"channels": chans})));+                let msg = v["data"].as_array().map(|a| a.iter().map(|r| format!("channel {}: offset {:.4} V, mean {:.0} codes after {} steps", r["channel"], r["offset_V"].as_f64().unwrap_or(0.0), r["mean"].as_f64().unwrap_or(0.0), r["iterations"])).collect::<Vec<_>>().join("; ")).unwrap_or_default();+                out.ok(&msg, v["data"].clone(), &[]);+            } else {+                let id = match target.as_str() {+                    "ch1" | "1" => "ch1-offset",+                    "ch2" | "2" => "ch2-offset",+                    x => x,+                };+                let Some(val) = value else { out.err("offset needs a value", &["e.g. `smi-dash offset ch1 0.52` or `smi-dash offset ch1 650 --counts`".into()]) };+                let v = set(id, num_or_str(val), if *counts { "counts" } else { "units" });+                let d = &v["data"];+                out.ok(&format!("{} = {:.4} V (code {})", d["id"].as_str().unwrap_or(""), d["applied"].as_f64().unwrap_or(0.0), d["code"]), d.clone(), &hints_of(&v));+            }+        }+        Cmd::Gain { stage, value } => {+            let v = set(stage, num_or_str(value), "units");+            let d = &v["data"];+            out.ok(&format!("{} = {} {}{}", d["id"].as_str().unwrap_or(""), d["target"], d["unit"].as_str().unwrap_or(""), d["label"].as_str().map(|l| format!(" ({l})")).unwrap_or_default()), d.clone(), &hints_of(&v));+        }+        Cmd::Bias { value } => {+            let v = set("bias", num_or_str(value), "units");+            let d = &v["data"];+            out.ok(&format!("monitor bias = {} V{}", d["target"], d["label"].as_str().map(|l| format!(" ({l})")).unwrap_or_default()), d.clone(), &hints_of(&v));+        }+        Cmd::Ctl { id, value, counts, index } => {+            let unit = if *counts { "counts" } else if *index { "index" } else { "units" };+            let v = set(id, num_or_str(value), unit);+            let d = &v["data"];+            out.ok(&format!("{} = {} {} (code {})", d["id"].as_str().unwrap_or(""), d["applied"], d["unit"].as_str().unwrap_or(""), d["code"]), d.clone(), &hints_of(&v));+        }+        Cmd::Board { action, isense_hz, hb_timeout_ms } => match action.as_deref().unwrap_or("state") {+            "state" => {+                let v = call(out, port, "GET", "/board", None);+                let d = &v["data"];+                out.ok(&format!("{}\n{}", laser_line(&d["state"]), controls_lines(&d["state"], &d["map"])), d.clone(), &hints_of(&v));+            }+            "map" => {+                let v = call(out, port, "GET", "/board", None);+                let m = &v["data"]["map"];+                let lines: Vec<String> = m["controls"].as_array().map(|a| a.iter().map(|c| {+                    let range = if c["kind"] == "switch" { c["settings"].as_array().map(|s| s.iter().map(|x| format!("{} ({})", x["value"], x["label"].as_str().unwrap_or(""))).collect::<Vec<_>>().join(" | ")).unwrap_or_default() } else { format!("{} to {} {}", c["min"], c["max"], c["unit"].as_str().unwrap_or("")) };+                    format!("  {:<26} {:<7} {}  default {}{}", c["id"].as_str().unwrap_or(""), c["kind"].as_str().unwrap_or(""), range, c["default"], if c["requires_laser_off"] == json!(true) { "  [laser off only]" } else { "" })+                }).collect()).unwrap_or_default();+                out.ok(&format!("control map {} (hash {})\n{}", m["map_version"].as_str().unwrap_or(""), v["data"]["map_hash"].as_str().unwrap_or(""), lines.join("\n")), v["data"].clone(), &[]);+            }+            "clear-fault" => {+                let v = call(out, port, "POST", "/board/clear_fault", Some(json!({})));+                out.ok(&laser_line(&v["data"]), v["data"].clone(), &hints_of(&v));+            }+            "config" => {+                let mut b = json!({});+                if let Some(x) = isense_hz { b["isense_hz"] = json!(x) }+                if let Some(x) = hb_timeout_ms { b["hb_timeout_ms"] = json!(x) }+                let v = call(out, port, "POST", "/board/config", Some(b));+                out.ok(&format!("current sense {} Hz, heartbeat timeout {} ms", v["data"]["isense_hz"], v["data"]["hb_timeout_ms"]), v["data"].clone(), &[]);+            }+            a => out.err(&format!("unknown board action '{a}'"), &["Use `smi-dash board state | map | clear-fault | config`".into()]),+        },+        Cmd::Tune { channel, min_ma, max_ma, steps, no_gains, no_wait, status, stop } => {+            let summary = |t: &Value| -> String {+                let rows: Vec<String> = t["steps"].as_array().map(|a| a.iter().map(|r| format!("  {:<7} {:>7.2} mA  measured {:>7.2}  score {:>6.1}  swing {:>5}  noise {:>5}  clip {:.3}{}", r["phase"].as_str().unwrap_or(""), r["set_mA"].as_f64().unwrap_or(0.0), r["measured_mA"].as_f64().unwrap_or(f64::NAN), r["score"].as_f64().unwrap_or(0.0), r["swing"], r["noise"], r["clip"].as_f64().unwrap_or(0.0), r["gain"].as_f64().map(|g| format!("  gain {g}")).unwrap_or_default())).collect()).unwrap_or_default();+                let head = match t["status"].as_str() {+                    Some("done") => format!("tuned channel {}: best {:.2} mA, score {:.1}{} in {:.1} s", t["channel"], t["best_mA"].as_f64().unwrap_or(0.0), t["final_score"].as_f64().unwrap_or(0.0), t["gain"]["value"].as_f64().map(|g| format!(", {} = {g}", t["gain"]["id"].as_str().unwrap_or(""))).unwrap_or_default(), t["seconds"].as_f64().unwrap_or(0.0)),+                    Some("failed") => format!("tuning failed: {}", t["error"].as_str().unwrap_or("")),+                    Some(s) => format!("tuning {s}, step {}", t["step"]),+                    None => "no tune yet".into(),+                };+                let note = t["note"].as_str().map(|n| format!("\nNote: {n}")).unwrap_or_default();+                format!("{head}{note}\n{}", rows.join("\n"))+            };+            if *stop {+                let v = call(out, port, "POST", "/board/tune/stop", Some(json!({})));+                out.ok("stop requested", v["data"].clone(), &[]);+                return;+            }+            if *status {+                let v = call(out, port, "GET", "/board/tune", None);+                out.ok(&summary(&v["data"]), v["data"].clone(), &[]);+                return;+            }+            let mut b = json!({"channel": channel, "steps": steps, "gains": !no_gains});+            if let Some(x) = min_ma { b["min_ma"] = json!(x) }+            if let Some(x) = max_ma { b["max_ma"] = json!(x) }+            let v = call(out, port, "POST", "/board/tune", Some(b));+            if *no_wait {+                out.ok("tuning started", v["data"].clone(), &hints_of(&v));+                return;+            }+            let t = Instant::now();+            loop {+                std::thread::sleep(std::time::Duration::from_millis(500));+                let v = call(out, port, "GET", "/board/tune", None);+                let st = v["data"]["status"].as_str().unwrap_or("");+                if st == "done" {+                    out.ok(&summary(&v["data"]), v["data"].clone(), &[]);+                    return;+                }+                if st == "failed" {+                    out.err(&summary(&v["data"]), &hints_of(&json!({"hints": v["data"]["hints"]})));+                }+                if t.elapsed().as_secs() > 180 {+                    out.err("tuning did not finish within 180 s", &["Check `smi-dash tune --status`; stop it with `smi-dash tune --stop`".into()]);+                }+            }+        }+        _ => unreachable!(),+    }+}
software/dashboard/src/proto.rs+15−1
@@ -5,6 +5,9 @@ pub const T_DATA: u8 = 1; pub const T_SYNC: u8 = 2; pub const T_STATUS: u8 = 3; pub const T_INFO: u8 = 4;+pub const T_CMD: u8 = 0x10;+pub const T_ACK: u8 = 0x11;+pub const T_STATE: u8 = 0x12; const HDR: usize = 8; const BLOCK: usize = 64; @@ -23,8 +26,14 @@ pub fn crc16(p: &[u8]) -> u16 { pub enum Frame {     Data { seq: u16, first_pair: u64, t_us: u32, ch1: Vec<u16>, ch2: Vec<u16> },     Sync { seq: u16, pair: u64, t_us: u32, level: u8 },-    Status { seq: u16, pairs: u64, dropped_bufs: u32, sync_lost: u32, total_sps: u32, t_us: u32 },+    Status { seq: u16, pairs: u64, dropped_bufs: u32, sync_lost: u32, total_sps: u32, t_us: u32, isense_pauses: Option<u32>, rail_mv: Option<u16> },     Info { seq: u16, text: String },+    /// Host-to-Pico command (decoded here for tests and replays).+    Cmd { seq: u16, payload: Vec<u8> },+    /// The Pico's answer to one command: controls::Ack::parse(payload).+    Ack { seq: u16, payload: Vec<u8> },+    /// Board control state, four times a second: controls::BoardState::parse(payload).+    State { seq: u16, payload: Vec<u8> }, }  fn u16le(b: &[u8]) -> u16 {@@ -180,7 +189,12 @@ fn parse(ty: u8, seq: u16, p: &[u8]) -> Option<Frame> {             sync_lost: u32le(&p[12..]),             total_sps: u32le(&p[16..]),             t_us: u32le(&p[20..]),+            isense_pauses: (p.len() >= 28).then(|| u32le(&p[24..])),+            rail_mv: (p.len() >= 30).then(|| u16le(&p[28..])),         }),+        T_CMD => Some(Frame::Cmd { seq, payload: p.to_vec() }),+        T_ACK if p.len() >= 4 => Some(Frame::Ack { seq, payload: p.to_vec() }),+        T_STATE if p.len() >= 28 => Some(Frame::State { seq, payload: p.to_vec() }),         T_INFO => Some(Frame::Info { seq, text: String::from_utf8_lossy(p).into_owned() }),         _ => None,     }
software/dashboard/src/server.rs+202−2
@@ -66,6 +66,8 @@ impl App {             "view": e.view,             "settings": *s,             "recording": e.rec.as_ref().map(|r| serde_json::to_value(r.status()).unwrap()),+            "board_map": e.map,+            "board_map_hash": format!("{:08X}", crate::controls::ControlMap::hash()),             "enums": {                 "sim.profile": Profile::ALL,                 "source.kind": ["sim", "serial"],@@ -135,6 +137,18 @@ pub async fn serve(app: Arc<App>, listener: tokio::net::TcpListener) {             let _ = frame_no;         }     });+    // Host heartbeat: the firmware turns the laser off if commands stop for+    // hb_timeout_ms (3 s), so a crashed or closed dashboard cannot leave it on.+    let a4 = app.clone();+    tokio::spawn(async move {+        loop {+            tokio::time::sleep(Duration::from_millis(1000)).await;+            let on = a4.engine.lock().unwrap().board_state().is_some_and(|s| s.laser_on);+            if on {+                let _ = crate::tune::cmd(&a4, vec![crate::controls::OP_HEARTBEAT]).await;+            }+        }+    });     // Idle reaper.     let a3 = app.clone();     tokio::spawn(async move {@@ -172,6 +186,15 @@ pub async fn serve(app: Arc<App>, listener: tokio::net::TcpListener) {         .route("/ui/:verb", post(ui))         .route("/console", get(get_console).post(post_console))         .route("/shutdown", post(shutdown))+        .route("/board", get(board_get))+        .route("/board/laser", post(board_laser))+        .route("/board/set", post(board_set))+        .route("/board/read_current", post(board_read_current))+        .route("/board/auto_centre", post(board_centre))+        .route("/board/tune", get(board_tune_get).post(board_tune))+        .route("/board/tune/stop", post(board_tune_stop))+        .route("/board/clear_fault", post(board_clear_fault))+        .route("/board/config", post(board_config))         .with_state(app);     axum::serve(listener, r).await.unwrap(); }@@ -409,11 +432,11 @@ async fn set_settings(State(a): S, Json(p): Json<Value>) -> Response {  async fn ui(State(a): S, axum::extract::Path(verb): axum::extract::Path<String>, Json(p): Json<Value>) -> Response {     a.touch();-    let valid = ["toast", "click", "reveal", "cursor", "reload"];+    let valid = ["toast", "click", "reveal", "cursor", "reload", "fullscreen", "tab"];     if !valid.contains(&verb.as_str()) {         return refuse(StatusCode::NOT_FOUND, &format!("unknown ui verb '{verb}'"), &[format!("Valid verbs: {}", valid.join(", "))]);     }-    if verb != "toast" && verb != "reload" && p.get("selector").and_then(|v| v.as_str()).is_none() {+    if !["toast", "reload", "fullscreen", "tab"].contains(&verb.as_str()) && p.get("selector").and_then(|v| v.as_str()).is_none() {         return refuse(StatusCode::BAD_REQUEST, "missing selector", &[format!("Send {{\"selector\": \"#btn-zero\"}}; selectors are listed by `smi-dash ui {verb} --help`")]);     }     let n = a.tx.receiver_count();@@ -446,3 +469,180 @@ async fn shutdown(State(a): S) -> Response {     });     ok(json!({"stopping": true}), &[]) }++// ------------------------------------------------------------ board v1.2 --++use crate::controls;+use crate::tune;++fn fail_resp(f: tune::Fail) -> Response {+    refuse(StatusCode::CONFLICT, &f.0, &f.1)+}++fn board_now(a: &Arc<App>) -> Value {+    a.engine.lock().unwrap().board_view()+}++async fn board_get(State(a): S) -> Response {+    a.touch();+    let e = a.engine.lock().unwrap();+    let st = e.board_view();+    let hints: Vec<&str> = if st.is_null() {+        if matches!(e.source, SourceKind::Sim) { vec!["The simulator models the v1.1 board; turn the v1.2 model on with `smi-dash sim --board on`"] } else { vec!["No STATE frames from the Pico: it needs firmware 1.2.0"] }+    } else if st["map_match"] == json!(false) {+        vec!["The firmware's control map differs from this dashboard's: flash the smi_pico.uf2 built from the same map"]+    } else {+        vec![]+    };+    ok(json!({"state": st, "map": e.map, "map_hash": format!("{:08X}", controls::ControlMap::hash()), "sim_firmware_map_hash": format!("{:08X}", controls::SimBoard::firmware_hash()), "tune": e.tune}), &hints)+}++async fn board_laser(State(a): S, Json(p): Json<Value>) -> Response {+    a.touch();+    let Some(on) = p.get("on").and_then(|v| v.as_bool()) else {+        return refuse(StatusCode::BAD_REQUEST, "missing 'on'", &["Send {\"on\": false}, or {\"on\": true, \"confirm\": \"beam-safe\"}".into()]);+    };+    if on && p.get("confirm").and_then(|v| v.as_str()) != Some("beam-safe") {+        return refuse(+            StatusCode::PRECONDITION_REQUIRED,+            "laser interlock: confirm the beam path is safe",+            &["Class 3B: enclose the beam or wear eyewear, then `smi-dash laser on --beam-safe` (the page asks you to tick the interlock box and hold Enable)".into()],+        );+    }+    match tune::laser(&a, on).await {+        Ok(_) => {+            a.broadcast("toast", json!({"text": if on { "Laser enabled: set-point written to the head, read back, then armed" } else { "Laser off" }, "kind": if on { "info" } else { "success" }}));+            ok(board_now(&a), &[if on { "Set the current with `smi-dash laser current <mA> --wait`" } else { "" }])+        }+        Err(f) => fail_resp(f),+    }+}++/// {id, value, unit: "units" | "counts" | "index"}; a switch also takes a setting label.+async fn board_set(State(a): S, Json(p): Json<Value>) -> Response {+    a.touch();+    let map = a.engine.lock().unwrap().map.clone();+    let key = p.get("id").and_then(|v| v.as_str()).unwrap_or("");+    let Some(idx) = tune::resolve(&map, key) else {+        return refuse(StatusCode::BAD_REQUEST, &format!("unknown control '{key}'"), &[format!("Controls: {} (aliases: laser, ch1-offset, ch2-offset, ch1-tia, ch1-amp, ch2-tia, ch2-amp, bias)", map.controls.iter().map(|c| c.id.as_str()).collect::<Vec<_>>().join(", "))]);+    };+    let c = &map.controls[idx];+    let unit = p.get("unit").and_then(|v| v.as_str()).unwrap_or("units");+    let mode = match unit {+        "units" => 0,+        "counts" => 1,+        "index" => 2,+        _ => return refuse(StatusCode::BAD_REQUEST, &format!("unknown unit '{unit}'"), &["Use units, counts or index".into()]),+    };+    let v = match p.get("value") {+        Some(Value::Number(n)) => n.as_f64().unwrap_or(f64::NAN),+        Some(Value::String(t)) => match t.parse::<f64>() {+            Ok(x) => x,+            Err(_) => match c.settings.iter().find(|s| s.label.to_ascii_lowercase().starts_with(&t.to_ascii_lowercase())) {+                Some(s) => s.value,+                None => return refuse(StatusCode::BAD_REQUEST, &format!("'{t}' is not a value of {}", c.id), &[format!("Settings: {}", c.settings.iter().map(|s| format!("{} ({})", s.value, s.label)).collect::<Vec<_>>().join(", "))]),+            },+        },+        _ => return refuse(StatusCode::BAD_REQUEST, "missing 'value'", &[format!("e.g. {{\"id\": \"{}\", \"value\": {}}}", c.id, c.default)]),+    };+    match tune::set(&a, idx, mode, v).await {+        Ok(ack) => {+            let d = &ack.data;+            let code = if d.len() >= 3 { u16::from_le_bytes([d[1], d[2]]) } else { 0 };+            let applied = if d.len() >= 7 { f32::from_le_bytes([d[3], d[4], d[5], d[6]]) } else { f32::NAN };+            let target = if d.len() >= 11 { f32::from_le_bytes([d[7], d[8], d[9], d[10]]) } else { f32::NAN };+            let mut hints = vec![];+            if c.role == "laser" && (applied - target).abs() > 0.01 {+                hints.push(format!("Being written (at most four set-point writes a second); `smi-dash laser current {} --wait` blocks until the measured current arrives", target));+            }+            if c.role == "gain" && c.stage.as_deref() == Some("amp") {+                hints.push("Re-centre the channel after a gain change: `smi-dash offset auto`".to_string());+            }+            let h: Vec<&str> = hints.iter().map(|s| s.as_str()).collect();+            ok(json!({"id": c.id, "code": code, "applied": applied, "target": target, "unit": c.unit, "label": c.setting_label(target as f64)}), &h)+        }+        Err(f) => fail_resp(f),+    }+}++async fn board_read_current(State(a): S) -> Response {+    a.touch();+    match tune::cmd(&a, vec![controls::OP_READ_ISENSE]).await {+        Ok(ack) if ack.data.len() >= 8 => {+            let d = &ack.data;+            let ma = f32::from_le_bytes([d[0], d[1], d[2], d[3]]);+            let st = a.engine.lock().unwrap().board_state();+            ok(json!({"measured_mA": ma, "ads1115_code": i16::from_le_bytes([d[4], d[5]]), "age_ms": u16::from_le_bytes([d[6], d[7]]),+                      "setpoint_mA": st.as_ref().map(|s| s.laser_now_ma), "target_mA": st.as_ref().map(|s| s.laser_target_ma), "valid": ack.ok()}), &[])+        }+        Ok(ack) => fail_resp(tune::refusal(&ack, None)),+        Err(f) => fail_resp(f),+    }+}++async fn board_centre(State(a): S, Json(p): Json<Value>) -> Response {+    a.touch();+    let chans: Vec<u8> = match p.get("channels") {+        Some(Value::Array(v)) => v.iter().filter_map(|x| x.as_u64()).map(|x| x as u8).collect(),+        _ => vec![1, 2],+    };+    let mut out = vec![];+    for ch in chans {+        match tune::auto_centre(&a, ch).await {+            Ok(v) => out.push(v),+            Err(f) => return fail_resp(f),+        }+    }+    a.broadcast("toast", json!({"text": "Auto-centre done", "kind": "success"}));+    ok(json!(out), &[])+}++async fn board_tune(State(a): S, Json(p): Json<Value>) -> Response {+    a.touch();+    let tp: tune::TuneParams = match serde_json::from_value(p) {+        Ok(t) => t,+        Err(e) => return refuse(StatusCode::BAD_REQUEST, &format!("invalid tune parameters: {e}"), &["Keys: channel, min_ma, max_ma, steps, dither_ma, measure_s, gains".into()]),+    };+    let st = a.engine.lock().unwrap().board_state();+    if !st.as_ref().is_some_and(|s| s.laser_on) {+        return refuse(StatusCode::CONFLICT, "the laser is off; tuning never turns it on by itself", &["Turn it on first: `smi-dash laser on --beam-safe`".into()]);+    }+    match tune::spawn_tune(a.clone(), tp) {+        Ok(()) => ok(json!({"started": true}), &["Progress: `smi-dash tune --status` (or the Controls panel); about 15 to 25 s"]),+        Err(f) => fail_resp(f),+    }+}++async fn board_tune_get(State(a): S) -> Response {+    let t = a.engine.lock().unwrap().tune.clone();+    ok(t, &[])+}++async fn board_tune_stop(State(a): S) -> Response {+    tune::TUNE_CANCEL.store(true, std::sync::atomic::Ordering::SeqCst);+    let _ = &a;+    ok(json!({"stopping": tune::TUNE_RUNNING.load(std::sync::atomic::Ordering::SeqCst)}), &[])+}++async fn board_clear_fault(State(a): S) -> Response {+    a.touch();+    match tune::cmd(&a, vec![controls::OP_CLEAR_FAULT]).await {+        Ok(_) => ok(board_now(&a), &["If the cause remains, the fault latches again"]),+        Err(f) => fail_resp(f),+    }+}++async fn board_config(State(a): S, Json(p): Json<Value>) -> Response {+    a.touch();+    let cur = a.engine.lock().unwrap().board_state();+    let hz = p.get("isense_hz").and_then(|v| v.as_u64()).unwrap_or(cur.as_ref().map(|s| s.isense_hz as u64).unwrap_or(10));+    let hb = p.get("hb_timeout_ms").and_then(|v| v.as_u64()).unwrap_or(cur.as_ref().map(|s| s.hb_timeout_ms as u64).unwrap_or(3000));+    match tune::cmd(&a, controls::cmd_config(hz.min(255) as u8, hb.min(65535) as u16)).await {+        Ok(ack) if ack.ok() => ok(board_now(&a), &[]),+        Ok(ack) => {+            let (lo, hi) = ack.range().unwrap_or((0.0, 0.0));+            refuse(StatusCode::BAD_REQUEST, &format!("out of range (allowed {lo} to {hi})"), &["isense_hz 1..50, hb_timeout_ms 500..30000".into()])+        }+        Err(f) => fail_resp(f),+    }+}
software/dashboard/src/sim.rs+129−10
@@ -15,6 +15,12 @@ //! (44.4 kHz, Q 0.98), then the RP2040 ADC: 12-bit, 3.3 V reference, about //! 1.3 LSB rms noise and the wide codes at 512, 1536, 2560 and 3584. //!+//! Board v1.2 (`generate_with` and a BoardAnalog): the laser current from the+//! simulated DAC sets the optical power, the modulation depth, the wavelength+//! (current tuning makes fringes even with the target still) and mode hops;+//! each channel follows the board map's stage equation with its TIA gain,+//! second-stage gain, DAC offset and the monitor bias (see `laser`).+//! //! The ADC alternates ADC0/ADC1 every 2 us (500 ksps total), so the simulator //! runs at 500 kHz and samples ch1 on even ticks and ch2 on odd ticks, exactly //! as the firmware's round robin does.@@ -80,6 +86,9 @@ pub struct SimParams {     pub m: f64,     pub wavelength_nm: f64,     pub multimode: bool,+    /// Simulate board v1.2: the laser current, gains, offsets and bias come from+    /// the simulated DAC and switches (Controls panel). Off: the v1.1 fixed chain.+    pub board: bool,     /// Excess intensity noise multiplier (1 = clean bench, 10 = vibration, speckle).     pub noise: f64,     /// Offset trim error at the ADC, volts.@@ -111,6 +120,7 @@ impl Default for SimParams {             m: 0.12,             wavelength_nm: 658.0,             multimode: false,+            board: true,             noise: 1.0,             offset_v: 0.02,             rf1_ohm: 4700.0,@@ -203,6 +213,9 @@ struct Mode { }  impl Mode {+    fn set_lambda(&mut self, lambda_m: f64) {+        self.k = 2.0 * PI / lambda_m;+    }     fn new(lambda_m: f64, weight: f64) -> Self {         Self { k: 2.0 * PI / lambda_m, weight, phi_f: 0.0, phi0_prev: 0.0, init: false }     }@@ -337,6 +350,65 @@ pub struct Simulator {     rebuild: bool,     t_profile_origin: f64,     pos_origin: f64,+    /// Board mode: longitudinal modes keyed by (mode number * 2 + beat partner).+    bmodes: Vec<(i64, Mode)>,+}++/// Laser model for board v1.2 (a 658 nm Fabry-Perot diode such as the HL6501MG).+/// Model values, not datasheet figures: threshold 60 mA, 0.45 mW/mA above it,+/// thermal tuning 0.006 nm/mA, a mode hop every 18 mA (at 70, 88 and 106 mA)+/// with two-mode competition within 2 mA of each hop, 0.2 nm mode spacing.+pub mod laser {+    pub const ITH_MA: f64 = 60.0;+    pub const SLOPE_MW_PER_MA: f64 = 0.45;+    /// Reference current: the monitor and external photocurrents and the+    /// modulation depth m in SimParams are given at this current.+    pub const IREF_MA: f64 = 110.0;+    pub const TUNE_NM_PER_MA: f64 = 0.006;+    pub const HOP_FIRST_MA: f64 = 70.0;+    pub const HOP_EVERY_MA: f64 = 18.0;+    pub const HOP_HALF_WIDTH_MA: f64 = 2.0;+    pub const MODE_SPACING_NM: f64 = 0.2;+    /// Photocurrents at IREF: monitor photodiode and the external detector.+    pub const IMON_UA: f64 = 35.0;+    pub const IEXT_UA: f64 = 3.5;+    /// The external TIA's reference is not in the board map: assumed 0.25 V.+    pub const EXT_VREF: f64 = 0.25;++    pub fn power_mw(i: f64) -> f64 {+        if i > ITH_MA { SLOPE_MW_PER_MA * (i - ITH_MA) + 0.4 } else { 0.4 * (i / ITH_MA).max(0.0) }+    }+    /// Self-mixing modulation depth relative to m at IREF: large just above+    /// threshold, falling as the laser is driven harder; zero below threshold.+    pub fn m_scale(i: f64) -> f64 {+        if i <= ITH_MA {+            return 0.0;+        }+        let on = ((i - ITH_MA) / 2.0).min(1.0);+        (((IREF_MA - ITH_MA) / (i - ITH_MA)).powf(0.6)).min(3.0) * on+    }+    fn hop_n(i: f64) -> i64 {+        if i < HOP_FIRST_MA { 0 } else { ((i - HOP_FIRST_MA) / HOP_EVERY_MA).floor() as i64 + 1 }+    }+    /// Active modes at current i: (mode number, weight), one or two of them.+    pub fn modes(i: f64) -> Vec<(i64, f64)> {+        let n = hop_n(i);+        // Distance to the nearest hop centre.+        let k = ((i - HOP_FIRST_MA) / HOP_EVERY_MA).round();+        let h = HOP_FIRST_MA + k * HOP_EVERY_MA;+        let d = i - h;+        if k >= 0.0 && d.abs() < HOP_HALF_WIDTH_MA {+            let x = (d + HOP_HALF_WIDTH_MA) / (2.0 * HOP_HALF_WIDTH_MA);+            let w = x * x * (3.0 - 2.0 * x); // weight of the mode above the hop+            let hi = k as i64 + 1;+            vec![(hi - 1, 1.0 - w), (hi, w)]+        } else {+            vec![(n, 1.0)]+        }+    }+    pub fn lambda_nm(base: f64, i: f64, n: i64) -> f64 {+        base + TUNE_NM_PER_MA * (i - IREF_MA) + MODE_SPACING_NM * (n - hop_n(IREF_MA)) as f64+    } }  impl Simulator {@@ -362,6 +434,7 @@ impl Simulator {             rebuild: true,             t_profile_origin: 0.0,             pos_origin: 0.0,+            bmodes: vec![],         };         s.build_modes();         for i in 0..2 {@@ -478,8 +551,14 @@ impl Simulator {         None     } -    /// Generate `pairs` ADC sample pairs.+    /// Generate `pairs` ADC sample pairs with the v1.1 fixed analog chain.     pub fn generate(&mut self, pairs: usize) -> Chunk {+        self.generate_with(pairs, None)+    }++    /// Generate `pairs` ADC sample pairs; with `board`, the v1.2 board's laser+    /// current, gains, offsets and bias drive the optics and the analog chain.+    pub fn generate_with(&mut self, pairs: usize, board: Option<&crate::controls::BoardAnalog>) -> Chunk {         let mut out = Chunk {             ch1: Vec::with_capacity(pairs),             ch2: Vec::with_capacity(pairs),@@ -516,15 +595,55 @@ impl Simulator {                     }                 }                 let l = self.base_l + self.pos + mech * normal.sample(&mut self.rng);-                let mut fr = 0.0;-                for m in self.modes.iter_mut() {-                    fr += m.weight * m.step(l, self.p.c, th);-                }-                let pw = 1.0 + self.p.m * fr + rin * normal.sample(&mut self.rng);-                // Both channels see the same optical power fluctuation (rear monitor-                // and front pickoff), each through its own TIA and the inverting chain.-                let v1 = 1.65 + self.p.offset_v - a1 * (pw - 1.0);-                let v2 = 1.65 - 0.6 * self.p.offset_v - a2 * (pw - 1.0) + 0.002 * (2.0 * PI * 100.0 * self.t).sin();+                let (v1, v2) = if let Some(b) = board {+                    let i = b.i0_ma + (b.i1_ma - b.i0_ma) * (out.ch1.len() as f64 + 0.5 * sub as f64) / pairs as f64;+                    let act = laser::modes(i);+                    let beat_dl = if self.p.multimode { let lam = self.p.wavelength_nm; lam * lam / (2.0 * BEAT_MM * 1e6) } else { 0.0 };+                    let mut fr = 0.0;+                    let mut keys = [i64::MIN; 4];+                    let mut nk = 0;+                    for &(n, w) in &act {+                        let parts: &[(i64, f64, f64)] = if self.p.multimode { &[(0, 0.5, -0.5), (1, 0.5, 0.5)] } else { &[(0, 1.0, 0.0)] };+                        for &(pi, pw_, off) in parts {+                            let key = n * 2 + pi;+                            let lam = (laser::lambda_nm(self.p.wavelength_nm, i, n) + off * beat_dl) * 1e-9;+                            let m = match self.bmodes.iter_mut().find(|(k, _)| *k == key) {+                                Some((_, m)) => m,+                                None => {+                                    self.bmodes.push((key, Mode::new(lam, 1.0)));+                                    &mut self.bmodes.last_mut().unwrap().1+                                }+                            };+                            m.set_lambda(lam);+                            fr += w * pw_ * m.step(l, self.p.c, th);+                            keys[nk] = key;+                            nk += 1;+                        }+                    }+                    self.bmodes.retain(|(k, _)| keys[..nk].contains(k));+                    // Mode competition near a hop adds partition noise.+                    let wmix = if act.len() == 2 { act[0].1 * act[1].1 } else { 0.0 };+                    let prel = laser::power_mw(i) / laser::power_mw(laser::IREF_MA);+                    let m = self.p.m * laser::m_scale(i);+                    let pw = 1.0 + m * fr + rin * (1.0 + 120.0 * wmix) * normal.sample(&mut self.rng);+                    let i1 = laser::IMON_UA * 1e-6 * prel * pw;+                    let i2 = laser::IEXT_UA * 1e-6 * prel * pw;+                    // Vbuffer = Vref + I * Rf (rail-limited), Vstage = (1 + K) Voff - K Vbuffer.+                    let vb1: f64 = (b.bias_v + i1 * b.rf1).min(5.2);+                    let vb2: f64 = (laser::EXT_VREF + i2 * b.rf2).min(5.2);+                    let s1: f64 = ((1.0_f64 + b.k1) * b.off1_v - b.k1 * vb1).clamp(0.02, 5.25);+                    let s2: f64 = ((1.0_f64 + b.k2) * b.off2_v - b.k2 * vb2).clamp(0.02, 5.25) + 0.002 * (2.0 * PI * 100.0 * self.t).sin();+                    (s1, s2)+                } else {+                    let mut fr = 0.0;+                    for m in self.modes.iter_mut() {+                        fr += m.weight * m.step(l, self.p.c, th);+                    }+                    let pw = 1.0 + self.p.m * fr + rin * normal.sample(&mut self.rng);+                    // Both channels see the same optical power fluctuation (rear monitor+                    // and front pickoff), each through its own TIA and the inverting chain.+                    (1.65 + self.p.offset_v - a1 * (pw - 1.0), 1.65 - 0.6 * self.p.offset_v - a2 * (pw - 1.0) + 0.002 * (2.0 * PI * 100.0 * self.t).sin())+                };                 let y1 = self.aa2[0].run(self.aa1[0].run(v1));                 let y2 = self.aa2[1].run(self.aa1[1].run(v2));                 let y = if sub == 0 { y1 } else { y2 };
software/dashboard/src/tune.rsadded+468
@@ -0,0 +1,468 @@+// SPDX-License-Identifier: MIT+//! Board operations shared by the page, the CLI and the tuner: send a command+//! (simulated board or Pico), auto-centre a channel, and tune for fringes.++use crate::controls::{self, Ack, ControlMap};+use crate::engine::{ChanStats, SourceKind};+use crate::server::App;+use serde_json::{json, Value};+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::Arc;+use std::time::{Duration, Instant};++pub static TUNE_CANCEL: AtomicBool = AtomicBool::new(false);+pub static TUNE_RUNNING: AtomicBool = AtomicBool::new(false);+const MID: f64 = 2048.0;+const LSB: f64 = 3.3 / 4096.0;++pub type Fail = (String, Vec<String>);++fn fail(m: impl Into<String>, h: &[&str]) -> Fail {+    (m.into(), h.iter().map(|s| s.to_string()).collect())+}++/// Send one command payload to whichever board is the source.+pub async fn cmd(a: &Arc<App>, payload: Vec<u8>) -> Result<Ack, Fail> {+    let (sim, board, link) = {+        let e = a.engine.lock().unwrap();+        (matches!(e.source, SourceKind::Sim), e.sim_p.board, e.cmdlink.clone())+    };+    if sim {+        if !board {+            return Err(fail("the simulator is modelling the v1.1 board, which has no software controls", &["Turn the v1.2 board model on: `smi-dash sim --board on`"]));+        }+        let r = a.engine.lock().unwrap().sim_command(&payload);+        return Ack::parse(&r).ok_or_else(|| fail("malformed ACK from the simulated board", &[]));+    }+    let op = payload.first().copied().unwrap_or(0);+    let refresh = !matches!(op, controls::OP_HEARTBEAT | controls::OP_GET_STATE | controls::OP_READ_ISENSE);+    let link2 = link.clone();+    match tokio::task::spawn_blocking(move || link.call(&payload)).await {+        Ok(Ok(ack)) => {+            // The Pico pushes STATE four times a second; after a change, fetch it+            // now so the next reader (a --wait loop, the page) sees the change.+            if refresh {+                if let Ok(Ok(st)) = tokio::task::spawn_blocking(move || link2.call(&[controls::OP_GET_STATE])).await {+                    if let Some(bs) = controls::BoardState::parse(&st.data) {+                        a.engine.lock().unwrap().pico_state = Some((bs, Instant::now()));+                    }+                }+            }+            Ok(ack)+        }+        Ok(Err(m)) => Err((m, vec!["Check the link with `smi-dash status`; the Pico must run firmware 1.2.0 (`smi-dash board map`)".into()])),+        Err(e) => Err(fail(format!("command task failed: {e}"), &[])),+    }+}++/// Explain a refused ACK in terms of the control.+pub fn refusal(ack: &Ack, c: Option<&controls::Control>) -> Fail {+    let mut m = controls::status_text(ack.status).to_string();+    let mut h = vec![];+    if let (Some((lo, hi)), Some(c)) = (ack.range(), c) {+        m = format!("{} ({}) out of range", c.label, c.unit);+        if c.kind == "switch" {+            h.push(format!("{} takes one of: {}", c.id, c.settings.iter().map(|s| format!("{} ({})", s.value, s.label)).collect::<Vec<_>>().join(", ")));+        } else {+            h.push(format!("{} accepts {lo:.4} to {hi:.4} {}", c.id, c.unit));+        }+        if c.role == "laser" {+            h.push(format!("The firmware limit is the lower of the DAC's top ({:.2} mA) and the rated {:.0} mA", c.max, c.rated.unwrap_or(c.max)));+        }+    }+    match ack.status {+        5 => h.push("Turn the laser on with `smi-dash laser on --beam-safe` (the page needs the interlock box ticked)".into()),+        6 => h.push("Read the fault in `smi-dash board`, fix the cause, then `smi-dash board clear-fault`".into()),+        9 => h.push("The firmware checks the current readback at zero with the laser off first; try again in a second".into()),+        10 => {+            if let Some(c) = c {+                h.push(format!("Turn the laser off (`smi-dash laser off`), change {}, then turn it on again. Board note: {}", c.id, c.safety.clone().unwrap_or_default()));+            }+        }+        _ => {}+    }+    (m, h)+}++/// Resolve a control from an id or a short alias (ch1-tia, ch2-amp, ch1-offset, bias, laser).+pub fn resolve(map: &ControlMap, key: &str) -> Option<usize> {+    if let Some(i) = map.index(key) {+        return Some(i);+    }+    let k = key.to_ascii_lowercase();+    let ch = if k.contains("ch1") || k.contains("monitor") { Some(1) } else if k.contains("ch2") || k.contains("external") { Some(2) } else { None };+    if k.contains("offset") {+        return map.find("offset", ch, None);+    }+    if k.contains("tia") {+        return map.find("gain", ch, Some("tia"));+    }+    if k.contains("amp") || k.contains("stage") {+        return map.find("gain", ch, Some("amp"));+    }+    if k.contains("bias") {+        return map.find("bias", None, None);+    }+    if k.contains("laser") || k.contains("current") {+        return Some(map.laser());+    }+    None+}++/// Set control `idx`. mode 0 = units, 1 = DAC counts, 2 = setting index.+pub async fn set(a: &Arc<App>, idx: usize, mode: u8, v: f64) -> Result<Ack, Fail> {+    let c = a.engine.lock().unwrap().map.controls.get(idx).cloned();+    let Some(c) = c else { return Err(fail(format!("no control {idx}"), &["List them with `smi-dash board map`"])) };+    let ack = cmd(a, controls::cmd_set(idx, mode, v as f32)).await?;+    if !ack.ok() {+        return Err(refusal(&ack, Some(&c)));+    }+    Ok(ack)+}++/// Set a control the board says to change only with the laser off. If the+/// laser is on, this turns it off, writes, and turns it back on at the same+/// set-point, then waits for the head's soft-start (board 1.2.1 contract: no+/// writes while armed). It never turns on a laser that was off.+pub async fn set_disarmed(a: &Arc<App>, idx: usize, mode: u8, v: f64) -> Result<Ack, Fail> {+    let (needs_off, on) = {+        let e = a.engine.lock().unwrap();+        (e.map.controls.get(idx).is_some_and(|c| c.requires_laser_off), e.board_state().is_some_and(|s| s.laser_on))+    };+    if !(needs_off && on) {+        return set(a, idx, mode, v).await;+    }+    laser(a, false).await?;+    let r = set(a, idx, mode, v).await;+    laser(a, true).await?;+    wait_settled(a).await?;+    r+}++/// Is the laser on a gated head DAC (written in one step, soft-start on the head)?+pub fn gated(a: &Arc<App>) -> bool {+    let e = a.engine.lock().unwrap();+    let c = &e.map.controls[e.map.laser()];+    c.min_write_ms.unwrap_or(0) > 0 && c.ramp_per_s.unwrap_or(0.0) == 0.0+}++/// Wait for the set-point to be written and, with the laser on, for the+/// measured current to arrive near it (the head's soft-start).+pub async fn wait_settled(a: &Arc<App>) -> Result<(), Fail> {+    wait_ramp(a).await?;+    let t = Instant::now();+    let mut near = 0;+    loop {+        let st = a.engine.lock().unwrap().board_state();+        let Some(s) = st else { return Ok(()) };+        if !s.laser_on || s.laser_now_ma < 0.5 {+            return Ok(());+        }+        let tol = (0.03 * s.laser_now_ma).max(1.0);+        if s.isense_valid && (s.isense_ma - s.laser_now_ma).abs() < tol {+            near += 1;+            if near >= 3 {+                return Ok(());+            }+        } else {+            near = 0;+        }+        if t.elapsed() > Duration::from_secs(2) {+            return Ok(()); // the reading says what it says; the caller scores what is there+        }+        tokio::time::sleep(Duration::from_millis(25)).await;+    }+}++pub async fn laser(a: &Arc<App>, on: bool) -> Result<Ack, Fail> {+    let ack = cmd(a, controls::cmd_laser(on)).await?;+    if !ack.ok() {+        return Err(refusal(&ack, None));+    }+    Ok(ack)+}++fn head(a: &Arc<App>) -> u64 {+    a.engine.lock().unwrap().head+}++/// Wait until `pairs` new sample pairs have arrived after now.+async fn fresh(a: &Arc<App>, pairs: u64) -> Result<(), Fail> {+    let h0 = head(a);+    let t = Instant::now();+    while head(a) < h0 + pairs {+        if t.elapsed() > Duration::from_secs(3) {+            return Err(fail("no new samples are arriving", &["Check the source with `smi-dash status`"]));+        }+        tokio::time::sleep(Duration::from_millis(4)).await;+    }+    Ok(())+}++/// Wait for the laser set-point to finish ramping.+pub async fn wait_ramp(a: &Arc<App>) -> Result<(), Fail> {+    let t = Instant::now();+    loop {+        let st = a.engine.lock().unwrap().board_state();+        match st {+            Some(s) if !s.laser_on => return Ok(()),+            // The core clears "ramping" once the set-point is written (a gated DAC+            // lands on the nearest code, which can differ from the target by+            // half a count) or a stepped ramp has arrived.+            Some(s) if !s.ramping => return Ok(()),+            None => return Err(fail("no board state", &["Is the Pico running firmware 1.2.0?"])),+            _ => {}+        }+        if t.elapsed() > Duration::from_secs(15) {+            return Err(fail("the laser set-point did not settle within 15 s", &[]));+        }+        tokio::time::sleep(Duration::from_millis(20)).await;+    }+}++fn stats(a: &Arc<App>, ch: u8, n: usize) -> ChanStats {+    a.engine.lock().unwrap().chan_stats(ch, n)+}++/// Servo channel `ch`'s mean to mid-scale with its offset DAC.+pub async fn auto_centre(a: &Arc<App>, ch: u8) -> Result<Value, Fail> {+    let (oi, c, k) = {+        let e = a.engine.lock().unwrap();+        let Some(oi) = e.map.find("offset", Some(ch), None) else { return Err(fail(format!("no offset control for channel {ch}"), &[])) };+        let c = e.map.controls[oi].clone();+        // Board map: Vstage = (1 + K) Voffset - K Vbuffer, so the ADC moves (1 + |K|) per offset volt.+        let k = c.gain_link.as_ref().and_then(|g| e.map.index(g)).and_then(|gi| e.board_state().and_then(|s| s.targets.get(gi).copied())).map(|kv| 1.0 + (kv as f64).abs()).or(c.adc_V_per_unit).unwrap_or(2.0);+        (oi, c, k)+    };+    let mut slope = k;+    let mut cur = a.engine.lock().unwrap().board_state().and_then(|s| s.targets.get(oi).copied()).unwrap_or(c.default as f32) as f64;+    let mut prev: Option<(f64, f64)> = None;+    let mut steps = vec![];+    for it in 0..10 {+        fresh(a, 2500).await?;+        let st = stats(a, ch, 2500);+        let err = st.mean - MID;+        steps.push(json!({"offset_V": cur, "mean": st.mean, "clip": st.clip}));+        if err.abs() < 12.0 && st.clip < 0.002 {+            return Ok(json!({"channel": ch, "offset_V": cur, "mean": st.mean, "iterations": it, "slope_V_per_V": slope, "steps": steps}));+        }+        if let Some((po, pm)) = prev {+            let d = cur - po;+            // Secant update when both points were off the rails.+            if d.abs() > 1e-4 && st.clip < 0.05 && (pm - MID).abs() < 2000.0 {+                let s = (st.mean - pm) * LSB / d;+                if s > 0.3 * k && s < 3.0 * k {+                    slope = s;+                }+            }+        }+        prev = Some((cur, st.mean));+        let want = (cur - err * LSB / slope).clamp(c.min, c.max);+        if (want - cur).abs() < c.per_code.unwrap_or(1e-3) * 0.5 {+            return Err(fail(+                format!("cannot centre channel {ch}: the offset DAC is at {:.3} V, its limit, and the mean is still {:.0} codes from mid-scale", cur, err),+                &["Lower the second-stage gain, or choose a monitor bias that keeps the stage inside the ADC rails (with the laser off)"],+            ));+        }+        set_disarmed(a, oi, 0, want).await?;+        cur = want;+    }+    let st = stats(a, ch, 2500);+    Ok(json!({"channel": ch, "offset_V": cur, "mean": st.mean, "iterations": 10, "converged": false, "steps": steps}))+}++/// Fringe score of channel `ch` over the last `n` pairs: fringe swing over the+/// broadband noise, penalised for clipping.+pub fn score(s: &ChanStats) -> f64 {+    let pen = (1.0 - 20.0 * s.clip).max(0.0);+    s.swing / s.noise.max(0.5) * pen+}++fn progress(a: &Arc<App>, v: Value) {+    a.engine.lock().unwrap().tune = v.clone();+    a.broadcast("tune", v);+}++#[derive(Clone, Debug, serde::Deserialize)]+#[serde(default)]+pub struct TuneParams {+    pub channel: u8,+    pub min_ma: Option<f64>,+    pub max_ma: Option<f64>,+    pub steps: usize,+    /// Current dither while scoring, so a still target still makes fringes+    /// (current tuning moves the wavelength), mA peak.+    pub dither_ma: f64,+    pub measure_s: f64,+    /// Also try the second-stage gains.+    pub gains: bool,+}++impl Default for TuneParams {+    fn default() -> Self {+        Self { channel: 1, min_ma: None, max_ma: None, steps: 8, dither_ma: 0.5, measure_s: 0.4, gains: true }+    }+}++async fn measure(a: &Arc<App>, li: usize, base: f64, p: &TuneParams, ch: u8) -> Result<(ChanStats, i64), Fail> {+    let n = (p.measure_s * 250_000.0) as usize;+    let c0 = a.engine.lock().unwrap().det.count;+    let h0 = head(a);+    let lim = a.engine.lock().unwrap().map.controls[li].limit();+    let mut up = true;+    // A gated head DAC cannot be dithered: every write disarms the laser and+    // restarts its soft-start. There the score needs a moving target.+    let dither = if gated(a) { 0.0 } else { p.dither_ma };+    while head(a) < h0 + n as u64 {+        if TUNE_CANCEL.load(Ordering::SeqCst) {+            return Err(fail("tuning stopped", &[]));+        }+        if dither > 0.0 {+            let t = if up { base + dither } else { base - dither };+            set(a, li, 0, t.clamp(0.0, lim)).await?;+        }+        up = !up;+        tokio::time::sleep(Duration::from_millis(60)).await;+    }+    if dither > 0.0 {+        set(a, li, 0, base).await?;+    }+    let st = stats(a, ch, n);+    let fr = a.engine.lock().unwrap().det.count - c0;+    Ok((st, fr))+}++/// Step the laser current, re-centre, score the fringes, then try the second-stage gains.+pub async fn tune(a: Arc<App>, p: TuneParams) -> Result<Value, Fail> {+    let (li, lim, map) = {+        let e = a.engine.lock().unwrap();+        let li = e.map.laser();+        (li, e.map.controls[li].limit(), e.map.clone())+    };+    let st = a.engine.lock().unwrap().board_state().ok_or_else(|| fail("no board state", &[]))?;+    if !st.laser_on {+        return Err(fail("the laser is off; tuning never turns it on by itself", &["Turn it on first: `smi-dash laser on --beam-safe`, then `smi-dash tune`"]));+    }+    let ch = p.channel.clamp(1, 2);+    let start_ma = st.laser_target_ma as f64;+    let lo = p.min_ma.unwrap_or(lim * 0.4).clamp(0.0, lim);+    let hi = p.max_ma.unwrap_or(lim).clamp(lo, lim);+    let t0 = Instant::now();+    let mut log: Vec<Value> = vec![];+    let mut best: Option<(f64, f64)> = None; // (score, mA)+    let coarse: Vec<f64> = (0..p.steps.max(2)).map(|k| lo + (hi - lo) * k as f64 / (p.steps.max(2) - 1) as f64).collect();+    for ma in coarse {+        let s = step(&a, li, ma, &p, ch, "current", &mut log, t0).await?;+        if best.is_none_or(|b| s > b.0) {+            best = Some((s, ma));+        }+    }+    let (_, b) = best.unwrap();+    let span = (hi - lo) / (p.steps.max(2) - 1) as f64;+    let fine: Vec<f64> = (-2..=2).map(|k| b + k as f64 * span / 4.0).filter(|m| *m >= lo && *m <= hi && (*m - b).abs() > 1e-6).collect();+    for ma in fine {+        let s = step(&a, li, ma, &p, ch, "fine", &mut log, t0).await?;+        if s > best.unwrap().0 {+            best = Some((s, ma));+        }+    }+    let (bs, bma) = best.unwrap();+    let mut gain_choice = Value::Null;+    if p.gains {+        if let Some(gi) = map.find("gain", Some(ch), Some("amp")) {+            let g = &map.controls[gi];+            let mut gbest: Option<(f64, f64)> = None;+            for s in &g.settings {+                if TUNE_CANCEL.load(Ordering::SeqCst) {+                    return Err(fail("tuning stopped", &[]));+                }+                set_disarmed(&a, gi, 0, s.value).await?;+                let sc = step(&a, li, bma, &p, ch, "gain", &mut log, t0).await?;+                log.last_mut().unwrap()["gain"] = json!(s.value);+                if gbest.is_none_or(|b| sc > b.0) {+                    gbest = Some((sc, s.value));+                }+            }+            let (_, gv) = gbest.unwrap();+            set_disarmed(&a, gi, 0, gv).await?;+            gain_choice = json!({"id": g.id, "value": gv, "label": g.setting_label(gv)});+        }+    }+    // Final: best current, centred, scored once more.+    let fs = step(&a, li, bma, &p, ch, "final", &mut log, t0).await?;+    // Leave both channels centred for the gains now in place.+    for c2 in [1u8, 2] {+        let _ = auto_centre(&a, c2).await;+    }+    let fringes: i64 = log.iter().map(|r| r["fringes"].as_i64().unwrap_or(0).abs()).sum();+    // Nothing to score: put the current back where it was rather than keep a+    // "best" chosen from noise.+    let bma = if fringes == 0 {+        set(&a, li, 0, start_ma).await?;+        wait_settled(&a).await?;+        for c2 in [1u8, 2] {+            let _ = auto_centre(&a, c2).await;+        }+        start_ma+    } else {+        bma+    };+    let note = if fringes == 0 {+        Value::String(if gated(&a) {+            "No fringes were seen. On this board the laser current cannot be dithered (every write restarts the head's soft-start), so move the target while tuning.".into()+        } else {+            "No fringes were seen; check the alignment and the target.".into()+        })+    } else {+        Value::Null+    };+    let result = json!({+        "note": note,+        "status": "done", "channel": ch, "best_mA": bma, "best_score_sweep": bs, "final_score": fs,+        "gain": gain_choice, "seconds": t0.elapsed().as_secs_f64(), "steps": log,+    });+    progress(&a, result.clone());+    Ok(result)+}++#[allow(clippy::too_many_arguments)]+async fn step(a: &Arc<App>, li: usize, ma: f64, p: &TuneParams, ch: u8, phase: &str, log: &mut Vec<Value>, t0: Instant) -> Result<f64, Fail> {+    if TUNE_CANCEL.load(Ordering::SeqCst) {+        return Err(fail("tuning stopped", &[]));+    }+    set(a, li, 0, ma).await?;+    wait_settled(a).await?;+    let centred = auto_centre(a, ch).await;+    let (st, fr) = measure(a, li, ma, p, ch).await?;+    let sc = score(&st);+    let meas = a.engine.lock().unwrap().board_state().map(|s| s.isense_ma).unwrap_or(f32::NAN);+    let row = json!({+        "phase": phase, "set_mA": ma, "measured_mA": meas, "score": (sc * 10.0).round() / 10.0,+        "swing": st.swing.round(), "noise": (st.noise * 100.0).round() / 100.0, "clip": st.clip, "fringes": fr,+        "centred": centred.is_ok(), "t_s": t0.elapsed().as_secs_f64(),+    });+    log.push(row.clone());+    progress(a, json!({"status": "running", "phase": phase, "step": log.len(), "last": row, "steps": log}));+    Ok(sc)+}++/// Start the tuner in the background (one at a time).+pub fn spawn_tune(a: Arc<App>, p: TuneParams) -> Result<(), Fail> {+    if TUNE_RUNNING.swap(true, Ordering::SeqCst) {+        return Err(fail("a tune is already running", &["Watch it with `smi-dash tune --status`, stop it with `smi-dash tune --stop`"]));+    }+    TUNE_CANCEL.store(false, Ordering::SeqCst);+    progress(&a, json!({"status": "running", "phase": "start", "step": 0, "steps": []}));+    tokio::spawn(async move {+        let r = tune(a.clone(), p).await;+        if let Err((m, h)) = r {+            let prev = a.engine.lock().unwrap().tune.clone();+            progress(&a, json!({"status": "failed", "error": m, "hints": h, "steps": prev["steps"]}));+            a.broadcast("toast", json!({"text": format!("Tuning: {m}"), "kind": "error"}));+        } else {+            a.broadcast("toast", json!({"text": "Tuning finished", "kind": "success"}));+        }+        TUNE_RUNNING.store(false, Ordering::SeqCst);+    });+    Ok(())+}
software/dist/SHA256SUMS+3−3
@@ -1,3 +1,3 @@-3bd07d3d729ac9d1150e9a04079392ffdb51f313b6a0fc219624fd94877b4654  smi_pico.uf2-5d193be1b4148ad967e45339a13a5059bddbb33f7304ec1b8b2491d3d7166fb0  smi-dash-linux-x64-155a0c999610397694fcc3e369c6798ac6062aa332e2b47aa32b65e7b7eb8ab6  smi-dash-windows-x64.exe+e263677d31d6af4d997db00ee92a4a135ac3a28830cda2afbc0f02213fbbc9c4  smi_pico.uf2+ae81a40ab4841d8525d5a8a63db6f8dcdec75dfdfa86d84aa05d60241e5ba89e  smi-dash-linux-x64+b4c2f0e8dd6642aee31db46ef500549d75474103be79323800685ccde5db962b  smi-dash-windows-x64.exe
software/dist/smi-dash-linux-x64
⋯ 1 unchanged line ⋯
software/dist/smi-dash-windows-x64.exe
⋯ 1 unchanged line ⋯
software/dist/smi_pico.uf2
⋯ 1 unchanged line ⋯
software/firmware/CMakeLists.txt+6
@@ -9,6 +9,8 @@ pico_sdk_init() add_executable(smi_pico     src/main.c     src/smi_frame.c+    src/smi_ctl.c+    src/smi_text.c     src/usb_descriptors.c ) target_include_directories(smi_pico PRIVATE ${CMAKE_CURRENT_LIST_DIR}/src)@@ -18,6 +20,10 @@ target_link_libraries(smi_pico PRIVATE     pico_unique_id     hardware_adc     hardware_dma+    hardware_i2c+    hardware_pwm+    hardware_clocks+    hardware_watchdog     hardware_irq     tinyusb_device     tinyusb_board
software/firmware/README.md+15−5
@@ -1,6 +1,6 @@ # Pico firmware: smi_pico -Turns a Raspberry Pi Pico (RP2040, SC0915) into the interferometer's two-channel digitizer.+Turns a Raspberry Pi Pico (RP2040, SC0915) into the interferometer's two-channel digitizer and, on board v1.2, the board's controller: laser enable and current, both offsets, the gains and the monitor bias, with the laser's limits enforced here as well as in hardware.  | Pin | Use | |---|---|@@ -8,7 +8,13 @@ Turns a Raspberry Pi Pico (RP2040, SC0915) into the interferometer's two-channel | GPIO27 / ADC1, pin 32 | Channel 2, external photodiode | | GPIO15, pin 20 | SYNC from the motion stage (the board's SN74LVC1G17 buffer, non-inverting; internal pulls off) | | ADC_VREF, pin 35 | Filtered on the board (C150), not driven by the firmware |-| USB | CDC serial, the data stream |+| USB | CDC serial: the data stream and the command channel |+| GPIO4 / GPIO5 | I2C0 SDA / SCL, 100 kHz, 750 us per transfer: the laser head's DAC121C085 (0x09, laser set-point), MCP23008 (0x20) and ADS1115 (0x49, differential AIN0-AIN1); the main board's DAC7574 (0x4C, offsets) |+| GPIO6 | Laser enable as a 10 kHz carrier (PWM), only after a verified nonzero set-point |+| GPIO7, GPIO8, GPIO9 | Monitor second-stage gain, external second-stage gain, external TIA gain |+| GPIO28 / ADC2, pin 34 | Main 5.3 V analog rail through a 1:2 divider, read once a second |++The v1.2 pins and devices come from the board's control map: `controls/gen_controls.py` writes them into `src/smi_controls_gen.h`. Rebuild after changing the map.  ## Flashing @@ -22,7 +28,9 @@ Turns a Raspberry Pi Pico (RP2040, SC0915) into the interferometer's two-channel - Two DMA channels, chained ping-pong, fill a ring of 16 buffers of 1024 pairs (4.1 ms each, 65 ms of slack for USB stalls). If the ring overruns, the buffer is counted as dropped and the host sees the gap in the sample index. - A GPIO interrupt on both edges of GPIO15 reads the live DMA position, so every SYNC edge carries the index of the sample pair it landed on (resolution one pair, 4 us, plus interrupt latency) and a `time_us_32` timestamp. - The main loop packs each finished buffer into one DATA frame and writes it to USB CDC. A STATUS frame every 0.5 s reports the pair count, dropped buffers and lost SYNC events.-- Streaming starts when the host opens the port (DTR) and stops when it closes it. Text commands, one per line: `start`, `stop`, `info`.+- Streaming starts when the host opens the port (DTR) and stops when it closes it. Text commands, one per line: `start`, `stop`, `info`, and the board contract's `laser CODE`, `laser off`, `laser current`, `head MASK`, `gain MASK`, `offset B CODE`, `offset C CODE` (plus `hb MS`), in `src/smi_text.c`.+- Board v1.2: binary CMD frames on the same link run the control core in `src/smi_ctl.c` (ops, ACK and STATE layouts in `src/smi_ctl.h`). The laser is off at power-up, after a watchdog reset, when the port closes or USB goes away, and after 3 s without a command; each set-point write follows the board's controller contract (enable dropped, 2 ms wait, write, readback, carrier only on a verified nonzero code, one more readback; at most four writes a second; command codes pass a 45-count guard band) and is refused above the limit; while armed the head DAC is read back every 2 ms (which also feeds the head's I2C watchdog) and the bus carries no other writes; the head's ADS1115 is read 50 times a second for the overcurrent trip, with its configuration written only while disarmed. A STATE frame goes out four times a second.+- The analog rail on ADC2 is read once a second by pausing the round robin after a complete ch0/ch1 pair for about 14 us; pair indices stay contiguous and the pause count is in STATUS.  ## Stream format @@ -31,7 +39,7 @@ All fields little-endian. Every frame: | Bytes | Field | |---|---| | 2 | sync word `A5 5A` |-| 1 | type: 1 DATA, 2 SYNC, 3 STATUS, 4 INFO |+| 1 | type: 1 DATA, 2 SYNC, 3 STATUS, 4 INFO, 0x10 CMD (host to Pico), 0x11 ACK, 0x12 STATE | | 1 | flags, 0 | | 2 | payload length | | 2 | sequence number, wraps |@@ -40,7 +48,7 @@ All fields little-endian. Every frame:  DATA payload: `u64 first_pair`, `u32 t_us` (time the DMA buffer completed), `u8 groups` (16), then for each group of 64 pairs a channel 1 block and a channel 2 block. A block is `u16 head` (bits 0 to 11 the first sample, bits 12 to 15 a width code `w`) followed by 63 values packed LSB first and padded to a byte: for `w` from 0 to 12 they are zigzag-encoded deltas of `w` bits, for `w` = 15 they are raw 12-bit samples (used when the deltas would need 13 bits). -SYNC payload: `u64 pair`, `u32 t_us`, `u8 level`. STATUS payload: `u64 pairs`, `u32 dropped_buffers`, `u32 sync_lost`, `u32 total_sps`, `u32 t_us`. INFO payload: ASCII text with the version and rates.+SYNC payload: `u64 pair`, `u32 t_us`, `u8 level`. STATUS payload: `u64 pairs`, `u32 dropped_buffers`, `u32 sync_lost`, `u32 total_sps`, `u32 t_us`, then (1.2.0) `u32 adc2_pauses`, `u16 rail_mV`. INFO payload: ASCII text with the version and rates.  On realistic fringe signals a block takes about 4.6 bits per sample including all headers, about 290 kB/s for both channels; the worst case (pure noise) is 12 bits per sample, 750 kB/s, still inside USB full speed. @@ -56,6 +64,8 @@ Toolchain used for the published file: arm-none-eabi-gcc 13.2 on Ubuntu 24.04. T  ## Tests +`test/test_ctl.c` runs the control core against the generated control table (293 checks; `cc -O2 -Isrc test/test_ctl.c src/smi_ctl.c -lm`). `test/ctl_pty.c` serves the control and text-command code behind a pseudo-terminal, so the dashboard's serial command path and the board contract's text commands (`test/text_cmd_test.py`, 11 checks) can be tested without a Pico.+ `test/test_pack.c` round-trips 40,000 blocks through the packer and checks the CRC against its standard check value, and writes `test/vectors.bin`, which the dashboard's Rust decoder must decode exactly. `test/stream_gen.c` packs raw sample pairs from stdin into a full stream, for replaying recorded or simulated data into the dashboard over a serial port.  ```
software/firmware/src/main.c+395−38
@@ -1,20 +1,41 @@ // SPDX-License-Identifier: MIT-// Self-mixing interferometer digitizer for the Raspberry Pi Pico (RP2040).+// Self-mixing interferometer digitizer and board controller for the Raspberry+// Pi Pico (RP2040), board v1.2. // // ADC0 (GPIO26) = channel 1, laser monitor photodiode after the analog chain. // ADC1 (GPIO27) = channel 2, external photodiode.+// ADC2 (GPIO28) = main board 5.3 V analog rail through a 1:2 divider (monitor).+// Laser current: ADS1115 on the laser head (I2C), AIN0 across the 2 ohm shunt. // GPIO15        = SYNC from the motion stage (SN74LVC1G17 buffer, non-inverting).+// I2C0, across the cable to the laser head: the head's DAC121C085 (laser+// set-point, written then read back), MCP23008 (monitor TIA gain, monitor+// bias) and ADS1115 (laser current); on the main board the DAC7574 (both+// offsets). GPIO6 carries the laser enable as a 10 kHz carrier, started only+// after a verified nonzero set-point; while armed the firmware reads the head+// DAC back every 2 ms, which also keeps the head's I2C watchdog fed. Pico GPIOs: laser enable and the other+// gain switches. All from the control map (controls/control-map.json ->+// smi_controls_gen.h via controls/gen_controls.py). // // The ADC free-runs in round-robin over inputs 0 and 1 at 48 MHz / 96 = 500 ksps-// total (250 ksps per channel). DMA moves samples into a ring of buffers-// (two channels chained ping-pong). The main loop packs each finished buffer-// into a DATA frame (delta-encoded 64-sample blocks with a per-block bit width,+// total (250 ksps per channel). DMA moves samples into a ring of buffers (two+// channels chained ping-pong). The main loop packs each finished buffer into a+// DATA frame (delta-encoded 64-sample blocks with a per-block bit width, // CRC-16) and writes it to USB CDC. SYNC edges are captured by a GPIO interrupt // that reads the live DMA position, so each edge carries the sample-pair index // it landed on. //-// Streaming starts when the host asserts DTR (opens the port) and stops when it-// drops. Text commands, one per line: "start", "stop", "info".+// The laser current is read from the head's ADS1115 over I2C isense_hz times a+// second (50 by default; the ADS1115 converts continuously at 128 SPS), so the+// sampling is not disturbed. The analog rail on ADC2 is read once a second by+// pausing the round robin at a pair boundary for about 14 us; pair indices stay+// contiguous and the pause count and rail voltage are in STATUS.+//+// Commands: binary CMD frames (smi_ctl.h), or text lines: "start", "stop",+// "info", and the board contract's "laser CODE", "laser off", "laser current",+// "head MASK", "gain MASK", "offset B CODE", "offset C CODE" (plus "hb MS").+// Safety: the laser is off at boot, after a watchdog reset, when the host closes+// the port or USB goes away, when no command arrives for hb_timeout_ms, on+// overcurrent, and on a DAC write failure.  #include <stdio.h> #include <string.h>@@ -22,18 +43,28 @@ #include "hardware/adc.h" #include "hardware/dma.h" #include "hardware/gpio.h"+#include "hardware/i2c.h"+#include "hardware/pwm.h"+#include "hardware/clocks.h" #include "hardware/irq.h" #include "hardware/sync.h"+#include "hardware/watchdog.h" #include "tusb.h" #include "smi_frame.h"+#include "smi_ctl.h"+#include "smi_controls_gen.h"+#include "smi_text.h" -#define FW_VERSION "1.0.0"+#define FW_VERSION "1.2.1" #define SYNC_GPIO 15+#define RAIL_GPIO 28 #define PAIRS_PER_BUF 1024 #define SAMPLES_PER_BUF (PAIRS_PER_BUF * 2) #define NBUF 16 #define TOTAL_SPS 500000u #define SYNC_QUEUE 64+#define WATCHDOG_MS 300+#define I2C_TIMEOUT_US 750u   // per transfer, as in the board's 1.2 controller patch  static uint16_t bufs[NBUF][SAMPLES_PER_BUF] __attribute__((aligned(4))); static int dma_a, dma_b;@@ -44,6 +75,9 @@ static volatile uint32_t buf_done_us[NBUF]; static volatile uint32_t dropped_bufs; static volatile uint32_t bufs_sent;                // buffers handed to USB (main loop only) static volatile bool running;+static uint32_t isense_pauses;+static uint16_t rail_mv;+static bool ads_ok;  typedef struct { uint64_t pair; uint32_t t_us; uint8_t level; } sync_evt_t; static sync_evt_t sync_q[SYNC_QUEUE];@@ -51,6 +85,184 @@ static volatile uint32_t sync_head, sync_tail, sync_count, sync_lost;  static uint8_t frame[SMI_HDR_LEN + 13 + (PAIRS_PER_BUF / SMI_BLOCK) * 2 * SMI_MAX_BLOCK_BYTES + 2]; static uint16_t seq;+static smi_ctl_t ctl;++#define I2C_INST (SMI_I2C_BUS ? i2c1 : i2c0)++// ---------------------------------------------------------------- hardware --++static bool ads_prepare(void);++// Read the DAC121C085's register: two bytes, high first; bits 13:12 the+// power-down mode (0 = normal), bits 11:0 the code.+static bool head_dac_read(uint8_t addr, uint16_t *reg) {+    uint8_t r[2];+    if (i2c_read_timeout_us(I2C_INST, addr, r, 2, false, I2C_TIMEOUT_US) != 2) return false;+    *reg = (uint16_t)((r[0] << 8) | r[1]);+    return true;+}++// part 1, DAC7574 (TI, quad 12-bit, I2C, outputs reset to zero at power-up).+// Control byte: L1 L0 = 01 (update the selected channel), Sel1 Sel0 =+// channel, PD0 = 0; then D11..D4 and D3..D0 left-aligned in the second byte.+// part 2, DAC121C085 (TI, 12-bit, on the laser head, powers up at code 0):+// two bytes, high first, power-down bits 13:12 = 00, then the code; the write+// only counts if the register read straight back matches exactly.+static bool dac_write(void *ctx, uint8_t dev, uint8_t ch, uint16_t code) {+    (void)ctx;+    if (dev >= SMI_NUM_DACS) return false;+    const smi_dac_def_t *d = &smi_dacs[dev];+    if (d->part == 1) {+        uint8_t b[3] = { (uint8_t)(0x10 | ((ch & 3) << 1)), (uint8_t)(code >> 4), (uint8_t)((code & 0x0F) << 4) };+        return i2c_write_timeout_us(I2C_INST, d->addr, b, 3, false, I2C_TIMEOUT_US) == 3;+    }+    if (d->part == 2) {+        // The core has already dropped GP6 and waited disarm_us. Before arming at+        // a nonzero code, (re)configure the head ADC: its config and pointer may+        // only be written while disarmed; armed access to it is read-only.+        if (code && !(ads_ok = ads_prepare())) return false;+        uint8_t b[2] = { (uint8_t)((code >> 8) & 0x0F), (uint8_t)code };+        if (i2c_write_timeout_us(I2C_INST, d->addr, b, 2, false, I2C_TIMEOUT_US) != 2) return false;+        uint16_t reg;+        return head_dac_read(d->addr, &reg) && reg == (code & 0x0FFF);+    }+    return false;+}++// MCP23008 on the laser head: the switch bits. Its pins reset to inputs and the+// head's pull-downs hold every selector at its power-on default (code 0); the+// firmware writes OLAT first, then makes only the mapped bits outputs.+#define MCP_IODIR 0x00+#define MCP_OLAT 0x0A+static uint8_t exp_olat, exp_mask;+static bool exp_ok;++static bool exp_write(uint8_t reg, uint8_t v) {+    uint8_t b[2] = { reg, v };+    return i2c_write_timeout_us(I2C_INST, SMI_EXP_ADDR, b, 2, false, I2C_TIMEOUT_US) == 2;+}++static bool exp_read(uint8_t reg, uint8_t *v) {+    return i2c_write_timeout_us(I2C_INST, SMI_EXP_ADDR, &reg, 1, true, I2C_TIMEOUT_US) == 1 &&+           i2c_read_timeout_us(I2C_INST, SMI_EXP_ADDR, v, 1, false, I2C_TIMEOUT_US) == 1;+}++static void exp_init(void) {+    exp_mask = 0;+    for (int i = 0; i < SMI_NUM_CONTROLS; i++)+        for (int b = 0; b < smi_controls[i].ngpio; b++)+            if (smi_controls[i].gpio[b] >= SMI_EXP_BASE) exp_mask |= (uint8_t)(1u << (smi_controls[i].gpio[b] - SMI_EXP_BASE));+    exp_olat = 0;+    uint8_t dir = 0;+    // Verify the head interface: the IODIR read-back must match what was written.+    exp_ok = !SMI_EXP_PRESENT || (exp_write(MCP_OLAT, 0) && exp_write(MCP_IODIR, (uint8_t)~exp_mask) &&+                                  exp_read(MCP_IODIR, &dir) && dir == (uint8_t)~exp_mask);+}++// Laser enable: with a carrier the "on" state is a 10 kHz square wave from the+// pin's PWM slice; "off" returns the pin to a plain output driven inactive.+static void laser_enable_out(bool on) {+#if SMI_LASER_EN_CARRIER_HZ+    uint slice = pwm_gpio_to_slice_num(SMI_LASER_EN_GPIO);+    if (on) {+        uint32_t wrap = clock_get_hz(clk_sys) / SMI_LASER_EN_CARRIER_HZ - 1u;+        pwm_set_wrap(slice, (uint16_t)wrap);+        pwm_set_gpio_level(SMI_LASER_EN_GPIO, (uint16_t)((wrap + 1u) / 2u));+        pwm_set_enabled(slice, true);+        gpio_set_function(SMI_LASER_EN_GPIO, GPIO_FUNC_PWM);+    } else {+        gpio_set_function(SMI_LASER_EN_GPIO, GPIO_FUNC_SIO);+        gpio_put(SMI_LASER_EN_GPIO, SMI_LASER_EN_ACTIVE_HIGH ? 0 : 1);+        gpio_set_dir(SMI_LASER_EN_GPIO, GPIO_OUT);+        pwm_set_enabled(slice, false);+    }+#else+    gpio_put(SMI_LASER_EN_GPIO, on == (bool)SMI_LASER_EN_ACTIVE_HIGH);+#endif+}++static void hal_wait_us(void *ctx, uint32_t us) {+    (void)ctx;+    busy_wait_us_32(us);+}++static bool hal_dac_read(void *ctx, uint8_t dev, uint16_t *reg) {+    (void)ctx;+    return dev < SMI_NUM_DACS && smi_dacs[dev].part == 2 && head_dac_read(smi_dacs[dev].addr, reg);+}++static bool gpio_out(void *ctx, uint8_t pin, bool level) {+    (void)ctx;+    if (pin == SMI_LASER_EN_GPIO) {+        laser_enable_out(level == (bool)SMI_LASER_EN_ACTIVE_HIGH);+        return true;+    }+    if (pin < SMI_EXP_BASE) {+        gpio_put(pin, level);+        return true;+    }+    if (!SMI_EXP_PRESENT || !exp_ok) return false;+    uint8_t bit = (uint8_t)(1u << (pin - SMI_EXP_BASE));+    uint8_t v = level ? (exp_olat | bit) : (exp_olat & (uint8_t)~bit);+    if (!exp_write(MCP_OLAT, v)) return false;+    exp_olat = v;+    return true;+}++// ADS1115 on the laser head: continuous conversion of the shunt voltage.+#define ADS_REG_CONV 0x00+#define ADS_REG_CONFIG 0x01++// Write the config, check it, then leave the pointer on the conversion+// register so that every later read is a plain two-byte read. Only while the+// laser is disarmed (board contract: armed access is read-only).+static bool ads_prepare(void) {+    uint8_t w[3] = { ADS_REG_CONFIG, (uint8_t)(SMI_ADS_CONFIG >> 8), (uint8_t)SMI_ADS_CONFIG };+    if (i2c_write_timeout_us(I2C_INST, SMI_ADS_ADDR, w, 3, false, I2C_TIMEOUT_US) != 3) return false;+    uint8_t reg = ADS_REG_CONFIG, r[2];+    if (i2c_write_timeout_us(I2C_INST, SMI_ADS_ADDR, &reg, 1, true, I2C_TIMEOUT_US) != 1) return false;+    if (i2c_read_timeout_us(I2C_INST, SMI_ADS_ADDR, r, 2, false, I2C_TIMEOUT_US) != 2) return false;+    // Read-back check, ignoring the OS (conversion status) bit.+    if ((((r[0] << 8) | r[1]) & 0x7FFF) != (SMI_ADS_CONFIG & 0x7FFF)) return false;+    reg = ADS_REG_CONV;+    return i2c_write_timeout_us(I2C_INST, SMI_ADS_ADDR, &reg, 1, false, I2C_TIMEOUT_US) == 1;+}++// A plain read of the conversion register (the pointer was left there).+static bool ads_read(int32_t *v) {+    uint8_t r[2];+    if (i2c_read_timeout_us(I2C_INST, SMI_ADS_ADDR, r, 2, false, I2C_TIMEOUT_US) != 2) return false;+    *v = (int16_t)((r[0] << 8) | r[1]);+    return true;+}++static void outputs_init(void) {+    // Laser enable first, driven off, before anything else can happen.+    gpio_init(SMI_LASER_EN_GPIO);+    gpio_put(SMI_LASER_EN_GPIO, SMI_LASER_EN_ACTIVE_HIGH ? 0 : 1);+    gpio_set_dir(SMI_LASER_EN_GPIO, GPIO_OUT);+    for (int i = 0; i < SMI_NUM_CONTROLS; i++) {+        const smi_control_def_t *d = &smi_controls[i];+        for (int b = 0; b < d->ngpio; b++) {+            if (d->gpio[b] >= SMI_EXP_BASE) continue;+            gpio_init(d->gpio[b]);+            gpio_put(d->gpio[b], 0);+            gpio_set_dir(d->gpio[b], GPIO_OUT);+        }+    }+    i2c_init(I2C_INST, SMI_I2C_HZ);+    gpio_set_function(SMI_I2C_SDA, GPIO_FUNC_I2C);+    gpio_set_function(SMI_I2C_SCL, GPIO_FUNC_I2C);+    gpio_pull_up(SMI_I2C_SDA);+    gpio_pull_up(SMI_I2C_SCL);+    // DAC channel A (laser set-point) to zero before configuring anything else.+    for (int i = 0; i < SMI_NUM_CONTROLS; i++)+        if (smi_controls[i].is_laser) dac_write(NULL, smi_controls[i].dac, smi_controls[i].ch, 0);+    exp_init();+    ads_ok = ads_prepare();+}++// ------------------------------------------------------------- acquisition --  static void dma_irq(void) {     uint32_t mask = dma_hw->ints0;@@ -123,7 +335,7 @@ static void acq_start(void) {     dma_channel_abort(dma_a);     dma_channel_abort(dma_b);     adc_fifo_drain();-    bufs_done = 0; bufs_sent = 0; dropped_bufs = 0;+    bufs_done = 0; bufs_sent = 0; dropped_bufs = 0; isense_pauses = 0;     sync_head = sync_tail = sync_count = 0;     dma_channel_set_write_addr(dma_a, bufs[0], false);     dma_channel_set_trans_count(dma_a, SAMPLES_PER_BUF, false);@@ -144,15 +356,88 @@ static void acq_stop(void) {     adc_fifo_drain(); } -// Blocking-with-service write of a whole frame to CDC.+static void adc_wait_ready(void) {+    while (!(adc_hw->cs & ADC_CS_READY_BITS)) tight_loop_contents();+}++// Four ADC2 conversions with the FIFO off, so nothing lands in the sample ring.+static uint16_t adc2_convert(void) {+    adc_fifo_setup(false, false, 1, false, false);+    adc_set_round_robin(0);+    adc_select_input(2);+    uint32_t sum = 0;+    for (int i = 0; i < 4; i++) sum += adc_read();+    adc_select_input(0);+    adc_fifo_setup(true, true, 1, false, false);+    return (uint16_t)((sum + 2) / 4);+}++// Read ADC2 (the analog rail). While streaming, stop the round robin after a+// complete ch0/ch1 pair so the even/odd interleave in the ring is preserved.+static uint16_t adc2_read(void) {+    if (!running) {+        uint16_t v = adc2_convert();+        adc_set_round_robin(0x3);+        return v;+    }+    adc_run(false);+    busy_wait_us_32(3);                 // let a conversion already started finish+    adc_wait_ready();+    while (adc_fifo_get_level()) tight_loop_contents();   // DMA takes the last sample+    if (adc_get_selected_input() == 1) {+        // The last stored sample was ch0: convert ch1 once to complete the pair.+        hw_set_bits(&adc_hw->cs, ADC_CS_START_ONCE_BITS);+        busy_wait_us_32(1);+        adc_wait_ready();+        while (adc_fifo_get_level()) tight_loop_contents();+    }+    uint16_t v = adc2_convert();+    adc_set_round_robin(0x3);+    isense_pauses++;+    adc_run(true);+    return v;+}++// ----------------------------------------------------------------- USB out --++// Laser upkeep, called from every loop that can take time (the main loop,+// between DATA frames, and while waiting on USB): the ramp tick and, while+// armed, the head DAC readback every 2 ms. The readback is also the I2C+// traffic that keeps the head's watchdog from dropping the laser gate.+static void laser_service(void) {+    static uint32_t next_poll;+    uint32_t now = time_us_32();+    smi_ctl_tick(&ctl, now);+#if SMI_LASER_READBACK_POLL_MS+    if (ctl.laser_on && (int32_t)(now - next_poll) >= 0) {+        next_poll = now + SMI_LASER_READBACK_POLL_MS * 1000u;+        int li = 0;+        for (int i = 0; i < SMI_NUM_CONTROLS; i++)+            if (smi_controls[i].is_laser) li = i;+        uint16_t reg = 0;+        bool ok = head_dac_read(smi_dacs[smi_controls[li].dac].addr, &reg);+        smi_ctl_laser_readback(&ctl, ok, reg, time_us_32());+    }+#endif+}++// Write a whole frame to CDC; gives up if the host stops reading for 50 ms. static bool cdc_write_all(const uint8_t *p, size_t n) {+    uint32_t t0 = time_us_32();     while (n) {+        watchdog_update();         if (!tud_cdc_connected()) return false;         uint32_t avail = tud_cdc_write_available();-        if (avail == 0) { tud_task(); continue; }+        if (avail == 0) {+            tud_task();+            laser_service();+            if (time_us_32() - t0 > 50000u) return false;+            continue;+        }         uint32_t k = n < avail ? (uint32_t)n : avail;         k = tud_cdc_write(p, k);         p += k; n -= k;+        t0 = time_us_32();         tud_cdc_write_flush();         tud_task();     }@@ -176,64 +461,111 @@ static void send_data(uint32_t b) {     cdc_write_all(frame, n); } +static void send_small(uint8_t type, const uint8_t *payload, uint16_t len) {+    uint8_t f[SMI_HDR_LEN + 240 + 2];+    if (len > 240) return;+    memcpy(f + SMI_HDR_LEN, payload, len);+    smi_begin_frame(f, type, len, seq++);+    cdc_write_all(f, smi_finish_frame(f, len));+}+ static void send_sync(const sync_evt_t *e) {-    uint8_t f[SMI_HDR_LEN + 13 + 2];-    uint8_t *pl = f + SMI_HDR_LEN;+    uint8_t pl[13];     smi_put_u64(pl, e->pair);     smi_put_u32(pl + 8, e->t_us);     pl[12] = e->level;-    smi_begin_frame(f, SMI_T_SYNC, 13, seq++);-    cdc_write_all(f, smi_finish_frame(f, 13));+    send_small(SMI_T_SYNC, pl, 13); }  static void send_status(void) {-    uint8_t f[SMI_HDR_LEN + 24 + 2];-    uint8_t *pl = f + SMI_HDR_LEN;+    uint8_t pl[30];     smi_put_u64(pl, (uint64_t)bufs_done * PAIRS_PER_BUF);     smi_put_u32(pl + 8, dropped_bufs);     smi_put_u32(pl + 12, sync_lost);     smi_put_u32(pl + 16, TOTAL_SPS);     smi_put_u32(pl + 20, time_us_32());-    smi_begin_frame(f, SMI_T_STATUS, 24, seq++);-    cdc_write_all(f, smi_finish_frame(f, 24));+    smi_put_u32(pl + 24, isense_pauses);+    smi_put_u16(pl + 28, rail_mv);+    send_small(SMI_T_STATUS, pl, 30);+}++static void send_state(void) {+    uint8_t pl[30 + 6 * SMI_MAX_CONTROLS];+    size_t n = smi_ctl_state(&ctl, time_us_32(), pl);+    send_small(SMI_T_STATE, pl, (uint16_t)n); }  static void send_info(void) {-    char txt[160];+    char txt[240];     int n = snprintf(txt, sizeof txt,-        "smi-pico fw " FW_VERSION "; total_sps=%u; per_channel_sps=%u; pairs_per_frame=%u; block=%u; sync_gpio=%u",-        TOTAL_SPS, TOTAL_SPS / 2, PAIRS_PER_BUF, SMI_BLOCK, SYNC_GPIO);-    uint8_t f[SMI_HDR_LEN + 160 + 2];-    memcpy(f + SMI_HDR_LEN, txt, (size_t)n);-    smi_begin_frame(f, SMI_T_INFO, (uint16_t)n, seq++);-    cdc_write_all(f, smi_finish_frame(f, (uint16_t)n));+        "smi-pico fw " FW_VERSION "; total_sps=%u; per_channel_sps=%u; pairs_per_frame=%u; block=%u; sync_gpio=%u; "+        "map=" SMI_MAP_VERSION "; map_hash=%08lx; controls=%u; head_io=%s; head_adc=%s; boot=%s",+        TOTAL_SPS, TOTAL_SPS / 2, PAIRS_PER_BUF, SMI_BLOCK, SYNC_GPIO, (unsigned long)SMI_MAP_HASH,+        (unsigned)SMI_NUM_CONTROLS, exp_ok ? "ok" : "not answering", ads_ok ? "ok" : "not answering", ctl.boot_reason == SMI_OFF_WATCHDOG ? "watchdog" : "power-on");+    send_small(SMI_T_INFO, (const uint8_t *)txt, (uint16_t)n);+}++// -------------------------------------------------------------- commands in --++static uint8_t rx[8 + 160 + 2];+static int rx_len;++static void handle_cmd_frame(void) {+    uint16_t len = (uint16_t)(rx[4] | (rx[5] << 8));+    uint16_t crc = (uint16_t)(rx[8 + len] | (rx[9 + len] << 8));+    if (smi_crc16(rx + 2, 6u + len, 0xFFFF) != crc || rx[2] != SMI_T_CMD) return;   // host retries on timeout+    uint16_t cseq = (uint16_t)(rx[6] | (rx[7] << 8));+    uint8_t resp[160];+    size_t n = smi_ctl_command(&ctl, rx + 8, len, cseq, time_us_32(), resp);+    send_small(SMI_T_ACK, resp, (uint16_t)n); } -static char cmd[32];-static int cmd_len;+// Text commands (board contract): smi_text.c, wired to this firmware.+static uint32_t text_now(void *ctx) { (void)ctx; return time_us_32(); }+static void text_send(void *ctx, const char *t) { (void)ctx; send_small(SMI_T_INFO, (const uint8_t *)t, (uint16_t)strlen(t)); }+static void text_start(void *ctx) { (void)ctx; acq_start(); }+static void text_stop(void *ctx) { (void)ctx; acq_stop(); }+static void text_info(void *ctx) { (void)ctx; send_info(); }+static smi_text_t textcmd = { .ctl = &ctl, .now_us = text_now, .reply = text_send, .start = text_start,+                              .stop = text_stop, .info = text_info, .exp_base = SMI_EXP_BASE, .gain_base = 7 };  static void poll_commands(void) {     while (tud_cdc_available()) {         int c = tud_cdc_read_char();         if (c < 0) break;-        if (c == '\n' || c == '\r') {-            cmd[cmd_len] = 0;-            if (!strcmp(cmd, "start")) acq_start();-            else if (!strcmp(cmd, "stop")) acq_stop();-            else if (!strcmp(cmd, "info")) send_info();-            cmd_len = 0;-        } else if (cmd_len < (int)sizeof cmd - 1) {-            cmd[cmd_len++] = (char)c;+        if (rx_len > 0 || (c == SMI_SYNC0 && textcmd.len == 0)) {+            rx[rx_len++] = (uint8_t)c;+            if (rx_len == 2 && c != SMI_SYNC1) { rx_len = 0; continue; }+            if (rx_len >= 6) {+                uint16_t len = (uint16_t)(rx[4] | (rx[5] << 8));+                if (len > 160) { rx_len = 0; continue; }+                if (rx_len == 8 + len + 2) { handle_cmd_frame(); rx_len = 0; }+            }+            continue;         }+        smi_text_feed(&textcmd, (char)c);     } } +static volatile bool usb_gone;+void tud_umount_cb(void) { usb_gone = true; }+void tud_suspend_cb(bool remote_wakeup_en) { (void)remote_wakeup_en; usb_gone = true; }++// -------------------------------------------------------------------- main --+ int main(void) {+    bool wdt = watchdog_caused_reboot();+    outputs_init();+    smi_hal_t hal = { .ctx = NULL, .dac_write = dac_write, .wait_us = hal_wait_us, .dac_read = hal_dac_read, .gpio_put = gpio_out };+    smi_ctl_init(&ctl, smi_controls, SMI_NUM_CONTROLS, &smi_isense, SMI_MAP_HASH, SMI_MAP_VERSION,+                 SMI_LASER_EN_GPIO, SMI_LASER_EN_ACTIVE_HIGH, &hal, wdt ? SMI_OFF_WATCHDOG : SMI_OFF_BOOT, time_us_32());+     tusb_init();      adc_init();     adc_gpio_init(26);     adc_gpio_init(27);+    adc_gpio_init(RAIL_GPIO);     // FIFO on, DREQ on, DREQ threshold 1, no error bit, no byte shift (12-bit samples).     adc_fifo_setup(true, true, 1, false, false);     adc_set_clkdiv(0);                 // back-to-back: 96 ADC clocks = 2 us per conversion@@ -244,14 +576,36 @@ int main(void) {     gpio_disable_pulls(SYNC_GPIO);     // R151 on the board holds the buffer input low     gpio_set_irq_enabled_with_callback(SYNC_GPIO, GPIO_IRQ_EDGE_RISE | GPIO_IRQ_EDGE_FALL, true, sync_irq); +    watchdog_enable(WATCHDOG_MS, true);+     bool was_connected = false;-    uint32_t last_status = 0;+    uint32_t last_status = 0, last_state = 0, next_isense = time_us_32(), next_rail = time_us_32();     while (true) {+        watchdog_update();         tud_task();+        uint32_t now = time_us_32();         bool conn = tud_cdc_connected();+        if (usb_gone) {+            usb_gone = false;+            smi_ctl_link_lost(&ctl, SMI_OFF_USB);+        }         if (conn && !was_connected) { send_info(); acq_start(); }-        if (!conn && was_connected) acq_stop();+        if (!conn && was_connected) { acq_stop(); smi_ctl_link_lost(&ctl, SMI_OFF_USB); }         was_connected = conn;++        if ((int32_t)(now - next_isense) >= 0) {+            next_isense += 1000000u / (ctl.isense_hz ? ctl.isense_hz : 10);+            if ((int32_t)(now - next_isense) > 0) next_isense = now;   // fell behind: no burst+            int32_t raw;+            if (!ads_ok && !ctl.laser_on) ads_ok = ads_prepare();     // the head may be plugged in late; only while disarmed+            if (ads_ok && ads_read(&raw)) smi_ctl_isense(&ctl, raw, time_us_32());+            else { ads_ok = false; smi_ctl_isense_failed(&ctl, time_us_32()); }+        }+        if ((int32_t)(now - next_rail) >= 0) {+            next_rail = now + 1000000u;+            rail_mv = (uint16_t)(adc2_read() * SMI_RAIL_SCALE * 1000.0f + 0.5f);+        }+        laser_service();         if (!conn) continue;         poll_commands(); @@ -273,9 +627,12 @@ int main(void) {             }             send_data(bufs_sent);             bufs_sent++;+            poll_commands();               // commands are answered between frames+            laser_service();         } -        uint32_t now = time_us_32();+        now = time_us_32();         if (now - last_status > 500000) { last_status = now; send_status(); }+        if (now - last_state > 250000) { last_state = now; send_state(); }     } }
software/firmware/src/smi_controls_gen.hadded+43
@@ -0,0 +1,43 @@+// SPDX-License-Identifier: MIT+// GENERATED by controls/gen_controls.py from the board's control map. Do not edit.+// map_version 1.2.0-revision-1.2-controller-contract+#ifndef SMI_CONTROLS_GEN_H+#define SMI_CONTROLS_GEN_H+#include "smi_ctl.h"++#define SMI_MAP_HASH 0x0F78D131u+#define SMI_MAP_VERSION "1.2.0-revision-1.2-controller-contract"+#define SMI_I2C_BUS 0+#define SMI_I2C_SDA 4+#define SMI_I2C_SCL 5+#define SMI_I2C_HZ 100000u+#define SMI_LASER_EN_GPIO 6+#define SMI_LASER_EN_ACTIVE_HIGH 1+#define SMI_LASER_EN_CARRIER_HZ 10000u   /* 0 = a static level */+#define SMI_LASER_READBACK_POLL_MS 2u   /* 0 = no readback polling */+#define SMI_NUM_DACS 2+#define SMI_EXP_PRESENT 1+#define SMI_EXP_ADDR 0x20+#define SMI_EXP_BASE 32+static const smi_dac_def_t smi_dacs[SMI_NUM_DACS] = {+    { .part = 1, .addr = 0x4C, .bits = 12, .vref = 3.3f },+    { .part = 2, .addr = 0x09, .bits = 12, .vref = 2.5f },+};+// Laser current: ADS1115 at 0x49, AIN0-AIN1, +/-0.512 V, 128 SPS, continuous+#define SMI_ADS_ADDR 0x49+#define SMI_ADS_CONFIG 0x8883u+static const smi_isense_def_t smi_isense = { .ma_per_code = 0.0078125f, .offset_ma = 0.0f, .trip_ma = 116.0f, .rate_hz = 50, .zero_cal = 1 };+#define SMI_RAIL_PRESENT 1+#define SMI_RAIL_SCALE 0.001611328125f /* volts per ADC2 code */+#define SMI_NUM_CONTROLS 8+static const smi_control_def_t smi_controls[SMI_NUM_CONTROLS] = {+    /* laserCurrent */ { .kind = 1, .unit = 0, .is_laser = 1, .needs_off = 0, .min = 0.0f, .max = 109.16269930424299f, .def = 0.0f, .dac = 1, .ch = 0, .bits = 12, .per_code = 0.0269537529146279f, .at_zero = 0.0f, .ramp_per_s = 0.0f, .rated = 135.0f, .gate = 1, .min_write_us = 250000u, .disarm_us = 2000u, .max_code = 4050, .guard = 45 },+    /* monitorOffset */ { .kind = 1, .unit = 1, .is_laser = 0, .needs_off = 1, .min = 0.0f, .max = 3.299194f, .def = 0.0f, .dac = 0, .ch = 1, .bits = 12, .per_code = 0.0008056640625f, .at_zero = 0.0f, .ramp_per_s = 0.0f },+    /* externalOffset */ { .kind = 1, .unit = 1, .is_laser = 0, .needs_off = 1, .min = 0.0f, .max = 3.299194f, .def = 0.0f, .dac = 0, .ch = 2, .bits = 12, .per_code = 0.0008056640625f, .at_zero = 0.0f, .ramp_per_s = 0.0f },+    /* headTiaGain */ { .kind = 2, .unit = 2, .is_laser = 0, .needs_off = 1, .min = 1000.0f, .max = 4700.0f, .def = 1000.0f, .ngpio = 1, .gpio = {32}, .nset = 2, .set_code = {0, 1}, .set_value = {1000.0f, 4700.0f} },+    /* monitorSecondStageGain */ { .kind = 2, .unit = 4, .is_laser = 0, .needs_off = 1, .min = -20.0f, .max = -5.0f, .def = -5.0f, .ngpio = 1, .gpio = {7}, .nset = 2, .set_code = {0, 1}, .set_value = {-5.0f, -20.0f} },+    /* externalTiaGain */ { .kind = 2, .unit = 2, .is_laser = 0, .needs_off = 1, .min = 46836.0f, .max = 150000.0f, .def = 46836.0f, .ngpio = 1, .gpio = {9}, .nset = 2, .set_code = {0, 1}, .set_value = {46836.0f, 150000.0f} },+    /* externalSecondStageGain */ { .kind = 2, .unit = 4, .is_laser = 0, .needs_off = 1, .min = -20.0f, .max = -5.0f, .def = -5.0f, .ngpio = 1, .gpio = {8}, .nset = 2, .set_code = {0, 1}, .set_value = {-5.0f, -20.0f} },+    /* headMonitorBias */ { .kind = 2, .unit = 1, .is_laser = 0, .needs_off = 1, .min = 0.252f, .max = 4.649f, .def = 0.252f, .ngpio = 2, .gpio = {33, 34}, .nset = 4, .set_code = {0, 1, 2, 3}, .set_value = {0.252f, 2.488f, 4.649f, 4.649f} },+};+#endif
software/firmware/src/smi_ctl.cadded+413
@@ -0,0 +1,413 @@+// SPDX-License-Identifier: MIT+#include "smi_ctl.h"+#include <string.h>++static void put16(uint8_t *p, uint16_t v) { p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); }+static void put32(uint8_t *p, uint32_t v) { for (int i = 0; i < 4; i++) p[i] = (uint8_t)(v >> (8 * i)); }+static void putf(uint8_t *p, float f) { uint32_t u; memcpy(&u, &f, 4); put32(p, u); }+static uint16_t get16(const uint8_t *p) { return (uint16_t)(p[0] | (p[1] << 8)); }+static uint32_t get32(const uint8_t *p) { return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); }+static float getf(const uint8_t *p) { uint32_t u = get32(p); float f; memcpy(&f, &u, 4); return f; }+static float fabsf_(float x) { return x < 0 ? -x : x; }++uint16_t smi_ctl_code_for(const smi_control_def_t *d, float v) {+    float x = (v - d->at_zero) / d->per_code;+    float top = (float)(d->max_code ? d->max_code : (1u << d->bits) - 1u);+    if (x < 0) x = 0;+    if (x > top) x = top;+    return (uint16_t)(x + 0.5f);+}++float smi_ctl_value_of(const smi_control_def_t *d, uint16_t code) {+    return d->at_zero + (float)code * d->per_code;+}++static int laser_index(const smi_ctl_t *c) {+    for (int i = 0; i < c->n; i++)+        if (c->defs[i].is_laser) return i;+    return -1;+}++static void en_pin(smi_ctl_t *c, bool on) {+    (void)c->hal.gpio_put(c->hal.ctx, c->laser_en_gpio, on ? c->laser_en_active_high : !c->laser_en_active_high);+}++static bool put_switch(smi_ctl_t *c, int i, uint8_t code) {+    const smi_control_def_t *d = &c->defs[i];+    bool ok = true;+    for (int b = 0; b < d->ngpio; b++) ok &= c->hal.gpio_put(c->hal.ctx, d->gpio[b], (code >> b) & 1);+    if (ok) c->code[i] = code;+    return ok;+}++static bool put_dac(smi_ctl_t *c, int i, uint16_t code) {+    const smi_control_def_t *d = &c->defs[i];+    if (d->gate) {+        en_pin(c, false);                     // drop the enable before writing+        if (c->hal.wait_us && d->disarm_us) c->hal.wait_us(c->hal.ctx, d->disarm_us);+    }+    bool ok = c->hal.dac_write(c->hal.ctx, d->dac, d->ch, code);+    if (ok) c->code[i] = code;+    // Re-assert only after a verified write of a nonzero code, and only if armed;+    // then read back once more (the head watchdog wants fresh SCL after enable).+    if (d->gate && ok && c->laser_on && code != 0) {+        en_pin(c, true);+        uint16_t reg;+        if (c->hal.dac_read && !(c->hal.dac_read(c->hal.ctx, d->dac, &reg) && ((reg >> 12) & 3u) == 0 && (reg & 0x0FFFu) == code)) {+            en_pin(c, false);+            return false;+        }+    }+    return ok;+}++static void laser_off(smi_ctl_t *c, uint8_t reason) {+    int li = laser_index(c);+    en_pin(c, false);                 // the hardware enable goes first+    if (c->laser_on) c->off_since_us = c->last_tick_us;+    c->laser_on = false;+    c->laser_now = 0;+    c->laser_ua = 0;+    c->ramp_rem = 0;+    c->off_reason = reason;+    if (li >= 0) put_dac(c, li, smi_ctl_code_for(&c->defs[li], 0.0f));+}++static void fault(smi_ctl_t *c, uint8_t f, uint8_t reason) {+    c->fault = f;+    laser_off(c, reason);+}++void smi_ctl_init(smi_ctl_t *c, const smi_control_def_t *defs, uint8_t n, const smi_isense_def_t *is,+                  uint32_t map_hash, const char *map_version, uint8_t laser_en_gpio, bool laser_en_active_high,+                  const smi_hal_t *hal, uint8_t boot_reason, uint32_t now_us) {+    memset(c, 0, sizeof *c);+    c->defs = defs;+    c->n = n > SMI_MAX_CONTROLS ? SMI_MAX_CONTROLS : n;+    c->isense = is;+    c->map_hash = map_hash;+    c->map_version = map_version;+    c->laser_en_gpio = laser_en_gpio;+    c->laser_en_active_high = laser_en_active_high;+    c->hal = *hal;+    c->boot_reason = boot_reason;+    c->hb_timeout_ms = 3000;+    c->isense_hz = is->rate_hz ? is->rate_hz : 10;+    c->last_host_us = c->last_tick_us = now_us;+    en_pin(c, false);+    for (int i = 0; i < c->n; i++) {+        const smi_control_def_t *d = &defs[i];+        c->target[i] = d->def;+        if (d->kind == SMI_KIND_DAC) {+            if (!put_dac(c, i, smi_ctl_code_for(d, d->is_laser ? 0.0f : d->def))) c->fault = SMI_FAULT_HW;+        } else {+            uint8_t code = d->set_code[0];+            for (int k = d->nset - 1; k >= 0; k--)+                if (d->set_value[k] == d->def) code = d->set_code[k];+            if (!put_switch(c, i, code)) c->fault = SMI_FAULT_HW;   // head interface not answering+        }+    }+    c->off_reason = boot_reason;+    c->off_since_us = now_us;+}++static size_t ack(uint8_t *r, uint16_t seq, uint8_t op, uint8_t st) {+    put16(r, seq);+    r[2] = op;+    r[3] = st;+    return 4;+}++static size_t range_err(uint8_t *r, uint16_t seq, uint8_t op, float lo, float hi) {+    size_t o = ack(r, seq, op, SMI_E_RANGE);+    putf(r + o, lo);+    putf(r + o + 4, hi);+    return o + 8;+}++static size_t do_set(smi_ctl_t *c, const uint8_t *p, size_t n, uint16_t seq, uint8_t *r) {+    if (n < 7) return ack(r, seq, SMI_OP_SET, SMI_E_LEN);+    uint8_t i = p[1], mode = p[2];+    float v = getf(p + 3);+    if (i >= c->n) return ack(r, seq, SMI_OP_SET, SMI_E_CONTROL);+    const smi_control_def_t *d = &c->defs[i];+    if (v != v) return range_err(r, seq, SMI_OP_SET, d->min, d->max);   // NaN+    if (d->needs_off && c->laser_on) return ack(r, seq, SMI_OP_SET, SMI_E_LASER_ON);+    if (d->kind == SMI_KIND_DAC) {+        if (mode == 1) {+            float top = (float)((1u << d->bits) - 1u);+            if (v < 0 || v > top) return range_err(r, seq, SMI_OP_SET, 0, top);+            uint16_t cc = (uint16_t)(v + 0.5f);+            if (d->guard) cc = cc > d->guard ? (uint16_t)(cc - d->guard) : 0;   // command code -> DAC code+            v = smi_ctl_value_of(d, cc);+        } else if (mode != 0) {+            return ack(r, seq, SMI_OP_SET, SMI_E_MODE);+        }+        float tol = fabsf_(d->per_code) * 0.5f;+        float hi = d->max;+        if (d->is_laser && d->rated < hi) hi = d->rated;+        if (v < d->min - tol || v > hi + tol) return range_err(r, seq, SMI_OP_SET, d->min, hi);+        if (v > hi) v = hi;+        if (v < d->min) v = d->min;+        c->target[i] = v;+        if (!d->is_laser) {+            if (!put_dac(c, i, smi_ctl_code_for(d, v))) {+                fault(c, SMI_FAULT_HW, SMI_OFF_HW);+                return ack(r, seq, SMI_OP_SET, SMI_E_HW);+            }+        }+        // The laser set-point is applied by smi_ctl_tick at the ramp rate.+    } else {+        int k = -1;+        for (int j = d->nset - 1; j >= 0; j--) {   // first match wins (a map may list a value twice)+            if (mode == 0 && fabsf_(d->set_value[j] - v) <= fabsf_(d->set_value[j]) * 1e-3f) k = j;+            if (mode == 1 && (float)d->set_code[j] == v) k = j;+            if (mode == 2 && (float)j == v) k = j;+        }+        if (mode > 2) return ack(r, seq, SMI_OP_SET, SMI_E_MODE);+        if (k < 0) return range_err(r, seq, SMI_OP_SET, d->min, d->max);+        if (!put_switch(c, i, d->set_code[k])) {+            fault(c, SMI_FAULT_HW, SMI_OFF_HW);+            return ack(r, seq, SMI_OP_SET, SMI_E_HW);+        }+        c->target[i] = d->set_value[k];+    }+    size_t o = ack(r, seq, SMI_OP_SET, SMI_OK);+    r[o] = i;+    put16(r + o + 1, c->code[i]);+    float applied = d->is_laser ? c->laser_now : (d->kind == SMI_KIND_DAC ? smi_ctl_value_of(d, c->code[i]) : c->target[i]);+    putf(r + o + 3, applied);+    putf(r + o + 7, c->target[i]);+    return o + 11;+}++size_t smi_ctl_command(smi_ctl_t *c, const uint8_t *p, size_t n, uint16_t seq, uint32_t now_us, uint8_t *r) {+    if (n < 1) return ack(r, seq, 0, SMI_E_LEN);+    c->last_host_us = now_us;+    uint8_t op = p[0];+    switch (op) {+    case SMI_OP_GET_STATE: {+        size_t o = ack(r, seq, op, SMI_OK);+        return o + smi_ctl_state(c, now_us, r + o);+    }+    case SMI_OP_LASER_ENABLE: {+        if (n < 6) return ack(r, seq, op, SMI_E_LEN);+        if (!p[1]) {+            laser_off(c, SMI_OFF_HOST);+            return ack(r, seq, op, SMI_OK);+        }+        if (get32(p + 2) != SMI_LASER_KEY) return ack(r, seq, op, SMI_E_KEY);+        if (c->fault) return ack(r, seq, op, SMI_E_FAULT);+        // Startup rule: the current readback must have been validated at zero.+        if (c->isense->zero_cal ? c->zero_n < 8 : !c->isense_valid) return ack(r, seq, op, SMI_E_NOT_READY);+        int li = laser_index(c);+        if (li < 0) return ack(r, seq, op, SMI_E_CONTROL);+        if (!c->laser_on) {+            // Set-point to zero before the enable, then ramp up from there.+            if (!put_dac(c, li, smi_ctl_code_for(&c->defs[li], 0.0f))) {+                fault(c, SMI_FAULT_HW, SMI_OFF_HW);+                return ack(r, seq, op, SMI_E_HW);+            }+            c->laser_now = 0;+            c->laser_ua = 0;+            c->ramp_rem = 0;+            c->laser_on = true;+            c->off_reason = SMI_OFF_NONE;+            c->settled_since_us = now_us;+            c->last_tick_us = now_us;+            c->laser_write_us = now_us - c->defs[li].min_write_us;   // first write may go at once+            // A gated laser DAC asserts the enable on its first verified nonzero write.+            if (!c->defs[li].gate) en_pin(c, true);+        }+        return ack(r, seq, op, SMI_OK);+    }+    case SMI_OP_SET:+        return do_set(c, p, n, seq, r);+    case SMI_OP_READ_ISENSE: {+        size_t o = ack(r, seq, op, c->isense_valid ? SMI_OK : SMI_E_HW);+        putf(r + o, c->isense_ma);+        put16(r + o + 4, c->isense_raw);+        uint32_t age = (now_us - c->isense_us) / 1000u;+        put16(r + o + 6, (uint16_t)(age > 65535u ? 65535u : age));+        return o + 8;+    }+    case SMI_OP_HEARTBEAT:+        return ack(r, seq, op, SMI_OK);+    case SMI_OP_CLEAR_FAULT:+        c->fault = SMI_FAULT_NONE;+        c->over_n = c->offcur_n = 0;+        return ack(r, seq, op, SMI_OK);+    case SMI_OP_GET_MAP: {+        size_t o = ack(r, seq, op, SMI_OK);+        put32(r + o, c->map_hash);+        r[o + 4] = c->n;+        size_t l = strlen(c->map_version);+        if (l > 60) l = 60;+        memcpy(r + o + 5, c->map_version, l);+        return o + 5 + l;+    }+    case SMI_OP_CONFIG: {+        if (n < 4) return ack(r, seq, op, SMI_E_LEN);+        uint8_t hz = p[1];+        uint16_t hb = get16(p + 2);+        if (hz < 1 || hz > 50) return range_err(r, seq, op, 1, 50);+        if (hb < 500 || hb > 30000) return range_err(r, seq, op, 500, 30000);+        c->isense_hz = hz;+        c->hb_timeout_ms = hb;+        return ack(r, seq, op, SMI_OK);+    }+    default:+        return ack(r, seq, op, SMI_E_OP);+    }+}++void smi_ctl_tick(smi_ctl_t *c, uint32_t now_us) {+    int li = laser_index(c);+    uint32_t dt = now_us - c->last_tick_us;+    c->last_tick_us = now_us;+    if (dt > 10000u) dt = 10000u;     // a stalled loop slows the ramp, never speeds it+    if (li < 0) return;+    if (c->laser_on && c->hb_timeout_ms && (now_us - c->last_host_us) > (uint32_t)c->hb_timeout_ms * 1000u) {+        laser_off(c, SMI_OFF_HB_TIMEOUT);+        return;+    }+    if (!c->laser_on) return;+    const smi_control_def_t *d = &c->defs[li];+    if (d->gate) {+        // One verified write per set-point change, at most every min_write_us+        // (the latest request wins); the head's soft-start does the ramp.+        uint16_t tc = smi_ctl_code_for(d, c->target[li]);+        if (tc != c->code[li] && (now_us - c->laser_write_us) >= d->min_write_us) {+            c->laser_write_us = now_us;+            if (!put_dac(c, li, tc)) { fault(c, SMI_FAULT_READBACK, SMI_OFF_HW); return; }+            c->laser_now = smi_ctl_value_of(d, tc);+            c->laser_ua = (int32_t)(c->target[li] * 1000.0f);+            c->settled_since_us = now_us;+        } else if (tc == c->code[li]) {+            c->laser_ua = (int32_t)(c->target[li] * 1000.0f);   // nothing to write: arrived+        }+        return;+    }+    int32_t goal = (int32_t)(c->target[li] * 1000.0f);+    // Integer microamps: step = floor(rate * dt) with the remainder carried, so+    // the set-point is never ahead of ramp_per_s, however the loop is timed.+    uint64_t acc = (uint64_t)(uint32_t)(d->ramp_per_s * 1000.0f) * dt + c->ramp_rem;+    int32_t step = (int32_t)(acc / 1000000u);+    c->ramp_rem = (uint32_t)(acc % 1000000u);+    int32_t now = c->laser_ua;+    if (now < goal) now = (goal - now > step) ? now + step : goal;+    else if (now > goal) now = (now - goal > step) ? now - step : goal;+    if (now == goal) c->ramp_rem = 0;+    if (now != c->laser_ua) {+        c->laser_ua = now;+        c->laser_now = (float)now / 1000.0f;+        c->settled_since_us = now_us;+    }+    // The DAC follows the set-point, at most every min_write_us during a ramp+    // (always at once when the ramp arrives), so it never runs ahead of it.+    uint16_t code = smi_ctl_code_for(d, c->laser_now);+    if (code != c->code[li] && (now == goal || (now_us - c->laser_write_us) >= d->min_write_us)) {+        c->laser_write_us = now_us;+        if (!put_dac(c, li, code)) fault(c, SMI_FAULT_HW, SMI_OFF_HW);+    }+}++void smi_ctl_laser_readback(smi_ctl_t *c, bool ok, uint16_t reg, uint32_t now_us) {+    (void)now_us;+    int li = laser_index(c);+    if (li < 0 || !c->laser_on) return;+    if (!ok || ((reg >> 12) & 3u) != 0 || (reg & 0x0FFFu) != c->code[li]) {+        fault(c, SMI_FAULT_READBACK, SMI_OFF_HW);+        return;+    }+    c->readbacks++;+}++void smi_ctl_isense_failed(smi_ctl_t *c, uint32_t now_us) {+    (void)now_us;+    c->isense_valid = false;+    if (++c->isense_fail_n >= 3 && c->laser_on) fault(c, SMI_FAULT_ISENSE, SMI_OFF_HW);+}++void smi_ctl_isense(smi_ctl_t *c, int32_t raw, uint32_t now_us) {+    const smi_isense_def_t *s = c->isense;+    const float ma_per_code = s->ma_per_code;+    c->isense_fail_n = 0;+    // Zero calibration: with the laser off for 300 ms, a reading within about+    // 6 mA of zero is taken as the zero code (mean of the first 8, then a slow+    // average). More than that with the laser off counts towards a fault.+    bool quiet = !c->laser_on && (now_us - c->off_since_us) > 300000u;+    float zero = s->zero_cal ? c->zero_raw : 0.0f;+    if (s->zero_cal && quiet) {+        float m = (float)raw * ma_per_code;+        if (m < 6.0f && m > -6.0f) {+            if (c->zero_n < 8) c->zero_raw = (c->zero_raw * c->zero_n + raw) / (float)(c->zero_n + 1);+            else c->zero_raw += ((float)raw - c->zero_raw) / 16.0f;+            if (c->zero_n < 65535) c->zero_n++;+            zero = c->zero_raw;+        }+    }+    float ma = ((float)raw - zero) * ma_per_code + s->offset_ma;+    c->isense_ma = ma;+    c->isense_raw = (int16_t)(raw > 32767 ? 32767 : raw < -32768 ? -32768 : raw);+    c->isense_us = now_us;+    c->isense_valid = true;+    if (ma > s->trip_ma) {+        if (++c->over_n >= 3) fault(c, SMI_FAULT_OVERCURRENT, SMI_OFF_OVERCURRENT);+    } else {+        c->over_n = 0;+    }+    if (quiet && ma > 5.0f) {+        if (++c->offcur_n >= 5) c->fault = SMI_FAULT_CURRENT_WHEN_OFF;+    } else {+        c->offcur_n = 0;+    }+    int li = laser_index(c);+    bool settled = c->laser_on && li >= 0 && c->laser_ua == (int32_t)(c->target[li] * 1000.0f) && (now_us - c->settled_since_us) > 300000u;+    c->track_warn = settled && fabsf_(ma - c->laser_now) > 5.0f + 0.1f * c->laser_now;+}++void smi_ctl_link_lost(smi_ctl_t *c, uint8_t reason) {+    int li = laser_index(c);+    laser_off(c, reason);+    if (li >= 0) c->target[li] = 0;+}++size_t smi_ctl_state(const smi_ctl_t *c, uint32_t now_us, uint8_t *r) {+    int li = laser_index(c);+    put32(r, c->map_hash);+    uint8_t f = 0;+    if (c->laser_on) f |= SMI_FLAG_LASER_ON;+    if (li >= 0 && c->laser_on && c->laser_ua != (int32_t)(c->target[li] * 1000.0f)) f |= SMI_FLAG_RAMPING;+    if (c->fault) f |= SMI_FLAG_FAULT;+    if (c->isense_valid) f |= SMI_FLAG_ISENSE_VALID;+    if (c->track_warn) f |= SMI_FLAG_TRACK_WARN;+    r[4] = f;+    r[5] = c->fault;+    r[6] = c->boot_reason;+    r[7] = c->off_reason;+    putf(r + 8, li >= 0 ? c->target[li] : 0);+    putf(r + 12, c->laser_now);+    putf(r + 16, c->isense_ma);+    put16(r + 20, (uint16_t)c->isense_raw);+    uint32_t age = c->isense_valid ? (now_us - c->isense_us) / 1000u : 65535u;+    put16(r + 22, (uint16_t)(age > 65535u ? 65535u : age));+    put16(r + 24, c->hb_timeout_ms);+    r[26] = c->isense_hz;+    r[27] = c->n;+    size_t o = 28;+    for (int i = 0; i < c->n; i++) {+        put16(r + o, c->code[i]);+        putf(r + o + 2, c->target[i]);+        o += 6;+    }+    int32_t z = -32768;   // not calibrated+    if (c->zero_n >= 8) {+        float zz = c->zero_raw * 16.0f;+        z = (int32_t)(zz < 0 ? zz - 0.5f : zz + 0.5f);+        if (z > 32767) z = 32767;+        if (z < -32767) z = -32767;+    }+    put16(r + o, (uint16_t)(int16_t)z);+    return o + 2;+}
software/firmware/src/smi_ctl.hadded+209
@@ -0,0 +1,209 @@+// SPDX-License-Identifier: MIT+// Board control core: laser enable and current set-point, offsets, gains and+// monitor bias, with the firmware's own limits (rated current, ramp rate,+// overcurrent trip, host heartbeat). Portable C99 with a small hardware+// interface, so the same file runs in the Pico firmware, in the host-side test+// and inside the dashboard's simulator.+//+// Command channel, on the same USB link as the sample stream, using the same+// frame (smi_frame.h): the host sends SMI_T_CMD frames, the Pico answers every+// one with an SMI_T_ACK frame carrying the command's seq, and pushes+// SMI_T_STATE frames four times a second while the port is open.+//+// CMD payload: u8 op, then op arguments (little-endian):+//   SMI_OP_GET_STATE     -                       -> ACK carries the state block+//   SMI_OP_LASER_ENABLE  u8 on, u32 key          key must be SMI_LASER_KEY to turn on+//   SMI_OP_SET           u8 control, u8 mode, f32 value+//                        mode 0 = physical units (mA, V, ohm, x), 1 = DAC counts,+//                        2 = setting index (switches)+//                        -> ACK: u8 control, u16 code, f32 applied, f32 target+//   SMI_OP_READ_ISENSE   -                       -> ACK: f32 mA, u16 raw, u16 age_ms+//   SMI_OP_HEARTBEAT     -                       keeps the laser on (see hb_timeout_ms)+//   SMI_OP_CLEAR_FAULT   -+//   SMI_OP_GET_MAP       -                       -> ACK: u32 hash, u8 n, version text+//   SMI_OP_CONFIG        u8 isense_hz, u16 hb_timeout_ms+// ACK payload: u16 cmd_seq, u8 op, u8 status, then the result. On+// SMI_E_RANGE the result is f32 min, f32 max of what is allowed.+#ifndef SMI_CTL_H+#define SMI_CTL_H++#include <stdint.h>+#include <stdbool.h>+#include <stddef.h>++#define SMI_T_CMD 0x10+#define SMI_T_ACK 0x11+#define SMI_T_STATE 0x12++#define SMI_OP_GET_STATE 0x01+#define SMI_OP_LASER_ENABLE 0x02+#define SMI_OP_SET 0x03+#define SMI_OP_READ_ISENSE 0x04+#define SMI_OP_HEARTBEAT 0x05+#define SMI_OP_CLEAR_FAULT 0x06+#define SMI_OP_GET_MAP 0x07+#define SMI_OP_CONFIG 0x08++#define SMI_LASER_KEY 0x4C415345u /* "LASE" */++enum {+    SMI_OK = 0,+    SMI_E_LEN = 1,        // payload too short for the op+    SMI_E_OP = 2,         // unknown op+    SMI_E_CONTROL = 3,    // no such control index+    SMI_E_RANGE = 4,      // value outside the control's limits+    SMI_E_KEY = 5,        // laser enable without the interlock key+    SMI_E_FAULT = 6,      // a fault is latched; clear it first+    SMI_E_HW = 7,         // the DAC did not acknowledge+    SMI_E_MODE = 8,       // unit mode does not apply to this control+    SMI_E_NOT_READY = 9,  // current readback not yet validated at zero (startup rule)+    SMI_E_LASER_ON = 10,  // the map says change this control only with the laser off+};++// Why the laser is off (last_off_reason) and why the Pico booted.+enum {+    SMI_OFF_NONE = 0,+    SMI_OFF_BOOT = 1,+    SMI_OFF_HOST = 2,+    SMI_OFF_USB = 3,+    SMI_OFF_WATCHDOG = 4,+    SMI_OFF_HB_TIMEOUT = 5,+    SMI_OFF_OVERCURRENT = 6,+    SMI_OFF_HW = 7,+};++enum { SMI_FAULT_NONE = 0, SMI_FAULT_OVERCURRENT = 1, SMI_FAULT_HW = 2, SMI_FAULT_CURRENT_WHEN_OFF = 3, SMI_FAULT_ISENSE = 4,+       SMI_FAULT_READBACK = 5 };   // the laser DAC's register no longer matches what was written++#define SMI_FLAG_LASER_ON 0x01+#define SMI_FLAG_RAMPING 0x02+#define SMI_FLAG_FAULT 0x04+#define SMI_FLAG_ISENSE_VALID 0x08+#define SMI_FLAG_TRACK_WARN 0x10++enum { SMI_KIND_DAC = 1, SMI_KIND_SWITCH = 2 };+enum { SMI_UNIT_MA = 0, SMI_UNIT_V = 1, SMI_UNIT_OHM = 2, SMI_UNIT_X = 3 };++#define SMI_MAX_CONTROLS 12+#define SMI_MAX_SETTINGS 8++typedef struct {+    uint8_t part, addr, bits;+    float vref;+} smi_dac_def_t;++// Laser current readback (ADS1115 on the laser head): mA = (code - zero) *+// ma_per_code + offset_ma, with the zero code calibrated with the laser off.+typedef struct {+    float ma_per_code, offset_ma, trip_ma;+    uint8_t rate_hz;+    uint8_t zero_cal;+} smi_isense_def_t;++typedef struct {+    uint8_t kind, unit, is_laser, needs_off;+    float min, max, def;+    // DAC channels: value = at_zero + code * per_code.+    uint8_t dac, ch, bits;+    float per_code, at_zero, ramp_per_s, rated;+    // Laser DAC on the head (board 1.2.1 controller contract), gate = 1: every+    // write drops the enable, waits disarm_us for the head's disable path and+    // soft-start reset, writes and reads back, and re-asserts the enable only on+    // a verified nonzero code, then reads back once more. The head's soft-start+    // ramps the current from zero on every arm, so there is no stepped ramp:+    // the target is written in one step, at most every min_write_us.+    uint8_t gate;+    uint32_t min_write_us, disarm_us;+    // Highest DAC code allowed (0 = full scale). Command codes (counts mode on+    // the laser) map to DAC codes as max(command - guard, 0): the guard band+    // reserves counts for the DAC's positive offset error.+    uint16_t max_code, guard;+    // Switches: GPIO bits (LSB first) take set_code[i] for set_value[i].+    uint8_t ngpio, gpio[4], nset, set_code[SMI_MAX_SETTINGS];+    float set_value[SMI_MAX_SETTINGS];+} smi_control_def_t;++typedef struct {+    void *ctx;+    // Write one DAC channel; return false if the device did not acknowledge.+    // For a write-then-readback DAC (DAC121C085) also false if the register+    // read back does not match exactly.+    bool (*dac_write)(void *ctx, uint8_t dac, uint8_t ch, uint16_t code);+    // Optional (NULL = absent): busy-wait, and read a DAC's raw register back.+    void (*wait_us)(void *ctx, uint32_t us);+    bool (*dac_read)(void *ctx, uint8_t dac, uint16_t *reg);+    // Drive a switch line: Pico GPIO below 32, MCP23008 bit (32 + n) above.+    // Return false if an expander write was not acknowledged.+    bool (*gpio_put)(void *ctx, uint8_t gpio, bool level);+} smi_hal_t;++typedef struct {+    const smi_control_def_t *defs;+    uint8_t n;+    const smi_isense_def_t *isense;+    uint32_t map_hash;+    const char *map_version;+    uint8_t laser_en_gpio, laser_en_active_high;+    smi_hal_t hal;++    uint16_t code[SMI_MAX_CONTROLS];   // what the hardware holds (switches: GPIO code)+    float target[SMI_MAX_CONTROLS];    // requested value, physical units+    float laser_now;                   // ramped laser set-point, mA (= laser_ua / 1000)+    int32_t laser_ua;                  // the ramp runs in integer microamps, exactly at the rate+    uint32_t ramp_rem;                 // remainder of ramp_ua_per_s * dt_us / 1e6+    bool laser_on;+    uint8_t fault, boot_reason, off_reason;+    uint32_t last_host_us, last_tick_us, settled_since_us;+    uint16_t hb_timeout_ms;+    uint8_t isense_hz;+    float isense_ma;+    int16_t isense_raw;+    uint8_t isense_fail_n;             // consecutive failed reads of the head ADC+    uint32_t isense_us;+    bool isense_valid, track_warn;+    uint8_t over_n, offcur_n;+    uint32_t off_since_us;+    float zero_raw;                    // calibrated zero code of the current sense+    uint16_t zero_n;                   // readings that went into it+    uint32_t laser_write_us;           // last laser DAC write+    uint32_t readbacks;                // laser DAC readback polls that matched+} smi_ctl_t;++// boot_reason: SMI_OFF_BOOT for a normal power-up, SMI_OFF_WATCHDOG after a+// watchdog reset. Drives every output to its power-on default, laser off.+void smi_ctl_init(smi_ctl_t *c, const smi_control_def_t *defs, uint8_t n, const smi_isense_def_t *is,+                  uint32_t map_hash, const char *map_version, uint8_t laser_en_gpio, bool laser_en_active_high,+                  const smi_hal_t *hal, uint8_t boot_reason, uint32_t now_us);++// Handle one CMD payload. Writes the ACK payload into resp (at least 96 bytes)+// (at least 128 bytes) and returns its length.+size_t smi_ctl_command(smi_ctl_t *c, const uint8_t *p, size_t n, uint16_t cmd_seq, uint32_t now_us, uint8_t *resp);++// Call often (every loop pass): advances the laser ramp, checks the heartbeat.+void smi_ctl_tick(smi_ctl_t *c, uint32_t now_us);++// A new reading of the laser current sense (signed ADC code).+void smi_ctl_isense(smi_ctl_t *c, int32_t raw, uint32_t now_us);+// The current-sense ADC did not answer. Three in a row with the laser on is a+// fault: the firmware's overcurrent trip cannot work blind.+void smi_ctl_isense_failed(smi_ctl_t *c, uint32_t now_us);++// A poll of the laser DAC's register while armed (every 2 ms on the board:+// the traffic also feeds the head's I2C watchdog). reg is the raw 16-bit+// register: bits 13:12 power-down mode, 11:0 code. A failed read, a mode other+// than normal, or a code other than the one written is a latched fault.+void smi_ctl_laser_readback(smi_ctl_t *c, bool ok, uint16_t reg, uint32_t now_us);++// The host went away (USB unplugged, port closed): laser off, set-point to 0.+void smi_ctl_link_lost(smi_ctl_t *c, uint8_t reason);++// The STATE block (also the GET_STATE result). resp needs 30 + 6 * n bytes:+// 28 bytes of header (isense_raw is a signed i16), 6 per control, then the+// zero code as i16 x 16 (0x8000 = not calibrated).+size_t smi_ctl_state(const smi_ctl_t *c, uint32_t now_us, uint8_t *resp);++// Value <-> code for a DAC control.+uint16_t smi_ctl_code_for(const smi_control_def_t *d, float v);+float smi_ctl_value_of(const smi_control_def_t *d, uint16_t code);++#endif
software/firmware/src/smi_text.cadded+116
@@ -0,0 +1,116 @@+// SPDX-License-Identifier: MIT+#include "smi_text.h"+#include <stdio.h>+#include <string.h>+++static uint8_t text_ctl(smi_text_t *x, const uint8_t *p, size_t n) {+    uint8_t r[160];+    smi_ctl_command(x->ctl, p, n, 0, x->now_us(x->ctx), r);+    return r[3];+}++static uint8_t text_set(smi_text_t *x, int idx, uint8_t mode, float v) {+    uint8_t p[7] = { SMI_OP_SET, (uint8_t)idx, mode };+    memcpy(p + 3, &v, 4);+    return text_ctl(x, p, 7);+}++static uint8_t text_laser_off(smi_text_t *x) {+    uint8_t p[6] = { SMI_OP_LASER_ENABLE, 0, 0, 0, 0, 0 };+    x->laser_cmd = 0;+    return text_ctl(x, p, 6);+}++static void text_reply(smi_text_t *x, const char *what, uint8_t st) {+    if (st == SMI_OK) return;+    char t[64];+    snprintf(t, sizeof t, "error: %s: status %u", what, st);+    x->reply(x->ctx, t);+}++static long text_number(const char *s, long max) {+    if (!*s || strlen(s) > 5) return -1;+    long v = 0;+    for (; *s; s++) {+        if (*s < '0' || *s > '9') return -1;+        v = v * 10 + (*s - '0');+    }+    return v <= max ? v : -1;+}++// Set every switch whose lines are in [base, base + 3) from a bit mask.+static uint8_t text_mask(smi_text_t *x, long mask, int base) {+    uint8_t st = SMI_OK;+    for (int i = 0; i < x->ctl->n; i++) {+        const smi_control_def_t *d = &x->ctl->defs[i];+        if (d->kind != SMI_KIND_SWITCH || d->gpio[0] < base || d->gpio[0] >= base + 3) continue;+        unsigned code = 0;+        for (int b = 0; b < d->ngpio; b++) code |= ((unsigned)(mask >> (d->gpio[b] - base)) & 1u) << b;+        uint8_t s1 = text_set(x, i, 1, (float)code);+        if (s1 != SMI_OK) st = s1;+    }+    return st;+}++void smi_text_command(smi_text_t *x, const char *c) {+    long v;+    int li = 0;+    smi_ctl_t *ctl = x->ctl;+    const smi_control_def_t *defs = ctl->defs;+    for (int i = 0; i < ctl->n; i++)+        if (defs[i].is_laser) li = i;+    if (!strcmp(c, "start")) { if (x->start) x->start(x->ctx); }+    else if (!strcmp(c, "stop")) { text_laser_off(x); if (x->stop) x->stop(x->ctx); }+    else if (!strcmp(c, "info")) { if (x->info) x->info(x->ctx); }+    else if (!strcmp(c, "laser off")) text_reply(x, c, text_laser_off(x));+    else if (!strcmp(c, "laser current")) {+        char t[96];+        snprintf(t, sizeof t, "laser_current_code=%d; command_code=%u; dac_code=%u",+                 (int)ctl->isense_raw, x->laser_cmd, ctl->laser_on ? ctl->code[li] : 0u);+        x->reply(x->ctx, t);+    } else if (!strncmp(c, "laser ", 6)) {+        if ((v = text_number(c + 6, 4095)) < 0) { text_laser_off(x); return; }+        if (v <= defs[li].guard) { text_reply(x, c, text_laser_off(x)); return; }   // disarmed command codes+        uint8_t st = SMI_OK;+        if (!ctl->laser_on) {+            uint8_t p[6] = { SMI_OP_LASER_ENABLE, 1, (uint8_t)SMI_LASER_KEY, (uint8_t)(SMI_LASER_KEY >> 8), (uint8_t)(SMI_LASER_KEY >> 16), (uint8_t)(SMI_LASER_KEY >> 24) };+            st = text_ctl(x, p, 6);+        }+        if (st == SMI_OK) st = text_set(x, li, 1, (float)v);+        if (st == SMI_OK) x->laser_cmd = (uint16_t)v;+        else text_laser_off(x);+        text_reply(x, c, st);+    } else if (!strncmp(c, "head ", 5) || !strncmp(c, "gain ", 5)) {+        if ((v = text_number(c + 5, 7)) < 0) return;+        text_laser_off(x);+        text_reply(x, c, text_mask(x, v, c[0] == 'h' ? x->exp_base : x->gain_base));+    } else if (!strncmp(c, "offset B ", 9) || !strncmp(c, "offset C ", 9)) {+        if ((v = text_number(c + 9, 4095)) < 0) return;+        text_laser_off(x);+        int ch = c[7] - 'A';+        for (int i = 0; i < ctl->n; i++)+            if (!defs[i].is_laser && defs[i].kind == SMI_KIND_DAC && defs[i].ch == ch)+                text_reply(x, c, text_set(x, i, 1, (float)v));+    } else if (!strncmp(c, "hb ", 3)) {+        // Heartbeat timeout for text-only hosts: hb MS (500..30000).+        if ((v = text_number(c + 3, 30000)) < 0) return;+        uint8_t p[4] = { SMI_OP_CONFIG, ctl->isense_hz, (uint8_t)v, (uint8_t)(v >> 8) };+        text_reply(x, c, text_ctl(x, p, 4));+    }+}+++void smi_text_feed(smi_text_t *x, char c) {+    if (c == '\n' || c == '\r') {+        x->line[x->len] = 0;+        if (x->overflow) text_laser_off(x);+        else if (x->len) smi_text_command(x, x->line);+        x->len = 0;+        x->overflow = false;+    } else if (x->len < (int)sizeof x->line - 1) {+        x->line[x->len++] = c;+    } else {+        x->overflow = true;+    }+}
software/firmware/src/smi_text.hadded+34
@@ -0,0 +1,34 @@+// SPDX-License-Identifier: MIT+// Text commands of the board's controller contract (control map,+// firmwareCommands): "laser CODE", "laser off", "laser current", "head MASK",+// "gain MASK", "offset B CODE", "offset C CODE", plus "start", "stop", "info"+// and "hb MS". They run through the control core (smi_ctl.c), so every limit,+// refusal and fault applies; selector and offset commands disarm the laser+// first, as the contract says. Portable: used by the firmware and the host+// stand-in (test/ctl_pty.c).+#ifndef SMI_TEXT_H+#define SMI_TEXT_H+#include "smi_ctl.h"++typedef struct {+    smi_ctl_t *ctl;+    void *ctx;+    uint32_t (*now_us)(void *ctx);+    void (*reply)(void *ctx, const char *text);   // sent back as an INFO frame+    void (*start)(void *ctx);+    void (*stop)(void *ctx);+    void (*info)(void *ctx);+    int exp_base, gain_base;                      // "head" mask bit 0 = exp_base, "gain" bit 0 = gain_base+    uint16_t laser_cmd;                           // last accepted laser command code+    char line[32];                                // line buffer for smi_text_feed+    int len;+    bool overflow;+} smi_text_t;++void smi_text_command(smi_text_t *x, const char *line);++// Feed one received character; a line ending runs the command. A line longer+// than the buffer is ignored and disarms the laser.+void smi_text_feed(smi_text_t *x, char c);++#endif
software/firmware/test/ctl_pty.cadded+114
@@ -0,0 +1,114 @@+// SPDX-License-Identifier: MIT+// Host stand-in for the Pico's command channel, for testing the dashboard's+// serial path without hardware: the firmware's control core (smi_ctl.c) and+// frame code (smi_frame.c) behind a pseudo-terminal. It answers CMD frames+// with ACKs, sends STATE frames four times a second, and feeds the core a+// current reading that follows the DAC like the head's ADS1115 would.+//   cc -O2 -I../src ctl_pty.c ../src/smi_ctl.c ../src/smi_text.c ../src/smi_frame.c -lm -o ctl_pty+//   ./ctl_pty SECONDS     (prints the pty path, then serves it)+#define _XOPEN_SOURCE 600+#define _DEFAULT_SOURCE+#include <fcntl.h>+#include <termios.h>+#include <math.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <time.h>+#include <unistd.h>+#include "smi_frame.h"+#include "smi_ctl.h"+#include "smi_controls_gen.h"+#include "smi_text.h"++static uint16_t dac[4][8];+static bool gp[64];+static bool d_w(void *c, uint8_t d, uint8_t ch, uint16_t code) { (void)c; dac[d][ch] = code; return true; }+static bool g_w(void *c, uint8_t g, bool v) { (void)c; gp[g] = v; return true; }+static uint32_t now_us(void);+static uint32_t text_now(void *x) { (void)x; return now_us(); }+static uint32_t now_us(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return (uint32_t)(t.tv_sec * 1000000ull + t.tv_nsec / 1000); }++static int fd;+static uint16_t seq;+static void send(uint8_t type, const uint8_t *pl, uint16_t n);+static void text_send(void *x, const char *t) { (void)x; send(SMI_T_INFO, (const uint8_t *)t, (uint16_t)strlen(t)); }+static void send(uint8_t type, const uint8_t *pl, uint16_t n) {+    uint8_t f[256];+    memcpy(f + SMI_HDR_LEN, pl, n);+    smi_begin_frame(f, type, n, seq++);+    size_t len = smi_finish_frame(f, n);+    if (write(fd, f, len) != (ssize_t)len) perror("write");+}++int main(int argc, char **argv) {+    double secs = argc > 1 ? atof(argv[1]) : 30;+    fd = posix_openpt(O_RDWR | O_NOCTTY);+    grantpt(fd); unlockpt(fd);+    {   // Raw from the start, like a USB CDC port: no echo of our own frames back to us.+        int sl = open(ptsname(fd), O_RDWR | O_NOCTTY);+        struct termios t;+        tcgetattr(sl, &t);+        cfmakeraw(&t);+        tcsetattr(sl, TCSANOW, &t);+        close(sl);+    }+    printf("%s\n", ptsname(fd)); fflush(stdout);+    fcntl(fd, F_SETFL, O_NONBLOCK);+    smi_ctl_t c;+    smi_hal_t hal = {.ctx = NULL, .dac_write = d_w, .gpio_put = g_w};+    smi_ctl_init(&c, smi_controls, SMI_NUM_CONTROLS, &smi_isense, SMI_MAP_HASH, SMI_MAP_VERSION, SMI_LASER_EN_GPIO, SMI_LASER_EN_ACTIVE_HIGH, &hal, SMI_OFF_BOOT, now_us());+    const char *info = "ctl_pty host stand-in; map=" SMI_MAP_VERSION;+    send(SMI_T_INFO, (const uint8_t *)info, (uint16_t)strlen(info));+    uint8_t rx[200]; int rl = 0;+    smi_text_t tx = { .ctl = &c, .now_us = text_now, .reply = text_send, .exp_base = SMI_EXP_BASE, .gain_base = 7 };+    uint32_t t0 = now_us(), last_state = 0, last_is = 0, last_poll = 0;+    int li = 0;+    unsigned acks = 0;+    while ((now_us() - t0) < secs * 1e6) {+        uint8_t b;+        while (read(fd, &b, 1) == 1) {+            if (rl == 0 && b != SMI_SYNC0) {+                // Text command lines (board contract), as the firmware takes them.+                smi_text_feed(&tx, (char)b);+                continue;+            }+            rx[rl++] = b;+            if (rl == 2 && b != SMI_SYNC1) { rl = 0; continue; }+            if (rl >= 6) {+                uint16_t len = (uint16_t)(rx[4] | (rx[5] << 8));+                if (len > 160) { rl = 0; continue; }+                if (rl == 8 + len + 2) {+                    uint16_t crc = (uint16_t)(rx[8 + len] | (rx[9 + len] << 8));+                    if (rx[2] == SMI_T_CMD && smi_crc16(rx + 2, 6u + len, 0xFFFF) == crc) {+                        uint8_t r[200];+                        size_t n = smi_ctl_command(&c, rx + 8, len, (uint16_t)(rx[6] | (rx[7] << 8)), now_us(), r);+                        send(SMI_T_ACK, r, (uint16_t)n);+                        acks++;+                    }+                    rl = 0;+                }+            }+        }+        uint32_t t = now_us();+        smi_ctl_tick(&c, t);+        if (t - last_is > 20000) {   // 50 Hz, like the firmware: current follows the DAC, zero code +6+            last_is = t;+            bool on = gp[SMI_LASER_EN_GPIO] == SMI_LASER_EN_ACTIVE_HIGH;+            float ma = on ? smi_ctl_value_of(&smi_controls[li], dac[smi_controls[li].dac][smi_controls[li].ch]) : 0.0f;+            smi_ctl_isense(&c, (int32_t)lroundf(ma / smi_isense.ma_per_code) + 6, t);+        }+        if (SMI_LASER_READBACK_POLL_MS && c.laser_on && t - last_poll >= SMI_LASER_READBACK_POLL_MS * 1000u) {+            last_poll = t;   // the stand-in's head DAC reads back what was written+            smi_ctl_laser_readback(&c, true, dac[smi_controls[li].dac][smi_controls[li].ch] & 0x0FFF, t);+        }+        if (t - last_state > 250000) {+            last_state = t;+            uint8_t st[200];+            send(SMI_T_STATE, st, (uint16_t)smi_ctl_state(&c, t, st));+        }+        usleep(500);+    }+    fprintf(stderr, "ctl_pty: text laser command %u; answered %u commands; laser %s, off reason %u, fault %u, readback polls %u\n", tx.laser_cmd, acks, c.laser_on ? "on" : "off", c.off_reason, c.fault, (unsigned)c.readbacks);+    return 0;+}
software/firmware/test/test_ctl.cadded+394
@@ -0,0 +1,394 @@+// SPDX-License-Identifier: MIT+// Host test of the board control core against the generated control table:+// boot defaults, the laser interlock, range limits, the gated head-DAC write+// sequence and its rate limit (or the ramp, for a static DAC), the guard band,+// readback checks, the heartbeat timeout, overcurrent trip, link loss and DAC failure.+//   cc -O2 -Wall -Wextra -I../src test_ctl.c ../src/smi_ctl.c -o test_ctl && ./test_ctl+#include <stdio.h>+#include <string.h>+#include <math.h>+#include "smi_ctl.h"+#include "smi_controls_gen.h"++static int fails, checks;+#define CHECK(c, ...) do { checks++; if (!(c)) { fails++; printf("FAIL line %d: ", __LINE__); printf(__VA_ARGS__); printf("\n"); } } while (0)++typedef struct {+    uint16_t dac[4][8];+    int dac_writes;+    bool gpio[64];+    bool fail_exp;+    bool fail_dac;+    float max_step;      // largest laser DAC change seen while ramping, in mA+    float last_laser;+    int gate_violations;   // laser DAC writes made while the enable was asserted+    int laser_writes;+    int waits_ok;          // disarm waits of at least disarm_us made with the enable dropped+    int waits_bad;+    int reads;             // head DAC readbacks made by the core+    bool fail_read;+} hw_t;++static hw_t hw;+static int LI;++static bool fake_dac(void *ctx, uint8_t dev, uint8_t ch, uint16_t code) {+    hw_t *h = ctx;+    if (h->fail_dac) return false;+    if (dev == smi_controls[LI].dac && ch == smi_controls[LI].ch) {+        h->laser_writes++;+        if (smi_controls[LI].gate && h->gpio[SMI_LASER_EN_GPIO] == (SMI_LASER_EN_ACTIVE_HIGH ? 1 : 0)) h->gate_violations++;+        float v = smi_ctl_value_of(&smi_controls[LI], code);+        float d = fabsf(v - h->last_laser);+        if (v > h->last_laser && d > h->max_step) h->max_step = d;+        h->last_laser = v;+    }+    h->dac[dev][ch] = code;+    h->dac_writes++;+    return true;+}+static bool fake_gpio(void *ctx, uint8_t g, bool v) {+    hw_t *h = ctx;+    if (g >= SMI_EXP_BASE && h->fail_exp) return false;+    h->gpio[g] = v;+    return true;+}++static bool laser_pin_on(void) { return hw.gpio[SMI_LASER_EN_GPIO] == (SMI_LASER_EN_ACTIVE_HIGH ? 1 : 0); }+static void fake_wait(void *ctx, uint32_t us) {+    hw_t *h = ctx;+    bool on = h->gpio[SMI_LASER_EN_GPIO] == (SMI_LASER_EN_ACTIVE_HIGH ? 1 : 0);+    if (!on && us >= smi_controls[LI].disarm_us) h->waits_ok++; else h->waits_bad++;+}+static bool fake_read(void *ctx, uint8_t dev, uint16_t *reg) {+    hw_t *h = ctx;+    h->reads++;+    *reg = h->dac[dev][smi_controls[LI].ch];+    return !h->fail_read;+}+// Armed: the firmware has the laser enabled. With a gated head DAC the pin itself+// is asserted only while a verified nonzero code is in the DAC.+static bool armed(const smi_ctl_t *c) { return c->laser_on; }++static uint8_t resp[160];+static uint16_t cseq;++static uint8_t cmd(smi_ctl_t *c, uint32_t now, const uint8_t *p, size_t n, size_t *len) {+    size_t l = smi_ctl_command(c, p, n, ++cseq, now, resp);+    if (len) *len = l;+    CHECK(resp[0] == (uint8_t)cseq && resp[1] == (uint8_t)(cseq >> 8), "ack echoes seq");+    return resp[3];+}+static uint8_t enable(smi_ctl_t *c, uint32_t now, int on, uint32_t key) {+    uint8_t p[6] = {SMI_OP_LASER_ENABLE, (uint8_t)on, (uint8_t)key, (uint8_t)(key >> 8), (uint8_t)(key >> 16), (uint8_t)(key >> 24)};+    return cmd(c, now, p, 6, NULL);+}+static uint8_t set(smi_ctl_t *c, uint32_t now, int idx, int mode, float v) {+    uint8_t p[7] = {SMI_OP_SET, (uint8_t)idx, (uint8_t)mode};+    memcpy(p + 3, &v, 4);+    return cmd(c, now, p, 7, NULL);+}+static void hb(smi_ctl_t *c, uint32_t now) { uint8_t p[1] = {SMI_OP_HEARTBEAT}; cmd(c, now, p, 1, NULL); }+static float zero_code(const smi_ctl_t *c) { return smi_isense.zero_cal ? c->zero_raw : 0.0f; }+static int32_t raw_for(const smi_ctl_t *c, float ma) { return (int32_t)lroundf((ma - smi_isense.offset_ma) / smi_isense.ma_per_code + zero_code(c)); }++static smi_ctl_t boot(uint8_t reason) {+    memset(&hw, 0, sizeof hw);+    for (int i = 0; i < 64; i++) hw.gpio[i] = SMI_LASER_EN_ACTIVE_HIGH;   // pessimistic: pins start "on"+    smi_hal_t hal = {.ctx = &hw, .dac_write = fake_dac, .wait_us = fake_wait, .dac_read = fake_read, .gpio_put = fake_gpio};+    static smi_ctl_t c;+    smi_ctl_init(&c, smi_controls, SMI_NUM_CONTROLS, &smi_isense, SMI_MAP_HASH, SMI_MAP_VERSION, SMI_LASER_EN_GPIO, SMI_LASER_EN_ACTIVE_HIGH, &hal, reason, 0);+    return c;+}++int main(void) {+    LI = -1;+    for (int i = 0; i < SMI_NUM_CONTROLS; i++) if (smi_controls[i].is_laser) LI = i;+    CHECK(LI == 0, "laser control is index 0");+    const smi_control_def_t *L = &smi_controls[LI];+    float lim = L->max < L->rated ? L->max : L->rated;+    uint32_t t = 0;++    // Boot: laser off, every output at its default.+    smi_ctl_t c = boot(SMI_OFF_BOOT);+    CHECK(!laser_pin_on(), "laser enable pin off at boot");+    CHECK(hw.dac[L->dac][L->ch] == smi_ctl_code_for(L, 0), "laser DAC at 0 mA at boot");+    for (int i = 0; i < SMI_NUM_CONTROLS; i++) {+        const smi_control_def_t *d = &smi_controls[i];+        if (d->kind == SMI_KIND_DAC && !d->is_laser) CHECK(hw.dac[d->dac][d->ch] == smi_ctl_code_for(d, d->def), "control %d DAC default", i);+        if (d->kind == SMI_KIND_SWITCH) {+            int k = 0; for (int j = d->nset - 1; j >= 0; j--) if (d->set_value[j] == d->def) k = j;+            for (int b = 0; b < d->ngpio; b++) CHECK(hw.gpio[d->gpio[b]] == ((d->set_code[k] >> b) & 1), "control %d switch default bit %d", i, b);+        }+    }+    CHECK(c.off_reason == SMI_OFF_BOOT, "off reason boot");+    smi_ctl_t w = boot(SMI_OFF_WATCHDOG);+    CHECK(!laser_pin_on() && w.boot_reason == SMI_OFF_WATCHDOG, "watchdog boot: laser off, reason reported");+    c = boot(SMI_OFF_BOOT);++    // Startup rule: no enable until the current readback is validated at zero.+    CHECK(enable(&c, t, 1, SMI_LASER_KEY) == (smi_isense.zero_cal ? SMI_E_NOT_READY : SMI_E_NOT_READY), "enable refused before the zero check");+    for (int k = 0; k < 12; k++) { t += 100000u; hb(&c, t); smi_ctl_isense(&c, 37, t); }+    CHECK(!smi_isense.zero_cal || (c.zero_n >= 8 && fabsf(c.zero_raw - 37) < 0.01f), "zero code calibrated (%.2f)", c.zero_raw);+    CHECK(fabsf(c.isense_ma) < 0.01f, "reads 0 mA at the zero code");++    // Interlock key.+    CHECK(enable(&c, t, 1, 0x12345678) == SMI_E_KEY, "enable without the key is refused");+    CHECK(!laser_pin_on(), "still off");+    CHECK(enable(&c, t, 1, SMI_LASER_KEY) == SMI_OK && armed(&c), "enable with key");+    CHECK(!L->gate || !laser_pin_on(), "gated: no enable carrier while the DAC holds code 0");+    CHECK(c.laser_now == 0, "enable starts at 0 mA");++    // Limits.+    CHECK(set(&c, t, LI, 0, lim + 1.0f) == SMI_E_RANGE, "above the limit is refused");+    CHECK(set(&c, t, LI, 0, L->rated + 10.0f) == SMI_E_RANGE, "above rated is refused");+    CHECK(set(&c, t, LI, 0, -1.0f) == SMI_E_RANGE, "negative is refused");+    CHECK(set(&c, t, LI, 0, NAN) == SMI_E_RANGE, "NaN is refused");+    CHECK(set(&c, t, LI, 2, 1) == SMI_E_MODE, "index mode on a DAC is refused");+    CHECK(set(&c, t, SMI_NUM_CONTROLS, 0, 1) == SMI_E_CONTROL, "unknown control");++    if (L->gate) {+        // Board 1.2.1 contract: no stepped ramp (every write resets the head's+        // soft-start); one verified write per change, at most every min_write_us.+        hw.laser_writes = 0; hw.gate_violations = 0; hw.waits_ok = 0; hw.waits_bad = 0; hw.reads = 0;+        CHECK(L->max_code == 4095 - L->guard || !L->guard, "top DAC code is full scale minus the guard (%u)", L->max_code);+        CHECK(fabsf(lim - smi_ctl_value_of(L, L->max_code)) < 1e-3f, "limit %.3f mA is the top code's current", lim);+        CHECK(set(&c, t, LI, 0, lim) == SMI_OK, "set to the limit");+        t += 1000; smi_ctl_tick(&c, t);+        CHECK(hw.dac[L->dac][L->ch] == L->max_code, "written in one step to the top code (%u)", hw.dac[L->dac][L->ch]);+        CHECK(laser_pin_on(), "enable asserted after the verified nonzero write");+        CHECK(fabsf(c.laser_now - lim) < fabsf(L->per_code), "set-point at the target");+        CHECK(hw.waits_ok >= 1 && hw.waits_bad == 0, "every write waited disarm_us with the enable dropped (%d ok, %d bad)", hw.waits_ok, hw.waits_bad);+        CHECK(hw.reads >= 1, "read back once more right after arming");+        CHECK(hw.gate_violations == 0, "no laser write with the enable asserted");+        // Requests every 10 ms for 1 s: at most one write per min_write_us, the latest wins.+        hw.laser_writes = 0;+        float last_req = 0;+        uint32_t t0 = t;+        for (int k = 1; k <= 100; k++) {+            t = t0 + (uint32_t)k * 10000u;+            last_req = 20.0f + (float)(k % 7) * 3.0f;+            set(&c, t, LI, 0, last_req);+            smi_ctl_tick(&c, t);+        }+        for (int ms = 1; ms <= (int)(L->min_write_us / 1000) + 5; ms++) smi_ctl_tick(&c, t + (uint32_t)ms * 1000u);+        t += L->min_write_us + 5000u; hb(&c, t);+        int allowed = (int)(1e6f / (float)L->min_write_us) + 2;+        CHECK(hw.laser_writes <= allowed, "write rate limited: %d writes in 1 s (allowed %d)", hw.laser_writes, allowed);+        CHECK(hw.dac[L->dac][L->ch] == smi_ctl_code_for(L, last_req), "the latest request wins (%u)", hw.dac[L->dac][L->ch]);+        CHECK(hw.gate_violations == 0 && hw.waits_bad == 0, "still every write disarmed first");+        if (L->guard) {+            // Command codes: 0..guard are disarmed; guard + 1 is DAC code 1.+            t += L->min_write_us; hb(&c, t);+            CHECK(set(&c, t, LI, 1, (float)L->guard) == SMI_OK, "command code %u accepted", L->guard);+            t += L->min_write_us; smi_ctl_tick(&c, t);+            CHECK(hw.dac[L->dac][L->ch] == 0 && !laser_pin_on() && armed(&c), "command code at the guard: DAC 0, enable off");+            t += L->min_write_us; hb(&c, t);+            CHECK(set(&c, t, LI, 1, (float)L->guard + 1) == SMI_OK, "command code guard + 1");+            t += L->min_write_us; smi_ctl_tick(&c, t);+            CHECK(hw.dac[L->dac][L->ch] == 1 && laser_pin_on(), "guard + 1: DAC code 1, enable on");+            t += L->min_write_us; hb(&c, t);+            CHECK(set(&c, t, LI, 1, 4095) == SMI_OK, "command code 4095");+            t += L->min_write_us; smi_ctl_tick(&c, t);+            CHECK(hw.dac[L->dac][L->ch] == 4095 - L->guard, "command 4095: DAC %u", hw.dac[L->dac][L->ch]);+        }+        // The readback right after arming fails: disarm, fault.+        t += L->min_write_us; hb(&c, t);+        set(&c, t, LI, 0, 30);+        hw.fail_read = true;+        t += L->min_write_us; smi_ctl_tick(&c, t);+        CHECK(!armed(&c) && !laser_pin_on() && c.fault == SMI_FAULT_READBACK, "failed readback after arming: fault, off");+        hw.fail_read = false;+        uint8_t cf0[1] = {SMI_OP_CLEAR_FAULT};+        cmd(&c, t, cf0, 1, NULL);+        enable(&c, t, 1, SMI_LASER_KEY);+        set(&c, t, LI, 0, lim / 2);+        t += 1000; smi_ctl_tick(&c, t);+    } else {+        // Ramp: set to the limit, tick at 1 ms, the set-point moves at ramp_per_s.+        hw.max_step = 0; hw.last_laser = 0; hw.laser_writes = 0;+        CHECK(set(&c, t, LI, 0, lim) == SMI_OK, "set to the limit");+        float expect_s = lim / L->ramp_per_s;+        float half_t = 0;+        uint32_t t0 = t;+        for (int ms = 1; ms <= (int)(expect_s * 1000) + 50; ms++) {+            t = t0 + (uint32_t)ms * 1000u;+            smi_ctl_tick(&c, t);+            if (ms % 1000 == 0) hb(&c, t);+            if (half_t == 0 && c.laser_now >= lim / 2) half_t = ms / 1000.0f;+            CHECK(c.laser_now <= L->ramp_per_s * ms / 1000.0f + 1e-3f, "ramp never ahead of the rate at %d ms", ms);+            CHECK(c.laser_now <= lim + 1e-4f, "never above the limit");+            CHECK(smi_ctl_value_of(L, c.code[LI]) <= c.laser_now + fabsf(L->per_code) * 0.51f, "DAC never ahead of the set-point at %d ms", ms);+        }+        CHECK(fabsf(c.laser_now - lim) <= 1e-3f, "reached the target (1 uA resolution)");+        CHECK(fabsf(half_t - expect_s / 2) < 0.01f, "half way at %.3f s (expect %.3f)", half_t, expect_s / 2);+        float wstep = L->ramp_per_s * (L->min_write_us > 1000 ? L->min_write_us : 1000) * 1e-6f;+        CHECK(hw.max_step <= wstep + fabsf(L->per_code) * 1.01f, "largest DAC step %.4f mA (allowed %.4f)", hw.max_step, wstep);+        CHECK(!L->gate || laser_pin_on(), "gated: enable asserted after a verified nonzero write");+        CHECK(hw.gate_violations == 0, "gated: every laser DAC write made with the enable dropped (%d violations)", hw.gate_violations);+        if (L->min_write_us) {+            float max_rate = 1e6f / (float)L->min_write_us + 2;+            CHECK(hw.laser_writes <= (int)(expect_s * max_rate) + 5, "ramp write rate limited: %d writes in %.2f s", hw.laser_writes, expect_s);+        }+        float maxv = smi_ctl_value_of(L, hw.dac[L->dac][L->ch]);+        CHECK(maxv <= lim + fabsf(L->per_code) * 0.5f, "DAC code value %.3f within limit", maxv);++        // A stalled loop (1 s between ticks) moves at most 10 ms worth.+        set(&c, t, LI, 0, 0);+        float before = c.laser_now;+        t += 1000000u; hb(&c, t);+        smi_ctl_tick(&c, t);+        CHECK(before - c.laser_now <= L->ramp_per_s * 0.0101f, "stalled tick limited (%.3f mA)", before - c.laser_now);++    }++    // Heartbeat timeout: no command for longer than hb_timeout_ms turns it off.+    set(&c, t, LI, 0, lim / 2);+    uint32_t last = t;+    for (int ms = 1; ms < c.hb_timeout_ms + 100; ms++) { t = last + (uint32_t)ms * 1000u; smi_ctl_tick(&c, t); }+    CHECK(!laser_pin_on() && c.off_reason == SMI_OFF_HB_TIMEOUT, "heartbeat timeout turns the laser off");+    CHECK(hw.dac[L->dac][L->ch] == smi_ctl_code_for(L, 0), "and the DAC to 0");++    // Overcurrent: three readings over the trip latch a fault.+    enable(&c, t, 1, SMI_LASER_KEY);+    smi_ctl_isense(&c, raw_for(&c, smi_isense.trip_ma + 3), t);+    smi_ctl_isense(&c, raw_for(&c, smi_isense.trip_ma + 3), t);+    CHECK(armed(&c), "two readings over trip: still on (glitch filter)");+    smi_ctl_isense(&c, raw_for(&c, smi_isense.trip_ma + 3), t);+    CHECK(!laser_pin_on() && c.fault == SMI_FAULT_OVERCURRENT && c.off_reason == SMI_OFF_OVERCURRENT, "overcurrent trips");+    CHECK(enable(&c, t, 1, SMI_LASER_KEY) == SMI_E_FAULT, "enable refused while the fault is latched");+    uint8_t cf[1] = {SMI_OP_CLEAR_FAULT};+    CHECK(cmd(&c, t, cf, 1, NULL) == SMI_OK && c.fault == 0, "clear fault");+    smi_ctl_isense(&c, raw_for(&c, 0), t);+    CHECK(enable(&c, t, 1, SMI_LASER_KEY) == SMI_OK, "enable after clear");++    // Head ADC stops answering with the laser on: fault after three misses.+    smi_ctl_isense_failed(&c, t);+    smi_ctl_isense_failed(&c, t);+    CHECK(armed(&c), "two missed current reads: still on");+    smi_ctl_isense_failed(&c, t);+    CHECK(!laser_pin_on() && c.fault == SMI_FAULT_ISENSE, "three missed current reads: fault, off");+    cmd(&c, t, cf, 1, NULL);+    smi_ctl_isense(&c, raw_for(&c, 0), t);+    CHECK(enable(&c, t, 1, SMI_LASER_KEY) == SMI_OK, "enable after the readback returns");+    // A negative zero code (signed ADC) calibrates too.+    {+        static smi_ctl_t z;+        hw_t keep = hw;+        smi_hal_t hal = {.ctx = &hw, .dac_write = fake_dac, .wait_us = fake_wait, .dac_read = fake_read, .gpio_put = fake_gpio};+        smi_ctl_init(&z, smi_controls, SMI_NUM_CONTROLS, &smi_isense, SMI_MAP_HASH, SMI_MAP_VERSION, SMI_LASER_EN_GPIO, SMI_LASER_EN_ACTIVE_HIGH, &hal, SMI_OFF_BOOT, 0);+        for (int k = 0; k < 12; k++) smi_ctl_isense(&z, -21, 400000u + k * 100000u);+        CHECK(fabsf(z.zero_raw + 21) < 0.01f && fabsf(z.isense_ma) < 0.01f, "negative zero code %.2f", z.zero_raw);+        uint8_t st2[160]; size_t l2 = smi_ctl_state(&z, 2000000u, st2);+        int16_t zc = (int16_t)(st2[l2 - 2] | (st2[l2 - 1] << 8));+        CHECK(zc == -21 * 16, "zero code in STATE (%d)", zc);+        hw = keep;+    }++    // Measured current readback.+    smi_ctl_isense(&c, raw_for(&c, 42.0f), t);+    uint8_t ri[1] = {SMI_OP_READ_ISENSE};+    size_t n;+    CHECK(cmd(&c, t, ri, 1, &n) == SMI_OK && n == 12, "read isense");+    float ma; memcpy(&ma, resp + 4, 4);+    CHECK(fabsf(ma - 42.0f) < smi_isense.ma_per_code, "isense %.3f mA", ma);++    // Link lost: off and the set-point back to 0.+    set(&c, t, LI, 0, lim / 3);+    smi_ctl_link_lost(&c, SMI_OFF_USB);+    CHECK(!laser_pin_on() && c.off_reason == SMI_OFF_USB && c.target[LI] == 0, "USB loss: off, set-point 0");++    // Controls the map marks "change with the laser disabled" are refused while it is on.+    enable(&c, t, 1, SMI_LASER_KEY);+    for (int i = 0; i < SMI_NUM_CONTROLS; i++)+        if (smi_controls[i].needs_off) CHECK(set(&c, t, i, 2, 0) == SMI_E_LASER_ON, "control %d refused with the laser on", i);+    enable(&c, t, 0, 0);++    // Switches, by value, index and code; DAC controls in counts.+    for (int i = 0; i < SMI_NUM_CONTROLS; i++) {+        const smi_control_def_t *d = &smi_controls[i];+        if (d->kind == SMI_KIND_SWITCH) {+            int k = d->nset - 1;+            for (int j = 0; j < d->nset; j++) if (d->set_value[j] == d->set_value[k]) { k = j; break; }+            CHECK(set(&c, t, i, 0, d->set_value[k]) == SMI_OK && c.code[i] == d->set_code[k], "switch %d by value", i);+            for (int b = 0; b < d->ngpio; b++) CHECK(hw.gpio[d->gpio[b]] == ((d->set_code[k] >> b) & 1), "switch %d bit %d", i, b);+            CHECK(set(&c, t, i, 2, 0) == SMI_OK && c.code[i] == d->set_code[0], "switch %d by index", i);+            CHECK(set(&c, t, i, 0, d->set_value[0] * 1.37f + 0.5f) == SMI_E_RANGE, "switch %d off-list value refused", i);+        } else if (!d->is_laser) {+            uint16_t code = smi_ctl_code_for(d, (d->min + d->max) / 2);+            CHECK(set(&c, t, i, 1, code) == SMI_OK && hw.dac[d->dac][d->ch] == code, "DAC %d by counts", i);+            CHECK(set(&c, t, i, 0, d->max + fabsf(d->per_code) * 2) == SMI_E_RANGE, "DAC %d above max refused", i);+        }+    }++    // A value listed twice (bias LOW at codes 0 and 3): the first code is used.+    for (int i = 0; i < SMI_NUM_CONTROLS; i++) {+        const smi_control_def_t *d = &smi_controls[i];+        for (int a = 0; a < d->nset; a++) for (int b2 = a + 1; b2 < d->nset; b2++)+            if (d->kind == SMI_KIND_SWITCH && d->set_value[a] == d->set_value[b2])+                CHECK(set(&c, t, i, 0, d->set_value[a]) == SMI_OK && c.code[i] == d->set_code[a], "control %d duplicate value takes code %d", i, d->set_code[a]);+    }++    // Head expander not answering at boot: a latched fault, the laser cannot be enabled.+    {+        hw_t keep = hw;+        memset(&hw, 0, sizeof hw);+        hw.fail_exp = true;+        smi_hal_t hal = {.ctx = &hw, .dac_write = fake_dac, .wait_us = fake_wait, .dac_read = fake_read, .gpio_put = fake_gpio};+        static smi_ctl_t e;+        smi_ctl_init(&e, smi_controls, SMI_NUM_CONTROLS, &smi_isense, SMI_MAP_HASH, SMI_MAP_VERSION, SMI_LASER_EN_GPIO, SMI_LASER_EN_ACTIVE_HIGH, &hal, SMI_OFF_BOOT, 0);+        if (SMI_EXP_PRESENT) {+            CHECK(e.fault == SMI_FAULT_HW, "expander silent at boot: fault");+            for (int k = 0; k < 12; k++) smi_ctl_isense(&e, 0, 400000u + k * 100000u);+            CHECK(enable(&e, 1500000u, 1, SMI_LASER_KEY) == SMI_E_FAULT, "and enable is refused");+        }+        hw = keep;+    }++    // Readback polls (board: every 2 ms while armed). Matching register: counted;+    // wrong code, a power-down mode or a failed read: fault and off.+    cmd(&c, t, cf, 1, NULL);+    enable(&c, t, 1, SMI_LASER_KEY);+    set(&c, t, LI, 0, 20);+    for (int ms = 1; ms < 1000; ms++) { smi_ctl_tick(&c, t + ms * 1000u); if (ms % 500 == 0) hb(&c, t + ms * 1000u); }+    t += 1000000u;+    uint16_t good = c.code[LI];+    uint32_t rb0 = c.readbacks;+    smi_ctl_laser_readback(&c, true, good, t);+    CHECK(c.readbacks == rb0 + 1 && armed(&c), "matching readback counted");+    smi_ctl_laser_readback(&c, true, (uint16_t)(good | 0x1000), t);+    CHECK(!armed(&c) && !laser_pin_on() && c.fault == SMI_FAULT_READBACK, "power-down bits in the readback: fault, off");+    cmd(&c, t, cf, 1, NULL); enable(&c, t, 1, SMI_LASER_KEY); set(&c, t, LI, 0, 20);+    for (int ms = 1; ms < 1000; ms++) { smi_ctl_tick(&c, t + ms * 1000u); if (ms % 500 == 0) hb(&c, t + ms * 1000u); }+    t += 1000000u;+    smi_ctl_laser_readback(&c, true, (uint16_t)(c.code[LI] ^ 1), t);+    CHECK(!armed(&c) && c.fault == SMI_FAULT_READBACK, "wrong code in the readback: fault, off");+    cmd(&c, t, cf, 1, NULL); enable(&c, t, 1, SMI_LASER_KEY); set(&c, t, LI, 0, 20);+    for (int ms = 1; ms < 1000; ms++) { smi_ctl_tick(&c, t + ms * 1000u); if (ms % 500 == 0) hb(&c, t + ms * 1000u); }+    t += 1000000u;+    smi_ctl_laser_readback(&c, false, 0, t);+    CHECK(!armed(&c) && c.fault == SMI_FAULT_READBACK, "failed readback: fault, off");+    smi_ctl_laser_readback(&c, false, 0, t);+    CHECK(c.fault == SMI_FAULT_READBACK, "readback ignored while disarmed");+    cmd(&c, t, cf, 1, NULL);++    // DAC failure while on: fault, laser off.+    enable(&c, t, 1, SMI_LASER_KEY);+    set(&c, t, LI, 0, 10);+    for (int ms = 1; ms < 400; ms++) smi_ctl_tick(&c, t + ms * 1000u);+    t += 400000u; hb(&c, t);+    set(&c, t, LI, 0, 12);+    hw.fail_dac = true;+    for (int ms = 1; ms < 50; ms++) smi_ctl_tick(&c, t + ms * 1000u);+    // A gated head DAC verifies its own write, so a failed write reads as a readback fault.+    CHECK(!laser_pin_on() && (c.fault == SMI_FAULT_HW || (L->gate && c.fault == SMI_FAULT_READBACK)), "DAC failure: fault %u, off", c.fault);++    // State block layout.+    uint8_t st[160];+    size_t sl = smi_ctl_state(&c, t, st);+    uint32_t hsh = st[0] | (st[1] << 8) | (st[2] << 16) | ((uint32_t)st[3] << 24);+    CHECK(sl == 30u + 6u * SMI_NUM_CONTROLS && hsh == SMI_MAP_HASH && st[27] == SMI_NUM_CONTROLS, "state block");++    printf("%s: %d checks, %d failed (map %s, %d controls, laser limit %.1f mA, ramp %.1f mA/s)\n", fails ? "FAIL" : "OK", checks, fails, SMI_MAP_VERSION, SMI_NUM_CONTROLS, lim, L->ramp_per_s);+    return fails ? 1 : 0;+}
software/firmware/test/text_cmd_test.pyadded+112
@@ -0,0 +1,112 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: MIT+"""Drive the board contract's text commands into ctl_pty (the firmware's control+and text code behind a pseudo-terminal) and check the STATE frames and replies.+    ./ctl_pty 20 > pty.txt &  python3 text_cmd_test.py "$(head -1 pty.txt)" ../../dashboard/assets/controls.json+"""+import json, os, struct, sys, time, tty++pty, mapfile = sys.argv[1], sys.argv[2]+m = json.load(open(mapfile))+ids = [c["id"] for c in m["controls"]]+L = next(c for c in m["controls"] if c["role"] == "laser")+fd = os.open(pty, os.O_RDWR | os.O_NOCTTY)+tty.setraw(fd)   # raw, as a serial client opens it+os.set_blocking(fd, False)+buf = bytearray()+fails = checks = 0+++def crc16(b):+    c = 0xFFFF+    for x in b:+        c ^= x << 8+        for _ in range(8):+            c = ((c << 1) ^ 0x1021) & 0xFFFF if c & 0x8000 else (c << 1) & 0xFFFF+    return c+++def frames(wait):+    global buf+    out, t = [], time.time()+    while time.time() - t < wait:+        try:+            buf += os.read(fd, 4096)+        except BlockingIOError:+            time.sleep(0.01)+        while True:+            i = buf.find(b"\xa5\x5a")+            if i < 0 or len(buf) < i + 8:+                break+            n = struct.unpack_from("<H", buf, i + 4)[0]+            if len(buf) < i + 10 + n:+                break+            f = buf[i:i + 10 + n]+            buf = buf[i + 10 + n:]+            if crc16(f[2:8 + n]) == struct.unpack_from("<H", f, 8 + n)[0]:+                out.append((f[2], bytes(f[8:8 + n])))+    return out+++def state(wait=0.35):+    st = [p for t, p in frames(wait) if t == 0x12]+    p = st[-1]+    n = p[27]+    return {"on": bool(p[4] & 1), "fault": p[5], "codes": [struct.unpack_from("<H", p, 28 + 6 * i)[0] for i in range(n)]}+++def cmd(line, wait=0.35):+    os.write(fd, (line + "\n").encode())+    out = frames(wait)+    for t, p in out:+        if t == 4 and p.startswith(b"error"):+            print("  reply:", p.decode())+    return out+++def check(ok, what):+    global fails, checks+    checks += 1+    if not ok:+        fails += 1+        print("FAIL:", what)+++li = ids.index(L["id"])+g = L["guard"]+frames(1.5)                                   # current-readback zero check (laser off)+cmd("laser 2000", 0.6)+s = state()+check(s["on"] and s["codes"][li] == 2000 - g, f"laser 2000: armed, DAC {2000 - g} ({s})")+rep = [p.decode() for t, p in cmd("laser current", 0.3) if t == 4]+check(any(f"command_code=2000; dac_code={2000 - g}" in r for r in rep), f"laser current reply {rep}")+cmd("offset B 1000")+s = state()+ob = next(i for i, c in enumerate(m["controls"]) if c["kind"] == "dac" and c["ch"] == 1 and c["role"] == "offset")+check(not s["on"] and s["codes"][ob] == 1000, f"offset B: laser disarmed first, offset code 1000 ({s})")+cmd(f"laser {g}")+s = state()+check(not s["on"], f"laser {g} (guard): disarmed")+cmd(f"laser {g + 1}", 0.6)+s = state()+check(s["on"] and s["codes"][li] == 1, f"laser {g + 1}: DAC code 1 ({s})")+cmd("head 5")+s = state()+tia = ids.index("headTiaGain"); bias = ids.index("headMonitorBias")+check(not s["on"] and s["codes"][tia] == 1 and s["codes"][bias] == 2, f"head 5: disarmed, TIA bit 1, bias code 2 ({s})")+cmd("gain 7")+s = state()+gi = [ids.index(x) for x in ("monitorSecondStageGain", "externalSecondStageGain", "externalTiaGain")]+check(all(s["codes"][i] == 1 for i in gi), f"gain 7: all three Pico selectors set ({s})")+cmd("laser 3000", 0.6)+check(state()["on"], "re-armed by a fresh laser command")+cmd("laser 99999")+check(not state()["on"], "out-of-range laser code disarms")+cmd("laser 3000", 0.6)+cmd("x" * 80)+check(not state()["on"], "over-long line disarms")+cmd("laser 3000", 0.6)+cmd("laser off")+check(not state()["on"], "laser off")+print(f"{'OK' if not fails else 'FAIL'}: {checks} text-command checks, {fails} failed")+sys.exit(1 if fails else 0)
software/screenshots/controls-laser-off.pngadded
⋯ 1 unchanged line ⋯
software/screenshots/controls-tuned.pngadded
⋯ 1 unchanged line ⋯
software/screenshots/controls-tuning.pngadded
⋯ 1 unchanged line ⋯