by John Lauer
Two-board Molecule interferometer with onboard RP2040, USB-C data, 15 V USB-C PD power and a JST stage interface.
← Commit history
Software 1.3.1: test-stage firmware (J4 TMC2209, HOME, limits, self-test), Stage tab and Calibrate in smi-dash (simulated)
39 files changed
+3095−141
software/README.md+95−16software/controls/control-map.json+157−57software/controls/gen_controls.py+21software/dashboard/Cargo.lock+1−1software/dashboard/Cargo.toml+1−1software/dashboard/README.md+12−5software/dashboard/SKILL.md+19−8software/dashboard/assets/controls.json+1−1software/dashboard/assets/index.html+163−9software/dashboard/build.rs+4−3software/dashboard/csrc/stage_shim.c+12software/dashboard/src/controls.rs+11−3software/dashboard/src/engine.rs+119−2software/dashboard/src/eval.rs+1software/dashboard/src/main.rs+258−4software/dashboard/src/proto.rs+5software/dashboard/src/server.rs+143−2software/dashboard/src/sim.rs+48−1software/dashboard/src/stage.rs+1057software/dashboard/src/tune.rs+3−3software/dist/SHA256SUMS+3−3software/dist/smi-dash-linux-x64software/dist/smi-dash-windows-x64.exesoftware/dist/smi_pico.uf2software/firmware/CMakeLists.txt+1software/firmware/README.md+10−6software/firmware/src/main.c+123−6software/firmware/src/smi_controls_gen.h+3−3software/firmware/src/smi_stage.c+341software/firmware/src/smi_stage.h+163software/firmware/src/smi_text.c+1software/firmware/src/smi_text.h+2−1software/firmware/test/ctl_pty.c+54−6software/firmware/test/test_stage.c+228software/firmware/test/text_cmd_test.py+35software/screenshots/controls-tuned.pngsoftware/screenshots/stage-calibrate.pngsoftware/screenshots/stage-selftest.pngsoftware/screenshots/stage-step.pngsoftware/README.md+95−16@@ -1,12 +1,12 @@ # 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. 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.+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. Since board 1.2, and on board 1.3 now, 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. Board 1.3 adds a STAGE connector for the test stage: the Pico homes it, steps it and runs its self-test, and the dashboard uses it as the moving target to calibrate the board by itself. 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. -+ | 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, and the v1.2 command channel on the same link. |+| [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, the command channel on the same link, and the board 1.3 test-stage driver (TMC2209, HOME, limits, self-test). | | [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`. |@@ -17,17 +17,18 @@ 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`.+5. Board 1.3: 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`.+6. Test stage: open the **Stage** tab and press **Home**, or run `smi-dash stage home`. Step it, run the **Self-test**, or **Calibrate** (simulator only for now). 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 1.3: every setting from software -Boards v1.2 and v1.3 replace 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.3.0, and the board's `design/decision8-firmware.patch`), and takes commands on the same USB link that carries the samples.+Boards 1.2 and 1.3 replace 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.3.0, 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 `1.3.0-revision-1.3-controller-contract`. | Control (map id) | Where | Range | Scaling | Power-on | Firmware limits | CLI | |---|---|---|---|---|---|---|@@ -112,7 +113,76 @@ The control logic (limits, the gated write sequence, guard band, interlock, hear ### 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.+With **Board 1.3 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.++## Board 1.3: the test stage++Board 1.3 brings the stage controller out on J4, STAGE: GP10 STEP, GP11 DIR, GP12 EN_N (active low, pulled high on the board), GP13 the TMC2209's single-wire UART, GP14 HOME (a normally closed switch to ground, pulled up, so open or disconnected reads high). The test stage (`test-stage/`) turns a 17HS08 stepper through an M3 screw and a 10:1 lever: 15.625 nm of mirror travel per pulse, nominal, and 1600 pulses (25 um) of travel. The firmware follows `test-stage/design/stage-map.json`. Board 1.4 will put the RP2040 on the main board with the same GPIO numbers; the firmware does not change for it.++++**Nothing here has run on a stage.** Nothing is assembled. Every number below comes from the dashboard's simulated stage, labelled "simulated" on the page and in the CLI: the firmware's own stage code (`firmware/src/smi_stage.c`) against a simulated TMC2209 (CRC, registers, IFCNT) and a mechanism model with a true scale of 15.31 nm/pulse (inside the stage map's 14.64 to 16.65 nm geometry range, off nominal on purpose), 1.6 pulses of lost motion at each reversal, a 2 ms lever lag and 0.6 nm/s of thermal drift. These are model values, not measurements.++### What the firmware does++- **Disabled at boot.** EN_N is driven high before anything else touches the port, and stays high through configuration. The driver is disabled on a fault, on `stage off`, when USB goes away or the port closes, and (once a dashboard has sent a binary command) when the host is silent for the heartbeat timeout, 3 s; the dashboard sends heartbeats while the stage is enabled. The position becomes invalid whenever the driver is disabled.+- **Configured and checked over the UART.** With EN_N high: IOIN must report version 0x21, then GCONF, SLAVECONF, IHOLD_IRUN (27/31, about 0.41 A rms), CHOPCONF (16 microsteps, interpolation off) and VACTUAL are written with the stage map's values, every write checked by IFCNT advancing by one, GSTAT cleared, GCONF and CHOPCONF read back. Only then is EN_N pulled low. Idle, DRV_STATUS is read twice a second; over-temperature, a short or an open load disables it.+- **Homing as the stage map describes.** Towards HOME at 80 pulses/s to the first high, verified for 5 ms; back off until low plus 32 pulses; back in at 32 pulses/s; zero is the switch's opening edge. If HOME starts high, only a release search (at most 128 pulses) is allowed. Searches give up after 1920 pulses; a stuck or missing switch latches a fault.+- **Hard limits.** Before homing, only homing moves the stage. After homing, any move outside 0 to 1600 pulses is refused. HOME going high during a normal move away from zero disables the driver and invalidates the position.+- **Rate-limited steps.** 160 pulses/s by default, at most 640, with the stage map's STEP and DIR timing (3 us high, 3 us DIR setup and hold).+- **Retries never step twice.** Stage commands carry the frame's sequence number; a retried command returns the cached answer without new pulses. The dashboard now resends the same sequence number on every retry.+- **Self-test.** To pulse 128, then +128 four times and -128 four times, 1 s at each plateau (about 17 s at 160 pulses/s).++Binary op 0x09 on the existing command channel (status, home, step, speed, stop, off, current, selftest, move); a STAGE frame (type 0x13: the 24-byte state block and the sample-pair index) every 50 ms while enabled, else every 500 ms. The stage map's text commands work on the same port: `stage home`, `stage step N`, `stage speed [N]`, `stage current`, `stage status`, `stage stop`, `stage selftest`, plus `stage move N` and `stage off`. A text-only host is not held to the heartbeat; the USB disconnect rule still applies. The DIR polarity is a commissioning setting (`DIR_POS_LEVEL` in `smi_stage.c`): if the first homing search runs away from the switch, flip it.++### The Stage tab++**Home**, **Stop** and **Off**; a step size of 1, 8, 32, 128 or 512 pulses with **towards HOME** and **away** buttons; the speed (80, 160, 320 or 640 pulses/s); the position in pulses, the commanded position in nm and the position counted from the fringes. The **Stage position** plot replaces the spectrum while the tab is open: 30 s of the commanded position (pulses times the scale: nominal 15.625 nm/pulse until Calibrate fits one) against the counted position (fringes times 329 nm), placed on the commanded trace where the stage last finished homing, plus the simulated mirror, dashed, on the simulator.++++**Self-test** runs the firmware's sequence and analyses the plateaus as the stage map asks: the scale fitted to the counted fringe edges (each edge placed at the stage position where it happened, so the slope is resolved far below one fringe), a plateau fit with a drift term, forward against reverse plateaus at the same position, and the return residual. A whole-fringe counter resolves 329 nm, so a return residual of "0 nm counted" means within one fringe; on the simulator the page also shows the true mirror's residual. If the counted scale is far outside the geometry range (laser off, or fringes missed), it says so instead of reporting a scale.++Simulated self-test after Calibrate: 15.284 nm/pulse from 46 counted fringe edges (outbound 15.273, return 15.296), return residual 0 nm counted; the simulated mirror's own fit is 15.274 nm/pulse and its return residual -19.6 nm, the 1.6 pulses of modelled lost motion. Before Calibrate (75 mA, power-on -5 V/V), the outbound sweep counted no fringes at all and the self-test said fringes were missed.++### Calibrate: the board calibrates itself++Tune needs a moving target, and the stage is one. **Calibrate** (or `smi-dash calibrate --beam-safe`) homes the stage, then:++1. records the settings and steps the stage 1024 pulses (16 um nominal) from pulse 128, counting fringes, as the board is;+2. turns the laser off and waits for the current readback's zero code to settle;+3. turns it back on at the same set-point and auto-centres both channels;+4. runs Tune while the stage moves back and forth between pulses 200 and 1400 at 640 pulses/s;+5. steps the 1024 pulses again, counting fringes and fitting the scale to the fringe edges;+6. prints a before/after report and uses the fitted scale for the commanded trace from then on.++It turns the laser off and on, so it needs the interlock: the page's checkbox, or `--beam-safe`. It runs on the simulator only for now and refuses on a Pico.++++A simulated run from an untuned board (75 mA, -5 V/V), `smi-dash calibrate --beam-safe`, 43 s:++| | Before | After |+|---|---|---|+| Laser current | 75.00 mA | 95.13 mA |+| Channel 1 second stage | -5 V/V | -20 V/V |+| Fringe score while moving | 15.5 | 80.8 |+| 1024-pulse step, counted | 0 nm (0 fringes) | 15,463 nm (47 fringes) |+| Scale from fringe edges | none | 15.338 nm/pulse |+| Simulated mirror travel | 15,680 nm | 15,660 nm |++The fitted 15.338 nm/pulse is within 0.2 % of the simulated mechanism's 15.31 (the remaining difference is the lost motion and the fit over 47 edges), where the nominal 15.625 is 2 % off. A real stage will need this run, and the self-test, on the bench; the stage map's measurement procedure (stationary windows, temperature, drift fits, sub-fringe phase from raw samples) still applies.++### CLI for the stage++```+smi-dash stage | stage home | stage step 128 | stage step -2000 --nm | stage move 640+smi-dash stage speed 320 | stage stop | stage off | stage current | stage align+smi-dash stage selftest | stage selftest --status+smi-dash calibrate --beam-safe [--check-pulses 1024] | calibrate --status | calibrate --stop+```++`home`, `step`, `move` and `selftest` wait until done (`--no-wait` returns at once); every verb takes `--json`. Refusals name the reason, for example `ERROR: the stage is not homed: only homing may move it` with `Hint: Home it first`. ## What the numbers are @@ -127,6 +197,7 @@ With **Board v1.2 model** on (the default), the simulator's laser current comes | 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) |+| Stage | 15.625 nm per pulse nominal, 0 to 1600 pulses, 160 pulses/s default, 640 at most | `test-stage/design/stage-map.json`; J4 GP10 to GP14 (control map `stage` entry) | ## The dashboard @@ -162,7 +233,7 @@ Every verb prints `OK:` or `ERROR:` first and a `Hint:` with the next command; ` ``` smi-dash start | show | ls | health | status | stop smi-dash source sim | source serial [--serial-port COM5]-smi-dash sim --profile constant|sine|step|hand|hold --speed-um-s 1000 --amp-um 10 --freq-hz 1 --c 3 --noise 1 --multimode on|off+smi-dash sim --profile constant|sine|step|hand|hold|stage --speed-um-s 1000 --amp-um 10 --freq-hz 1 --c 3 --noise 1 --multimode on|off smi-dash detect --lp-hz 10000 --threshold 0.35 --invert on|off smi-dash view --window-ms 20 --history-s 6 --pause | --resume smi-dash zero@@ -172,7 +243,7 @@ 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.+The board verbs (`laser`, `offset`, `gain`, `bias`, `ctl`, `board`, `tune`, `eval --board`) are listed under board 1.3 above, and the stage verbs (`stage`, `calibrate`) under the test stage. ## Fringe detection, and how well it works @@ -214,7 +285,7 @@ How to read it: ## The simulator -The laser's excess phase follows the Lang-Kobayashi steady-state equation `phi_F = phi_0 - C sin(phi_F + atan(alpha))` with `phi_0 = 4 pi L / lambda`, solved on its stable branch with hysteresis, so C below 1 gives a near-sinusoid and C above 1 the leaning sawtooth. The power is `P0 (1 + m cos phi_F)`. Multimode adds a second longitudinal mode spaced `lambda^2 / (2 x 1.46 mm)` = 0.148 nm away, which makes the fringe envelope null every 1.46 mm. Target motions: constant speed with reversals, sine, step and return, a hand-held target (smooth wander plus a 9 Hz tremor) and hold.+The laser's excess phase follows the Lang-Kobayashi steady-state equation `phi_F = phi_0 - C sin(phi_F + atan(alpha))` with `phi_0 = 4 pi L / lambda`, solved on its stable branch with hysteresis, so C below 1 gives a near-sinusoid and C above 1 the leaning sawtooth. The power is `P0 (1 + m cos phi_F)`. Multimode adds a second longitudinal mode spaced `lambda^2 / (2 x 1.46 mm)` = 0.148 nm away, which makes the fringe envelope null every 1.46 mm. Target motions: constant speed with reversals, sine, step and return, a hand-held target (smooth wander plus a 9 Hz tremor), hold, and the test stage's mirror. The electronics follow the board netlist: photodiode current into the TIA (4.7 k monitor, 47 k external), the 1:2 divider and inverting x20 stage (net gain -10) about the offset trim, the 3.9 k / 1 n pole and the Sallen-Key stage, then the RP2040 ADC with 12-bit quantisation, about 1.3 LSB rms noise and its wide codes at 512, 1536, 2560 and 3584. The simulator runs at 500 kHz and samples channel 1 on even ticks and channel 2 on odd ticks, exactly like the firmware's round robin. @@ -228,11 +299,15 @@ 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.-- 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.+- Control core (since board 1.2): `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.+- 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; 20 with the stage checks below).+- Control serial 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.+- Controls in the 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. `controls-tuned.png` is from the 1.3.1 build; the laser-off and tuning screenshots are from the 1.2.1 build, whose Controls tab is the same. The Windows build's `eval --board` output is identical to the Linux build's.+- Stage core: `firmware/test/test_stage.c` runs `smi_stage.c` against a mock TMC2209 (CRC, registers, IFCNT) and a mock screw and HOME switch, 62 checks: disabled at boot, every configuration write made with EN_N high, the driver refused on a dead UART, a wrong version or a stuck IFCNT, the TMC CRC against a published vector, homing from off the switch and from on it, a stuck and a missing switch, limits before and after homing, unexpected HOME, the step rate at 80, 160 and 640 pulses/s, stop mid-move keeping a valid position, duplicate sequence numbers issuing no pulses, the self-test plateaus and dwells, DRV_STATUS faults and link loss.+- Stage text commands and frames: `text_cmd_test.py` now also checks the stage through `ctl_pty.c` (20 checks in all): disabled at boot, a step refused before homing, a speed of 700 refused, home to 0 seen in a STAGE frame of the right size, a move past 1600 refused, 200 pulses at 640 pulses/s, `stage current`, and `stage off` invalidating the position.+- Stage serial path: `smi-dash source serial` against the stand-in: refused before homing, home, moves to 300, 299, 0 and 1600 (2966 pulses issued, the screw where the firmware thinks it is), and the stage stayed enabled while the dashboard's heartbeats ran, then latched `link_lost` and disabled after `kill -9` of the dashboard.+- Stage dashboard: the simulated stage runs the firmware's stage code; every stage verb, the Stage tab, the self-test and Calibrate were run against it, and the stage screenshots and clips are from those runs.+- **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. The stage driver has never moved a motor: the bit-banged half-duplex UART (with interrupts off for each 87 us byte), the DIR polarity, the HOME switch, the step timing under streaming load and the winding current all need checking at commissioning, with the laser interlock active, as the stage page says. ## Building from source @@ -249,6 +324,10 @@ cmake --build firmware/build # firmware/build/smi_pico.uf2 cd dashboard && cargo build --release # target/release/smi-dash cargo build --release --target x86_64-pc-windows-gnu --no-default-features # Windows, CSV only cargo test --release++# host tests+cc -O2 -Ifirmware/src firmware/test/test_stage.c firmware/src/smi_stage.c -o test_stage && ./test_stage+cc -O2 -Ifirmware/src firmware/test/test_ctl.c firmware/src/smi_ctl.c -lm -o test_ctl && ./test_ctl ``` MIT licence, as the rest of this page.
software/controls/control-map.json+157−57@@ -1,7 +1,7 @@ { "schema": "interferometer/control-map/1",- "hardwareVersion": "1.2.0",- "status": "revision-1.2-controller-contract",+ "hardwareVersion": "1.3.0",+ "status": "revision-1.3-controller-contract", "i2c": { "controller": "I2C0", "sda": {@@ -84,7 +84,7 @@ "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.",+ "signal": "HEAD_DAC_LOCAL stays on the head. The Pico commands the DAC over J2 pin 9 (SDA) and pin 10 (SCL).", "device": "headDac", "commandMapping": { "dacCodeEquation": "max(command_code - 45, 0)",@@ -109,7 +109,7 @@ "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+ "cablePin": 11 }, "monitorOffset": { "dacChannel": "B",@@ -150,7 +150,7 @@ }, "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."+ "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." }, "headMonitorBias": { "expanderBits": [@@ -212,7 +212,7 @@ "0": 46836, "1": 150000 },- "equation": "GP9 low enables the 68.1 kΩ switched branch in parallel with the permanent 150 kΩ feedback.",+ "equation": "GP9 low enables the 68.1 k\u03a9 switched branch in parallel with the permanent 150 k\u03a9 feedback.", "powerOnDefault": 46836 } },@@ -235,13 +235,13 @@ "device": "ADS1115", "location": "laser head", "i2cAddress": "0x49",- "channel": "AIN0–AIN1, differential Kelvin shunt",+ "channel": "AIN0\u2013AIN1, 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."+ "firmwareConfig": "ADS1115 at 0x49, differential AIN0\u2013AIN1, \u00b10.512 V, 128 SPS, continuous. Configure and set conversion pointer while disarmed; armed access is read-only." }, "mainAnalogRail": { "gpio": 28,@@ -285,73 +285,173 @@ "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": [+ "type": "12-position JST PH premade harness",+ "assemblyMpn": "CON-JST-PH-12-FF",+ "supplier": "ABRA Electronics",+ "lengthMm": 200,+ "connectorMpn": "S12B-PH-SM4-TB",+ "reference": "J2 on both boards",+ "pins": [ {- "pins": [- 1,- 2- ],- "signals": [- "NC_SPARE",- "LASER_EN"- ]+ "pin": 1,+ "signal": "LASER_SUPPLY",+ "mainNet": "/MAIN_PORT_5V_OUTPUT",+ "headNet": "/RAW_HEAD_5V" }, {- "pins": [- 3,- 6- ],- "signals": [- "MONITOR_AMP_OUT",- "ANALOG_RETURN"- ]+ "pin": 2,+ "signal": "LASER_SUPPLY_RETURN",+ "mainNet": "/CABLE_POWER_RETURN",+ "headNet": "/GND" }, {- "pins": [- 4,- 5- ],- "signals": [- "HEAD_5V",- "HEAD_POWER_RETURN"- ]+ "pin": 3,+ "signal": "MONITOR_AMP_OUT",+ "mainNet": "/MONITOR_JACK",+ "headNet": "/MONITOR_JACK" }, {- "pins": [- 7,- 8- ],- "signals": [- "SDA",- "SCL"- ]+ "pin": 4,+ "signal": "ANALOG_RETURN",+ "mainNet": "/ANALOG_RETURN_JACK",+ "headNet": "/ANALOG_RETURN_JACK"+ },+ {+ "pin": 5,+ "signal": "HEAD_5V",+ "mainNet": "/MAIN_PORT_5V_OUTPUT",+ "headNet": "/RAW_HEAD_5V"+ },+ {+ "pin": 6,+ "signal": "HEAD_POWER_RETURN",+ "mainNet": "/CABLE_POWER_RETURN",+ "headNet": "/GND"+ },+ {+ "pin": 7,+ "signal": "GUARD_GND",+ "mainNet": "/CABLE_POWER_RETURN",+ "headNet": "/GND"+ },+ {+ "pin": 8,+ "signal": "GUARD_GND",+ "mainNet": "/CABLE_POWER_RETURN",+ "headNet": "/GND"+ },+ {+ "pin": 9,+ "signal": "SDA",+ "mainNet": "/SDA_JACK",+ "headNet": "/SDA_JACK"+ },+ {+ "pin": 10,+ "signal": "SCL",+ "mainNet": "/SCL_JACK",+ "headNet": "/SCL_JACK"+ },+ {+ "pin": 11,+ "signal": "LASER_EN",+ "mainNet": "/LASER_EN_JACK",+ "headNet": "/LASER_EN_JACK"+ },+ {+ "pin": 12,+ "signal": "SPARE_GND",+ "mainNet": "/CABLE_POWER_RETURN",+ "headNet": "/GND" } ],- "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",+ "headFeedNominal_V": 5.296, "cableSideI2cPullUpOhms": 4700,- "draftI2cTransientLimitSeriesOhmsPerEnd": 270,+ "i2cTransientLimitSeriesOhmsPerEnd": 180, "watchdogs": { "enableCarrier_Hz": 10000, "firmwareReadbackInterval_ms": 2,- "busMonostableTiming": "100 kΩ and 100 nF; exact guaranteed timeout pending component and circuit qualification"+ "busMonostableTiming": "100 k\u03a9 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."+ "referenceNote": "Pins 1 and 5 share the regulated head feed. Pins 2 and 6 share the power return. Pin 4 is the dedicated analog monitor return. The laser current sink and the analog set-point are local to the head." }, "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)",+ "laser": "laser CODE (0\u20134095) or laser off",+ "head": "head MASK (0\u20137, MCP23008 GP0\u20132)",+ "gain": "gain MASK (0\u20137, Pico GP7\u20139)",+ "offset": "offset B CODE or offset C CODE (0\u20134095)", "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"+ },+ "stage": {+ "reference": "J4",+ "label": "STAGE",+ "connectorMpn": "SM08B-GHS-TB(LF)(SN)",+ "pins": [+ {+ "pin": 1,+ "signal": "GND",+ "direction": "return"+ },+ {+ "pin": 2,+ "signal": "STEP",+ "gpio": 10,+ "modulePin": 14,+ "direction": "output",+ "seriesOhms": 68,+ "externalPull": "10k to GND"+ },+ {+ "pin": 3,+ "signal": "DIR",+ "gpio": 11,+ "modulePin": 15,+ "direction": "output",+ "seriesOhms": 68+ },+ {+ "pin": 4,+ "signal": "EN_N",+ "gpio": 12,+ "modulePin": 16,+ "direction": "output",+ "seriesOhms": 68,+ "activeLow": true,+ "externalPull": "10k to local 3V3"+ },+ {+ "pin": 5,+ "signal": "UART",+ "gpio": 13,+ "modulePin": 17,+ "direction": "bidirectional",+ "seriesOhms": 68,+ "protocol": "TMC2209 PDN_UART, 3.3 V, single-wire half duplex"+ },+ {+ "pin": 6,+ "signal": "HOME",+ "gpio": 14,+ "modulePin": 19,+ "direction": "input",+ "seriesOhms": 68,+ "externalPull": "10k to local 3V3"+ },+ {+ "pin": 7,+ "signal": "3V3",+ "direction": "reference output",+ "seriesOhms": 75,+ "maxCurrentMa": 50,+ "usage": "High-impedance logic reference only, with external stage power"+ },+ {+ "pin": 8,+ "signal": "GND",+ "direction": "return"+ }+ ] } }
software/controls/gen_controls.py+21@@ -15,6 +15,7 @@ Both carry the same FNV-1a hash of the normalised map; the firmware reports it in every STATE frame and the dashboard warns when the two differ. """ import json+import re import math import sys from pathlib import Path@@ -411,10 +412,30 @@ def c_header(n, h): return "\n".join(L) + "\n" +def check_stage(src):+ """The board map's stage entry must match the pins compiled into the stage core."""+ st = src.get("stage")+ if not st:+ return+ hdr = (ROOT / "firmware/src/smi_stage.h").read_text()+ want = {"STEP": "SMI_STAGE_STEP_GPIO", "DIR": "SMI_STAGE_DIR_GPIO", "EN_N": "SMI_STAGE_EN_N_GPIO",+ "UART": "SMI_STAGE_UART_GPIO", "HOME": "SMI_STAGE_HOME_GPIO"}+ for p in st["pins"]:+ if p["signal"] in want:+ m = re.search(r"#define " + want[p["signal"]] + r" (\d+)", hdr)+ if not m or int(m.group(1)) != p["gpio"]:+ sys.exit(f"ERROR: stage {p['signal']} is GP{p['gpio']} in the map but {m.group(1) if m else 'missing'} in smi_stage.h")+ en = next(p for p in st["pins"] if p["signal"] == "EN_N")+ if not en.get("activeLow"):+ sys.exit("ERROR: the stage core assumes EN_N active low")+ print(f"OK: stage pins match the map (J4: STEP GP{want and next(p['gpio'] for p in st['pins'] if p['signal']=='STEP')} .. HOME GP{next(p['gpio'] for p in st['pins'] if p['signal']=='HOME')})")++ def main(): if len(sys.argv) != 2: sys.exit("usage: gen_controls.py <control-map.json>") src = json.loads(Path(sys.argv[1]).read_text())+ check_stage(src) if str(src.get("schema", "")).startswith("interferometer/control-map/"): src = from_board_schema(src) n = normalise(src)
software/dashboard/Cargo.lock+1−1@@ -1285,7 +1285,7 @@ checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" [[package]] name = "smi-dash"-version = "1.2.1"+version = "1.3.1" dependencies = [ "axum", "cc",
software/dashboard/Cargo.toml+1−1@@ -1,6 +1,6 @@ [package] name = "smi-dash"-version = "1.2.1"+version = "1.3.1" edition = "2021" license = "MIT" description = "Dashboard, simulator and CLI for a self-mixing laser interferometer read by a Raspberry Pi Pico"
software/dashboard/README.md+12−5@@ -4,15 +4,16 @@ 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; 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/sim.rs` | Lang-Kobayashi self-mixing model, target motions, multimode beat, the board's analog chain and the RP2040 ADC; with the board model, the laser's current dependence (power, tuning, mode hops); the `stage` profile follows the test stage's mirror |+| `src/controls.rs` | Board controls (1.2 and 1.3): 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/stage.rs` | Board 1.3 test stage: the protocol, the simulated stage (the firmware's `smi_stage.c` compiled in, a simulated TMC2209 and a mechanism model), the self-test analysis, Calibrate | | `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 suites against the simulator's ground truth (`--suite`, and `--board` through the simulated v1.2 board) |+| `src/eval.rs` | Offline accuracy suites against the simulator's ground truth (`--suite`, and `--board` through the simulated board) | | `src/main.rs` | CLI | ## Use@@ -25,6 +26,8 @@ smi-dash sim --profile sine --amp-um 10 --freq-hz 1 smi-dash source serial # first Pico found; --serial-port COM5 to choose smi-dash record start --format csv --seconds 10 smi-dash eval --suite # the published error table+smi-dash stage home # test stage: home, step 128, step -500 --nm, selftest+smi-dash calibrate --beam-safe # the board calibrates itself with the stage as the moving target (simulator) smi-dash stop ``` @@ -46,14 +49,18 @@ Run `smi-dash --help` or `smi-dash <verb> --help` for every flag. Each answer st | `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 |+| `GET /stage` | Stage state, the 30 s commanded-against-counted trace, the self-test and Calibrate results |+| `POST /stage/cmd` | `{action: status\|home\|step\|move\|speed\|stop\|off\|current\|selftest, value, unit: pulses\|nm}` |+| `POST /stage/align`, `GET /stage/selftest` | Put the counted trace on the commanded one now; the last self-test |+| `GET/POST /calibrate`, `POST /calibrate/stop` | Calibrate (`{confirm: "beam-safe"}`), its progress and report | -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.+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, or the stage driver is enabled, the server sends the firmware a heartbeat every second; if the server stops, the firmware turns the laser off and disables the stage 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 ``` 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 # Linux, needs libudev-dev, libhdf5-dev (and a C compiler: build.rs compiles smi_ctl.c and smi_stage.c) cargo build --release --target x86_64-pc-windows-gnu --no-default-features # Windows, CSV only cargo test --release ```
software/dashboard/SKILL.md+19−8@@ -4,10 +4,12 @@ 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, 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,+ simulated ground truth, and on board 1.3 every board setting: laser enable and current, offsets,+ gains, monitor bias, auto-centre and tune for fringes, plus the test stage: home, step, stop, a+ self-test, and Calibrate, where the stage is the moving target and the board calibrates itself. 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.+ centre a channel, change a gain, check the detector's error, move or home the stage, run the stage self-test,+ or calibrate the board. --- # smi-dash@@ -21,14 +23,21 @@ 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+`sim --profile constant|sine|step|hand|hold|stage ...`, `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|--board`, `stop`. -Board v1.2: `laser on --beam-safe|off|current <mA> [--wait]|read`, `offset ch1|ch2 <V> [--counts]`,+Board 1.3: `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]`. +Test stage (board 1.3 J4): `stage [status]`, `stage home`, `stage step N [--nm]`, `stage move POS`,+`stage speed PPS`, `stage stop`, `stage off`, `stage current`, `stage align`, `stage selftest [--status]`,+`calibrate --beam-safe [--status|--stop]`. Home before moving (the firmware refuses otherwise); moves stay+in 0..1600 pulses (15.625 nm each, nominal). On the simulator every stage result is simulated: say so,+and never present it as a measurement. Calibrate turns the laser off and on, so it needs the same+human confirmation as `laser on`; it runs on the simulator only for now.+ 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@@ -38,8 +47,9 @@ with `--wait`, rather than in small steps. Tune needs a moving target. After a g Selectors for `ui click`: `#btn-pause #btn-zero #btn-record #btn-settings #src-sim #src-serial [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.+#laser-off [data-ctl=<map id>][data-v=<value>] #tab-stage #st-home #st-stop #st-off #st-neg #st-posb+#st-sizes button[data-n=128] #st-speeds button[data-n=640] #st-test #cal-interlock #cal-go`. Enabling the laser needs a real one-second hold on the+page, so use the CLI for that. `ui tab board|stage|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) @@ -56,4 +66,5 @@ manual display, FIRST load the `webview` skill (adom-workspace-control) and foll Counting resolves one fringe (329 nm at 658 nm). Keep the fringe rate under about two thirds of the detector low-pass (default 10 kHz, so about 2 mm/s); raise `--lp-hz` to 60000 for up to 5 mm/s. 10 mm/s-fails. The multimode laser case fails on purpose. Not yet verified on physical hardware.+fails. The multimode laser case fails on purpose. Not yet verified on physical hardware; the stage is+not assembled, so no stage result is a measurement.
software/dashboard/assets/controls.json+1−1@@ -1 +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"}}+{"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.3.0-revision-1.3-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"}}
software/dashboard/assets/index.html+163−9@@ -159,6 +159,25 @@ aside.board-mode #tune-msg{display:none} .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}+/* Stage tab */+.plots.stage-mode{grid-template-rows:1fr .55fr .75fr 1.7fr}+.plots.stage-mode #card-spec{display:none}+#card-stage{display:none}.plots.stage-mode #card-stage{display:flex}+.simtag{font:600 10px var(--f-mono);letter-spacing:.4px;padding:1px 6px;border-radius:10px;color:var(--yellow);border:1px solid color-mix(in srgb,var(--yellow) 60%,transparent);background:color-mix(in srgb,var(--yellow) 10%,transparent)}+.pill.move{color:var(--accent-bright);border-color:var(--accent)}+.pill.idle{color:var(--green);border-color:var(--green)}+.btnrow{display:grid;grid-template-columns:repeat(3,1fr);gap:5px}+.btnrow .btn,.dirrow .btn{padding:4px 6px;font-size:12px}+.dirrow{display:grid;grid-template-columns:1fr 1fr;gap:5px}+.resline{font:11px var(--f-mono);color:var(--text-body);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}+.resline b{color:var(--text);font-weight:600}+.resline.warn{color:var(--yellow);white-space:normal}+table.ba{width:100%;border-collapse:collapse;font:11px var(--f-mono)}+table.ba td{padding:1px 2px;white-space:nowrap}+table.ba td:first-child{font:11px var(--f-body);color:var(--text-2);overflow:hidden;text-overflow:ellipsis;max-width:120px}+table.ba td.n{text-align:right;color:var(--text)}+table.ba td.n.good{color:var(--accent-bright)}+table.ba th{font:600 10px var(--f-body);color:var(--text-3);text-align:right;padding:0 2px} /* ?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)}@@ -204,6 +223,12 @@ html.framed #app{position:absolute;inset:0;margin:auto;width:min(100vw,177.7778v <span class="r" id="disp-r"></span></div> <div class="cv" data-tip="Running position from the fringe count, lambda/2 per fringe. Scroll to change the span (0.5 to 120 s)."><canvas id="cv-disp"></canvas></div> </div>+ <div class="card" id="card-stage">+ <div class="ct">Stage position+ <span class="lg"><span><i style="background:var(--yellow)"></i>commanded</span><span><i style="background:var(--accent)"></i>counted from fringes</span><span id="lg-stage-truth"><i style="background:var(--text-3)"></i>simulated mirror</span></span>+ <span class="r" id="stage-r"></span></div>+ <div class="cv" data-tip="Last 30 s. Commanded: the stage position in pulses times the scale (nominal 15.625 nm/pulse until Calibrate fits it). Counted: the fringe count times 329 nm, placed on the commanded trace where the stage last finished homing (Align moves that point to now)."><canvas id="cv-stage"></canvas></div>+ </div> <div class="card" id="card-spec"> <div class="ct">Spectrum <span class="lg"><span><i style="background:var(--accent)"></i>channel 1</span><span><i style="background:var(--ch2)"></i>channel 2</span></span>@@ -225,7 +250,8 @@ html.framed #app{position:absolute;inset:0;margin:auto;width:min(100vw,177.7778v </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-board" class="is-on" data-tip="Board 1.3: 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-stage" data-tip="Test stage on the STAGE connector (board 1.3 J4): home, step, stop, self-test and Calibrate. Also `smi-dash stage` and `smi-dash calibrate`.">Stage</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">@@ -264,6 +290,42 @@ html.framed #app{position:absolute;inset:0;margin:auto;width:min(100vw,177.7778v <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-stage">+ <div class="panel" id="p-stage">+ <div class="ph"><span class="lbl">Stage</span><span class="simtag" id="stage-sim" data-tip="The simulated stage runs the firmware's own stage code (smi_stage.c) against a simulated TMC2209 and mechanism. Nothing is assembled yet: no number here is a measurement.">SIMULATED</span><span class="pill" id="stage-pill">OFF</span></div>+ <div class="kv3">+ <div class="kv" data-tip="Pulses from HOME (0 to 1600), one microstep each."><div class="lbl">Position</div><div class="v" id="st-pos">n/a</div></div>+ <div class="kv" data-tip="Position times the scale: nominal 15.625 nm/pulse until Calibrate fits it."><div class="lbl">Commanded</div><div class="v" id="st-cmd">n/a</div></div>+ <div class="kv" data-tip="Counted from the fringes (329 nm each), placed on the commanded position at the last home."><div class="lbl">Counted</div><div class="v meas" id="st-meas">n/a</div></div>+ </div>+ <div class="hint" id="st-line"></div>+ <div class="btnrow">+ <button class="btn primary" id="st-home" data-tip="Configure the TMC2209 over its UART (every write checked against IFCNT), enable it, and home: 80 pulses/s to the switch, back off, 32 pulses/s to its opening edge, which is zero.">Home</button>+ <button class="btn" id="st-stop" data-tip="Stop motion now. The driver stays enabled and the position stays valid.">Stop</button>+ <button class="btn off" id="st-off" data-tip="Disable the driver (EN_N high). The position becomes invalid until the next home.">Off</button>+ </div>+ <div class="sw-row" data-tip="Pulses per step. Nominal 15.625 nm per pulse at the mirror; 21 pulses is about one fringe."><span>Step</span><div class="seg" id="st-sizes"></div></div>+ <div class="dirrow">+ <button class="btn" id="st-neg" data-tip="Step towards HOME (negative). Refused below 0.">◀ towards HOME</button>+ <button class="btn" id="st-posb" data-tip="Step away from HOME (positive). Refused above 1600 pulses.">away ▶</button>+ </div>+ <div class="sw-row" data-tip="Step rate. The stage map's default is 160 pulses/s (2.5 µm/s nominal), its maximum 640."><span>Speed</span><div class="seg" id="st-speeds"></div></div>+ </div>+ <div class="panel" id="p-selftest">+ <div class="ph"><span class="lbl">Self-test</span><span id="st-test-t" class="hint"></span>+ <button class="btn primary" style="margin-left:auto;padding:3px 12px" id="st-test" data-tip="The stage map's sequence: to pulse 128, then +128 four times and -128 four times, 1 s at each plateau (about 17 s). Reports the scale fitted to the counted fringe edges, the plateau fit with drift, the reversal errors and the return residual. Needs the laser on to count fringes.">Run</button></div>+ <div class="resline" id="st-r1">Steps out and back; reports the residual in nm.</div>+ <div class="resline" id="st-r2"></div>+ <div class="resline" id="st-r3"></div>+ </div>+ <div class="panel" id="p-cal">+ <div class="ph"><span class="lbl">Calibrate</span><span id="cal-t" class="hint"></span>+ <button class="btn primary" style="margin-left:auto;padding:3px 12px" id="cal-go" disabled data-tip="Uses the stage as the moving target: homes, checks a 1024-pulse step as things are, zeroes the current readback with the laser off, turns it back on, auto-centres, tunes while the stage moves back and forth, checks the step again, and reports before and after. Simulator only for now.">Calibrate</button></div>+ <div class="ilock" id="cal-interlock" role="checkbox" aria-checked="false" data-tip="Calibrate turns the class 3B laser off and on. Enclose the beam path or wear 658 nm eyewear first."><span class="box"></span><span>Beam path enclosed or eyewear on</span></div>+ <div class="tunebar"><i id="cal-bar"></i></div>+ <table class="ba" id="cal-table"></table>+ </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">@@ -289,12 +351,13 @@ html.framed #app{position:absolute;inset:0;margin:auto;width:min(100vw,177.7778v <button data-profile="step" data-tip="Smooth step out, dwell, and return to the start.">Step</button> <button data-profile="hand" data-tip="A hand-held target: slow wander plus a 9 Hz tremor.">Hand</button> <button data-profile="hold" data-tip="Target held still.">Hold</button>+ <button data-profile="stage" data-tip="The target is the test stage's mirror, moved from the Stage tab.">Stage</button> </div> <div id="motion-sliders"></div> <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 class="toggle" id="board-toggle" role="switch" aria-pressed="true" data-tip="Model board 1.3 (software controls since 1.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 1.3 model</span><span class="sw"></span></div> </div> </div> </aside>@@ -537,6 +600,7 @@ function render(){ $("#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();+ renderStage(); } // motion sliders per profile@@ -547,12 +611,13 @@ const MOTION={ step:[["step_um","Step",LOG(1,100),v=>v.toFixed(v<10?1:0)+" µm","Step size; the target returns after each dwell."],["dwell_s","Dwell",LOG(0.05,3),v=>v.toFixed(2)+" s","Time held at each end."]], hand:[["jitter_um","Wander",LOG(0.2,10),v=>v.toFixed(1)+" µm","RMS slow wander of a hand-held target."],["tremor_um","Tremor",LOG(0.02,2),v=>v.toFixed(2)+" µm","9 Hz tremor amplitude."]], hold:[],+ stage:[], }; let builtFor=null; function buildMotion(prof){ if(builtFor===prof) return; builtFor=prof; const box=$("#motion-sliders"); box.innerHTML="";- if(!MOTION[prof].length){ box.innerHTML='<div class="hint">Target is still. Watch the noise floor and drift.</div>'; return }+ if(!MOTION[prof].length){ box.innerHTML=prof==="stage"?'<div class="hint">The target is the stage mirror: move it from the Stage tab.</div>':'<div class="hint">Target is still. Watch the noise floor and drift.</div>'; return } for(const [key,label,map,fmt,tip] of MOTION[prof]){ const d=document.createElement("div"); d.className="slider"; d.dataset.tip=tip; d.innerHTML=`<span>${label}</span><input type="range" min="0" max="1000" step="1" id="${key==="speed_um_s"?"speed-slider":key+"-slider"}"><output></output>`;@@ -571,7 +636,7 @@ function applyState(){ $("#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":"")+(sim.board?" · board v1.2":" · board v1.1"));+ $("#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 1.3":" · 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();@@ -630,9 +695,11 @@ $("#s-invert").onclick=()=>post("detect",{invert:!S.detect.invert}).then(()=>toa // ---------------------------------------------------------------- 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");+function setTab(t){ if(!["board","stage","sim"].includes(t)) t="board";+ for(const k of ["board","stage","sim"]){ $("#tab-"+k).classList.toggle("is-on",t===k); $("#body-"+k).classList.toggle("hide",t!==k) }+ document.querySelector("aside").classList.toggle("board-mode",t!=="sim"); document.querySelector(".plots").classList.toggle("stage-mode",t==="stage");+ localStorage.setItem("smi-tab",t); requestAnimationFrame(render) }+$("#tab-board").onclick=()=>setTab("board"); $("#tab-stage").onclick=()=>setTab("stage"); $("#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(){@@ -710,7 +777,7 @@ function renderBoard(){ 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];+ for(const r of document.querySelectorAll(".sw-row[data-ctl]")){ 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;@@ -724,6 +791,93 @@ function renderBoard(){ } let lastOn=false; +// ------------------------------------------------------------------- Stage --+const STEP_SIZES=[1,8,32,128,512], SPEEDS=[80,160,320,640];+let stepSize=+(localStorage.getItem("smi-step")||128);+const stageCmd=(action,value)=>post("stage/cmd",value==null?{action}:{action,value});+(function(){+ const sz=$("#st-sizes"); sz.innerHTML=STEP_SIZES.map(n=>`<button data-n="${n}" data-tip="${n} pulse${n>1?"s":""}, ${(n*15.625).toFixed(n<8?1:0)} nm nominal">${n}</button>`).join("");+ for(const b of sz.querySelectorAll("button")) b.onclick=()=>{ stepSize=+b.dataset.n; localStorage.setItem("smi-step",stepSize); renderStage() };+ const sp=$("#st-speeds"); sp.innerHTML=SPEEDS.map(n=>`<button data-n="${n}" data-tip="${n} pulses/s, ${(n*15.625/1000).toFixed(2)} µm/s nominal">${n}</button>`).join("");+ for(const b of sp.querySelectorAll("button")) b.onclick=()=>stageCmd("speed",+b.dataset.n);+})();+$("#st-home").onclick=()=>stageCmd("home").then(j=>{ if(j&&j.status==="ok") toast("Homing: configuring the TMC2209, then seeking the HOME edge") });+$("#st-stop").onclick=()=>stageCmd("stop");+$("#st-off").onclick=()=>stageCmd("off").then(j=>{ if(j&&j.status==="ok") toast("Stage driver off; home again before moving") });+$("#st-neg").onclick=()=>stageCmd("step",-stepSize);+$("#st-posb").onclick=()=>stageCmd("step",stepSize);+$("#st-test").onclick=()=>stageCmd("selftest").then(j=>{ if(j&&j.status==="ok") toast("Self-test: to 128, +128 four times, -128 four times, 1 s plateaus") });+let calArmed=false;+function setCalArmed(a){ calArmed=a; const il=$("#cal-interlock"); il.classList.toggle("is-on",a); il.setAttribute("aria-checked",a); $("#cal-go").disabled=!a }+$("#cal-interlock").onclick=()=>setCalArmed(!calArmed);+$("#cal-go").onclick=()=>{ if(!calArmed) return; post("calibrate",{confirm:"beam-safe"}).then(j=>{ if(j&&j.status==="ok") toast("Calibrate: the stage is the moving target") }) };+const nmFmt=v=>v==null||!isFinite(v)?"n/a":Math.abs(v)>=10000?(v/1000).toFixed(2)+" µm":Math.round(v).toLocaleString("en-US")+" nm";+function drawStage(){+ const {g,w,h}=ctxOf("cv-stage"); const st=F&&F.stage; if(!st) return;+ const tr=st.trace, n=tr.t.length;+ const x0=PADL+14,y0=PADT,pw=w-x0-PADR,ph=h-PADT-PADB;+ if(n<2){ axes(g,x0,y0,pw,ph,0,25,v=>v+"µm",-30,0,(v,d)=>v.toFixed(d)+" s"); return }+ let lo=Infinity,hi=-Infinity; for(const a of [tr.cmd,tr.meas,tr.truth]) for(const v of a){ if(v==null) continue; lo=Math.min(lo,v); hi=Math.max(hi,v) }+ const sc=autoscale("stage",lo/1000,hi/1000,2);+ axes(g,x0,y0,pw,ph,sc.lo,sc.hi,v=>(Math.abs(sc.hi-sc.lo)<6?v.toFixed(1):v.toFixed(0))+"µm",-30,0,(v,d)=>v.toFixed(d)+" s");+ const X=t=>x0+(t+30)/30*pw, Y=v=>y0+ph-(v/1000-sc.lo)/(sc.hi-sc.lo)*ph;+ g.save(); g.beginPath(); g.rect(x0,y0,pw,ph); g.clip();+ const line=(a,col,lw,dash,step)=>{ g.strokeStyle=col; g.lineWidth=lw; g.setLineDash(dash||[]); g.beginPath(); let on=false, py=0;+ for(let i=0;i<n;i++){ if(a[i]==null){on=false;continue} const x=X(tr.t[i]), y=Y(a[i]); if(!on){g.moveTo(x,y);on=true} else { if(step) g.lineTo(x,py); g.lineTo(x,y) } py=y } g.stroke(); g.setLineDash([]) };+ if(tr.truth.some(v=>v!=null)) line(tr.truth,css("--text-3"),1.3,[5,4]);+ line(tr.cmd,css("--yellow"),1.6,null,false);+ line(tr.meas,css("--accent"),2,null,true);+ g.restore();+}+function renderStage(){+ const st=F&&F.stage; if(!st) return;+ if(!$("#card-stage").offsetParent&&$("#body-stage").classList.contains("hide")) { /* not shown */ } else drawStage();+ $("#stage-sim").classList.toggle("hide",!st.simulated); $("#lg-stage-truth").classList.toggle("hide",!st.simulated);+ const s=st.state, pill=$("#stage-pill");+ for(const b of document.querySelectorAll("#st-sizes button")) b.classList.toggle("is-on",+b.dataset.n===stepSize);+ $("#st-neg").textContent="◀ "+stepSize+" towards HOME"; $("#st-posb").textContent="away "+stepSize+" ▶";+ if(!s){ pill.textContent="NO STAGE"; pill.className="pill"; $("#st-line").textContent="No STAGE frames: the Pico needs firmware 1.3.1"; return }+ pill.textContent=s.state.toUpperCase(); pill.className="pill "+(s.state==="faulted"?"fault":s.moving?"move":s.state==="idle"?"idle":"");+ for(const b of document.querySelectorAll("#st-speeds button")) b.classList.toggle("is-on",+b.dataset.n===s.rate_pps);+ const scale=st.scale_nm_per_pulse, tr=st.trace, k=tr.t.length-1;+ $("#st-pos").textContent=s.homed?s.pos_pulses+" p":"not homed";+ $("#st-cmd").textContent=s.homed?nmFmt(s.pos_pulses*scale):"n/a";+ $("#st-meas").textContent=k>=0&&s.homed?nmFmt(tr.meas[k]):"n/a";+ $("#st-line").textContent=(s.fault?"Fault: "+s.fault_text:(s.enabled?(s.homed?"Homed":"Enabled, not homed"):"Driver off (disabled at boot)"))+" · HOME "+(s.home_in?"open":"closed")+" · "+s.rate_pps+" pulses/s · "+scale.toFixed(3)+" nm/pulse"+(st.calibrated?" (calibrated)":" (nominal)");+ const busy=s.moving||s.state==="homing"||s.state==="selftest", ready=s.homed&&s.enabled&&!busy;+ $("#st-neg").disabled=!ready; $("#st-posb").disabled=!ready; $("#st-test").disabled=busy;+ for(const id of ["#st-neg","#st-posb","#st-test"]) $(id).style.opacity=$(id).disabled?.5:1;+ $("#stage-r").textContent=(st.simulated?"simulated · ":"")+scale.toFixed(3)+" nm/pulse"+(st.calibrated?" (calibrated)":" nominal");+ // self-test+ const t=st.selftest||{};+ if(t.status==="running"){ $("#st-test-t").textContent="rung "+(t.rung||0)+" of 8"; $("#st-r1").textContent="Running: origin 128, ±128 pulse rungs, 1 s plateaus"; $("#st-r2").textContent=""; $("#st-r3").textContent=""; $("#st-r1").className="resline" }+ else if(t.status==="done"){ const c=t.counted, lab=t.label;+ $("#st-test-t").textContent=lab;+ if(t.scale_nm_per_pulse!=null){ $("#st-r1").innerHTML=`Scale <b>${t.scale_nm_per_pulse.toFixed(3)} nm/pulse</b> (${((t.scale_nm_per_pulse/15.625-1)*100).toFixed(1)} %), ${t.scale_edges} edges`; $("#st-r1").className="resline" }+ else { $("#st-r1").textContent=t.warning||"Fringes were missed"; $("#st-r1").className="resline warn" }+ $("#st-r2").innerHTML=`Return residual <b>${Math.round(c.return_residual_nm)} nm</b> counted (±${Math.round(t.resolution_nm)} nm resolution)`;+ $("#st-r3").textContent=t.truth?`Simulated mirror: ${t.truth.return_residual_drift_corrected_nm.toFixed(1)} nm return, ${t.truth.nm_per_pulse.toFixed(3)} nm/pulse`:`Plateau fit ${c.nm_per_pulse.toFixed(3)} nm/pulse, drift ${c.drift_nm_s.toFixed(1)} nm/s`;+ $("#st-r1").dataset.tip=t.note; }+ else if(t.status==="failed"){ $("#st-test-t").textContent="failed"; $("#st-r1").textContent=t.error; $("#st-r1").className="resline warn"; $("#st-r2").textContent=""; $("#st-r3").textContent="" }+ // calibrate+ const c=st.calib||{};+ $("#cal-bar").style.width=(c.status==="done"?100:c.status==="running"?Math.min(95,(c.step_n||0)/(c.steps_total||6)*100):0)+"%";+ $("#cal-t").textContent=c.status==="running"?(c.step_n+"/"+c.steps_total+" "+c.step):c.status==="done"?(c.label+", "+Math.round(c.seconds)+" s"):c.status==="failed"?"stopped":"";+ if(c.status==="running"||c.status==="done") $("#cal-go").disabled=true; else $("#cal-go").disabled=!calArmed;+ if(c.status==="done"&&calArmed) setCalArmed(false);+ const tb=$("#cal-table");+ if(c.status==="done"){ const b=c.before, a=c.after, f=(v,d)=>v==null||!isFinite(v)?"n/a":(+v).toFixed(d);+ const rows=[["Laser current, mA",f(b.settings.laser_mA,1),f(a.settings.laser_mA,1)],["Ch 1 stage-2 gain",f(b.settings.ch1_gain,0),f(a.settings.ch1_gain,0)],+ ["Fringe score, moving",f(b.check.moving_score,1),f(a.check.moving_score,1)],["Step "+b.check.pulses+" p, counted",nmFmt(b.check.counted_nm),nmFmt(a.check.counted_nm)],+ ["Fringes counted",f(b.check.counted_fringes,0),f(a.check.counted_fringes,0)],["Scale, nm/pulse",f(b.check.nm_per_pulse_edge_fit,3),f(a.check.nm_per_pulse_edge_fit,3)]];+ if(c.simulated) rows.push(["Simulated mirror",nmFmt(b.check.truth_nm),nmFmt(a.check.truth_nm)]);+ tb.innerHTML=`<tr><td></td><th>before</th><th>after</th></tr>`+rows.map((r,i)=>`<tr><td>${r[0]}</td><td class="n">${r[1]}</td><td class="n${i>=2&&i<=5?" good":""}">${r[2]}</td></tr>`).join("");+ tb.dataset.tip=(c.scale_note||"")+". "+(c.note||"") }+ else if(c.status==="running"&&c.before){ tb.innerHTML=`<tr><td>Before: step ${c.before.check.pulses} p counted</td><td class="n">${nmFmt(c.before.check.counted_nm)}</td></tr><tr><td>Fringes counted</td><td class="n">${c.before.check.counted_fringes}</td></tr>` }+ else if(c.status==="failed") tb.innerHTML=`<tr><td style="color:var(--yellow);white-space:normal">${c.error}</td></tr>`;+ else if(c.status!=="running") tb.innerHTML="";+}+ // 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;@@ -749,7 +903,7 @@ 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("tab",e=>setTab(JSON.parse(e.data).tab)); 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)) });
software/dashboard/build.rs+4−3@@ -1,12 +1,13 @@ // SPDX-License-Identifier: MIT-// Compiles the firmware's control core into the dashboard so the simulator+// Compiles the firmware's control and stage cores 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"] {+ for f in ["smi_ctl.c", "smi_ctl.h", "smi_controls_gen.h", "smi_stage.c", "smi_stage.h"] { println!("cargo:rerun-if-changed={fw}/{f}"); } println!("cargo:rerun-if-changed=csrc/ctl_shim.c");+ println!("cargo:rerun-if-changed=csrc/stage_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");+ cc::Build::new().file(format!("{fw}/smi_ctl.c")).file("csrc/ctl_shim.c").file(format!("{fw}/smi_stage.c")).file("csrc/stage_shim.c").include(fw).opt_level(2).warnings(true).compile("smi_ctl"); }
software/dashboard/csrc/stage_shim.cadded+12@@ -0,0 +1,12 @@+// SPDX-License-Identifier: MIT+// Lets the dashboard's simulator run the firmware's own stage core+// (firmware/src/smi_stage.c) against a simulated TMC2209 and mechanism.+#include "smi_stage.h"++size_t smi_stage_shim_size(void) { return sizeof(smi_stage_t); }++void smi_stage_shim_init(smi_stage_t *s, void *ctx, void (*put)(void *, uint8_t, bool), bool (*home)(void *),+ void (*wait)(void *, uint32_t), bool (*uart)(void *, const uint8_t *, size_t, uint8_t *, size_t)) {+ smi_stage_hal_t h = { .ctx = ctx, .put = put, .home_in = home, .wait_us = wait, .uart = uart };+ smi_stage_init(s, &h);+}
software/dashboard/src/controls.rs+11−3@@ -379,8 +379,14 @@ pub struct CmdLink { } impl CmdLink {+ /// Never 0: the firmware caches the answer to a nonzero sequence number. pub fn next_seq(&self) -> u16 {- self.seq.fetch_add(1, std::sync::atomic::Ordering::SeqCst)+ loop {+ let s = self.seq.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ if s != 0 {+ return s;+ }+ } } /// Called by the serial thread for each ACK frame. pub fn deliver(&self, payload: Vec<u8>) {@@ -391,10 +397,12 @@ impl CmdLink { } } /// 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.+ /// A retry resends the same sequence number, so the firmware answers it+ /// from its cache instead of running it twice (a relative stage step is+ /// not idempotent). pub fn call(&self, payload: &[u8]) -> Result<Ack, String> {+ let seq = self.next_seq(); 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() {
software/dashboard/src/engine.rs+119−2@@ -8,6 +8,7 @@ use crate::dsp::{spectrum, DetectParams, Detector, Fringe}; use crate::proto::{Decoder, Frame}; use crate::record::{Format, Meta, RecStatus, Recorder}; use crate::sim::{SimParams, Simulator, FS};+use crate::stage::{SimStage, StageState, TracePt, NM_PER_PULSE}; use rustfft::FftPlanner; use serde::{Deserialize, Serialize}; use serde_json::{json, Value};@@ -111,6 +112,21 @@ pub struct Engine { pub rail_v: Option<f64>, /// Progress of the tune-for-fringes routine (see tune.rs). pub tune: Value,+ /// Test stage (board 1.3.1 J4): the simulated one, and the Pico's last STAGE frame.+ pub simstage: SimStage,+ stage_seq: u16,+ pub pico_stage: Option<(StageState, Instant)>,+ /// 50 Hz trace of the stage position against the counted displacement.+ pub stage_trace: VecDeque<TracePt>,+ next_trace_pair: u64,+ /// (position in pulses, counted nm, truth nm) when the stage last finished homing:+ /// the plot puts the counted trace on the commanded one there.+ pub stage_ref: Option<(f64, f64, f64)>,+ stage_was_homed: bool,+ /// Calibrated scale from Calibrate: {nm_per_pulse, sign, simulated, at}.+ pub stage_cal: Option<Value>,+ pub stage_selftest: Value,+ pub calib: Value, } /// Summary of one channel over a window of recent samples, ADC codes.@@ -168,9 +184,99 @@ impl Engine { isense_pauses: 0, rail_v: None, tune: json!({"status": "idle"}),+ simstage: SimStage::new(0),+ stage_seq: 0,+ pico_stage: None,+ stage_trace: VecDeque::new(),+ next_trace_pair: 0,+ stage_ref: None,+ stage_was_homed: false,+ stage_cal: None,+ stage_selftest: json!({"status": "idle"}),+ calib: json!({"status": "idle"}), } } + /// Run one stage command on the simulated stage (the firmware's stage core).+ pub fn sim_stage_command(&mut self, payload: &[u8]) -> Vec<u8> {+ self.stage_seq = self.stage_seq.wrapping_add(1).max(1);+ let now = self.board_us;+ self.simstage.command(payload, self.stage_seq, now)+ }++ /// The stage's state: simulated, or the Pico's last STAGE frame or ACK (2 s).+ pub fn stage_state(&self) -> Option<StageState> {+ match &self.source {+ SourceKind::Sim => Some(self.simstage.state()),+ SourceKind::Serial { .. } => self.pico_stage.as_ref().filter(|(_, t)| t.elapsed() < Duration::from_secs(2)).map(|(s, _)| s.clone()),+ }+ }++ /// Commanded scale for the plot: Calibrate's counted scale, else nominal.+ pub fn stage_scale(&self) -> f64 {+ self.stage_cal.as_ref().and_then(|c| c["nm_per_pulse"].as_f64()).unwrap_or(NM_PER_PULSE)+ }++ /// Add a point to the stage trace (at most every 20 ms of samples).+ pub fn stage_point(&mut self, st: &StageState) {+ if self.head < self.next_trace_pair {+ return;+ }+ self.next_trace_pair = self.head + 5_000;+ let meas = self.det.displacement_nm();+ let truth = if self.have_truth { self.truth_now - self.truth_zero } else { f64::NAN };+ if st.homed && !self.stage_was_homed {+ self.stage_ref = Some((st.pos as f64, meas, truth));+ }+ self.stage_was_homed = st.homed;+ self.stage_trace.push_back(TracePt { t_s: self.head as f64 / FS, pos: st.pos, moving: st.moving, state: st.state, homed: st.homed, meas_nm: meas, truth_nm: truth });+ while self.stage_trace.len() > 6_000 {+ self.stage_trace.pop_front();+ }+ }++ /// Re-align the counted trace with the commanded position now.+ pub fn stage_align(&mut self) {+ if let Some(st) = self.stage_state() {+ let truth = if self.have_truth { self.truth_now - self.truth_zero } else { f64::NAN };+ self.stage_ref = Some((st.pos as f64, self.det.displacement_nm(), truth));+ }+ }++ /// Stage view for the page: state, the trace (last 30 s, at most 750 points) and results.+ pub fn stage_view(&self) -> Value {+ let st = self.stage_state();+ let scale = self.stage_scale();+ let sign = self.stage_cal.as_ref().and_then(|c| c["sign"].as_f64()).unwrap_or(1.0);+ let t_end = self.head as f64 / FS;+ let pts: Vec<&TracePt> = self.stage_trace.iter().filter(|p| p.t_s >= t_end - 30.0).collect();+ let stride = pts.len().div_ceil(750).max(1);+ let (rp, rm, rt) = self.stage_ref.unwrap_or_else(|| pts.first().map(|p| (p.pos as f64, p.meas_nm, p.truth_nm)).unwrap_or((0.0, 0.0, 0.0)));+ let rc = rp * scale;+ let r1 = |v: f64| (v * 10.0).round() / 10.0;+ let (mut t, mut c, mut m, mut tr): (Vec<f64>, Vec<Value>, Vec<f64>, Vec<Value>) = (vec![], vec![], vec![], vec![]);+ for (k, p) in pts.iter().enumerate() {+ if k % stride != 0 && k + 1 != pts.len() {+ continue;+ }+ t.push(r1((p.t_s - t_end) * 100.0) / 100.0);+ // The position is only valid once homed (homing counts from wherever it started).+ c.push(if p.homed { json!(r1(p.pos as f64 * scale)) } else { Value::Null });+ m.push(r1(rc + sign * (p.meas_nm - rm)));+ tr.push(if p.truth_nm.is_nan() || rt.is_nan() { Value::Null } else { json!(r1(rc + (p.truth_nm - rt))) });+ }+ let sim = matches!(self.source, SourceKind::Sim);+ json!({+ "state": st.as_ref().map(|s| s.view()),+ "simulated": sim,+ "follows_stage": sim && self.sim_p.profile == crate::sim::Profile::Stage,+ "scale_nm_per_pulse": scale, "calibrated": self.stage_cal,+ "trace": {"t": t, "cmd": c, "meas": m, "truth": tr},+ "aligned": self.stage_ref.is_some(),+ "selftest": self.stage_selftest, "calib": self.calib,+ })+ }+ /// 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);@@ -553,6 +659,7 @@ impl Engine { "tune": self.tune, "isense_pauses": self.isense_pauses, // The simulated board's rail is ideal; a Pico reports the measured one.+ "stage": self.stage_view(), "rail_v": match self.source { SourceKind::Sim => if self.sim_p.board { json!(5.3) } else { Value::Null }, _ => json!(self.rail_v) }, }) }@@ -610,13 +717,15 @@ pub fn run_acquisition(engine: Arc<Mutex<Engine>>) { } let n = ((due - sim_pairs) as usize).min(2_500); // The simulated board advances on the samples' clock (4 us per pair).- let analog = {+ let (analog, traj) = { 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 traj = e.simstage.advance(now);+ (if e.sim_p.board { Some(e.simboard.advance(now, dt)) } else { None }, traj) };+ sim.set_stage(traj.nm, traj.dt_us); let ch = sim.generate_with(n, analog.as_ref()); let base = sim.tick / 2 - n as u64; let mut e = engine.lock().unwrap();@@ -624,6 +733,8 @@ pub fn run_acquisition(engine: Arc<Mutex<Engine>>) { let sync: Vec<(u64, u8)> = ch.sync.iter().map(|s| (s.0 - base + first, s.1)).collect(); e.ingest(first, &ch.ch1, &ch.ch2, Some(&ch.truth_nm), &sync); e.link.connected = true;+ let st = e.simstage.state();+ e.stage_point(&st); drop(e); sim_pairs += n as u64; }@@ -660,6 +771,12 @@ pub fn run_acquisition(engine: Arc<Mutex<Engine>>) { e.pico_state = Some((st, Instant::now())); } }+ Frame::Stage { payload, .. } => {+ if let Some(st) = StageState::parse(&payload) {+ e.stage_point(&st);+ e.pico_stage = Some((st, Instant::now()));+ }+ } Frame::Ack { .. } | Frame::Cmd { .. } => {} } }
software/dashboard/src/eval.rs+1@@ -79,6 +79,7 @@ pub fn run_case(name: &str, p: SimParams, d: DetectParams, seconds: f64) -> Eval Profile::Step => format!("{} um steps", p.step_um), Profile::Hand => format!("{} um wander", p.jitter_um), Profile::Hold => "still".into(),+ Profile::Stage => "test stage".into(), }; EvalRow { case: name.into(),
software/dashboard/src/main.rs+258−4@@ -14,6 +14,7 @@ mod proto; mod record; mod server; mod sim;+mod stage; mod util; use clap::{Parser, Subcommand};@@ -112,11 +113,11 @@ 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).+ /// on | off: model board 1.3 (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.+ /// Laser (board 1.3): 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@@ -172,7 +173,7 @@ enum Cmd { }, /// 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+ /// Needs the laser on; it never turns it on itself. On board 1.3 (as on 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.@@ -196,6 +197,46 @@ enum Cmd { #[arg(long)] stop: bool, },+ /// Test stage on the STAGE connector (board 1.3.1 J4, TMC2209 + HOME switch).+ ///+ /// stage [status | home | step N | move POS | speed [PPS] | stop | off | current | selftest | align].+ /// Steps are pulses (15.625 nm nominal at the mirror) or nm with --nm. The+ /// stage is disabled at boot; home it first. Moves stay inside 0..1600+ /// pulses from HOME. home, step, move and selftest wait until done unless+ /// --no-wait. On the simulator every result is labelled simulated.+ Stage {+ action: Option<String>,+ #[arg(allow_negative_numbers = true)]+ value: Option<f64>,+ /// The value is in nm at the mirror (converted with the current scale).+ #[arg(long)]+ nm: bool,+ #[arg(long = "no-wait")]+ no_wait: bool,+ /// selftest: print the last result instead of starting one.+ #[arg(long)]+ status: bool,+ },+ /// Calibrate the board with the stage as the moving target (simulator only for now).+ ///+ /// Homes the stage, records the settings and a counted-against-commanded+ /// step as they are, zeroes the laser current readback with the laser off,+ /// turns it back on, auto-centres, tunes while the stage moves back and+ /// forth, re-checks the step, and prints a before/after report. Turns the+ /// laser on, so it needs --beam-safe.+ Calibrate {+ #[arg(long = "beam-safe")]+ beam_safe: bool,+ /// Pulses for the re-check step (64..1400, default 1024 = 16 um nominal).+ #[arg(long = "check-pulses")]+ check_pulses: Option<i32>,+ #[arg(long = "no-wait")]+ no_wait: bool,+ #[arg(long)]+ status: bool,+ #[arg(long)]+ stop: bool,+ }, /// Fringe detector parameters. Detect { #[arg(long = "lp-hz")]@@ -257,7 +298,7 @@ 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.+ /// Board 1.3 suite: laser current x stage-2 gain through the simulated board. #[arg(long)] board: bool, #[arg(long, default_value = "constant")]@@ -454,6 +495,7 @@ fn main() { out.ok(&format!("source is now {}", kind), v["data"].clone(), &hints_of(&v)); } Cmd::Laser { .. } | Cmd::Offset { .. } | Cmd::Gain { .. } | Cmd::Bias { .. } | Cmd::Ctl { .. } | Cmd::Board { .. } | Cmd::Tune { .. } => board_cli(&cli, &out),+ Cmd::Stage { .. } | Cmd::Calibrate { .. } => stage_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!({});@@ -938,3 +980,215 @@ fn board_cli(cli: &Cli, out: &Out) { _ => unreachable!(), } }++fn stage_line(v: &Value) -> String {+ if v.is_null() {+ return "no stage state".into();+ }+ let f = v["fault"].as_u64().unwrap_or(0);+ format!(+ "stage {}{}, {} pulses ({:.0} nm nominal){}, {} pulses/s{}",+ v["state"].as_str().unwrap_or("?"),+ if v["homed"] == json!(true) { ", homed" } else if v["enabled"] == json!(true) { ", not homed" } else { ", driver disabled" },+ v["pos_pulses"],+ v["pos_nm_nominal"].as_f64().unwrap_or(0.0),+ if v["target_pulses"] != v["pos_pulses"] { format!(" -> {}", v["target_pulses"]) } else { String::new() },+ v["rate_pps"],+ if f != 0 { format!(", FAULT: {}", v["fault_text"].as_str().unwrap_or("")) } else { String::new() }+ )+}++fn selftest_text(v: &Value) -> String {+ match v["status"].as_str() {+ Some("done") => {+ let c = &v["counted"];+ let lab = v["label"].as_str().unwrap_or("");+ let head = match v["scale_nm_per_pulse"].as_f64() {+ Some(sc) => format!("self-test ({lab}): {sc:.3} nm/pulse from {} counted fringe edges ({:+.2} % vs nominal 15.625), return residual {:.0} nm counted\n", v["scale_edges"].as_f64().unwrap_or(0.0) as i64, (sc / 15.625 - 1.0) * 100.0, c["return_residual_nm"].as_f64().unwrap_or(f64::NAN)),+ None => format!("self-test ({lab}): fringes were missed, no scale\n"),+ };+ let mut s = head + &format!(+ "plateau fit (whole fringes): {:.3} nm/pulse ({:+.2} %), drift {:.2} nm/s, return residual {:.0} nm ({:.0} nm drift-corrected), rms {:.0} nm",+ c["nm_per_pulse"].as_f64().unwrap_or(f64::NAN),+ c["scale_vs_nominal_pct"].as_f64().unwrap_or(f64::NAN),+ c["drift_nm_s"].as_f64().unwrap_or(f64::NAN),+ c["return_residual_nm"].as_f64().unwrap_or(f64::NAN),+ c["return_residual_drift_corrected_nm"].as_f64().unwrap_or(f64::NAN),+ c["fit_rms_nm"].as_f64().unwrap_or(f64::NAN),+ );+ for k in ["edge_fit_out", "edge_fit_back"] {+ if let Some(x) = c[k]["nm_per_pulse"].as_f64() {+ s += &format!("\n{} sweep, fitted to {} counted fringe edges: {:.3} nm/pulse", if k.ends_with("out") { "outbound" } else { "return" }, c[k]["edges"], x.abs());+ }+ }+ s += "\nplateaus (pulses: counted nm):";+ for p in v["plateaus"].as_array().into_iter().flatten() {+ s += &format!(" {}: {:.0}", p["pos"], p["meas_nm"].as_f64().unwrap_or(0.0));+ }+ for r in c["reversal"].as_array().into_iter().flatten() {+ s += &format!("\nreversal at {} pulses: reverse - forward {:+.0} nm", r["pos_pulses"], r["reverse_minus_forward_nm"].as_f64().unwrap_or(0.0));+ }+ if v["truth"].is_object() {+ let t = &v["truth"];+ s += &format!(+ "\nsimulated truth: {:.3} nm/pulse, return residual {:.1} nm drift-corrected ({})",+ t["nm_per_pulse"].as_f64().unwrap_or(f64::NAN),+ t["return_residual_drift_corrected_nm"].as_f64().unwrap_or(f64::NAN),+ v["truth_note"].as_str().unwrap_or("")+ );+ }+ s += &format!("\nNote: {}", v["note"].as_str().unwrap_or(""));+ if let Some(w) = v["warning"].as_str() {+ s = format!("{s}\nWARNING: {w}");+ }+ s+ }+ Some("running") => format!("self-test running, rung {}", v["rung"]),+ Some("failed") => format!("self-test failed: {}", v["error"].as_str().unwrap_or("")),+ _ => "no self-test yet".into(),+ }+}++fn calib_text(v: &Value) -> String {+ match v["status"].as_str() {+ Some("done") => {+ let lab = v["label"].as_str().unwrap_or("");+ let (b, a) = (&v["before"], &v["after"]);+ let num = |x: &Value, d: usize| x.as_f64().map(|f| format!("{f:.d$}")).unwrap_or_else(|| "n/a".into());+ let row = |name: &str, x: String, y: String| format!(" {name:<34} {x:>14} {y:>14}\n");+ let mut s = format!("Calibrate ({lab}), {:.0} s\n {:<34} {:>14} {:>14}\n", v["seconds"].as_f64().unwrap_or(0.0), "", "before", "after");+ s += &row("laser current, mA", num(&b["settings"]["laser_mA"], 2), num(&a["settings"]["laser_mA"], 2));+ s += &row("measured current, mA", num(&b["settings"]["measured_mA"], 2), num(&a["settings"]["measured_mA"], 2));+ s += &row("ch1 second-stage gain, V/V", num(&b["settings"]["ch1_gain"], 0), num(&a["settings"]["ch1_gain"], 0));+ s += &row("ch1 offset, V", num(&b["settings"]["ch1_offset_V"], 3), num(&a["settings"]["ch1_offset_V"], 3));+ s += &row("ch1 mean, codes", num(&b["settings"]["ch1_mean"], 0), num(&a["settings"]["ch1_mean"], 0));+ s += &row("readback zero code", num(&b["settings"]["isense_zero_code"], 2), num(&a["settings"]["isense_zero_code"], 2));+ let (cb, ca) = (&b["check"], &a["check"]);+ s += &row(&format!("step {} pulses: commanded nm", cb["pulses"]), num(&cb["commanded_nm_nominal"], 0), num(&ca["commanded_nm_nominal"], 0));+ s += &row(" counted nm", num(&cb["counted_nm"], 0), num(&ca["counted_nm"], 0));+ s += &row(" counted fringes", num(&cb["counted_fringes"], 0), num(&ca["counted_fringes"], 0));+ s += &row(" error vs nominal, %", num(&cb["error_vs_nominal_pct"], 2), num(&ca["error_vs_nominal_pct"], 2));+ s += &row(" scale from fringe edges, nm/pulse", num(&cb["nm_per_pulse_edge_fit"], 3), num(&ca["nm_per_pulse_edge_fit"], 3));+ s += &row(" return (counted), nm", num(&cb["return_counted_nm"], 0), num(&ca["return_counted_nm"], 0));+ s += &row(" fringe swing while moving, codes", num(&cb["moving_swing_codes"], 0), num(&ca["moving_swing_codes"], 0));+ s += &row(" fringe score while moving", num(&cb["moving_score"], 1), num(&ca["moving_score"], 1));+ if v["simulated"] == json!(true) {+ s += &row(" simulated truth, nm", num(&cb["truth_nm"], 0), num(&ca["truth_nm"], 0));+ s += &row(" counted minus truth, nm", num(&cb["error_vs_truth_nm"], 0), num(&ca["error_vs_truth_nm"], 0));+ }+ s += &format!("tune: best {} mA, score {}, gain {}\n", num(&v["tune"]["best_mA"], 2), num(&v["tune"]["final_score"], 1), v["tune"]["gain"]["label"].as_str().unwrap_or("unchanged"));+ s += &format!("{}\n{}", v["scale_note"].as_str().unwrap_or(""), v["note"].as_str().unwrap_or(""));+ s+ }+ Some("running") => format!("Calibrate running: step {} of {}, {}", v["step_n"], v["steps_total"], v["step"].as_str().unwrap_or("")),+ Some("failed") => format!("Calibrate failed at '{}': {}", v["step"].as_str().unwrap_or(""), v["error"].as_str().unwrap_or("")),+ _ => "no calibration yet".into(),+ }+}++fn stage_cli(cli: &Cli, out: &Out) {+ let port = find_port(cli, out);+ match &cli.cmd {+ Cmd::Stage { action, value, nm, no_wait, status } => {+ let act = action.as_deref().unwrap_or("status");+ if act == "align" {+ let v = call(out, port, "POST", "/stage/align", Some(json!({})));+ out.ok("counted trace aligned with the commanded position", v["data"].clone(), &hints_of(&v));+ return;+ }+ if act == "selftest" && *status {+ let v = call(out, port, "GET", "/stage/selftest", None);+ out.ok(&selftest_text(&v["data"]), v["data"].clone(), &hints_of(&v));+ return;+ }+ let mut b = json!({"action": act, "unit": if *nm { "nm" } else { "pulses" }});+ if let Some(x) = value {+ b["value"] = json!(x);+ }+ let v = call(out, port, "POST", "/stage/cmd", Some(b));+ let hints = hints_of(&v);+ if act == "selftest" {+ if *no_wait {+ out.ok("self-test started", v["data"].clone(), &hints);+ return;+ }+ let t = Instant::now();+ loop {+ std::thread::sleep(std::time::Duration::from_millis(500));+ let r = call(out, port, "GET", "/stage/selftest", None);+ match r["data"]["status"].as_str() {+ Some("done") => return out.ok(&selftest_text(&r["data"]), r["data"].clone(), &hints_of(&r)),+ Some("failed") => out.err(&selftest_text(&r["data"]), &hints_of(&json!({"hints": r["data"]["hints"]}))),+ _ => {}+ }+ if t.elapsed().as_secs() > 120 {+ out.err("the self-test did not finish within 120 s", &["`smi-dash stage selftest --status`; `smi-dash stage stop`".into()]);+ }+ }+ }+ let waits = matches!(act, "home" | "step" | "move") && !*no_wait;+ if !waits {+ return out.ok(&stage_line(&v["data"]), v["data"].clone(), &hints);+ }+ let t = Instant::now();+ loop {+ std::thread::sleep(std::time::Duration::from_millis(150));+ let r = call(out, port, "GET", "/stage", None);+ let st = &r["data"]["state"];+ let s = st["state"].as_str().unwrap_or("");+ if s == "faulted" {+ out.err(&stage_line(st), &["`smi-dash stage off`, fix the cause, then `smi-dash stage home`".into()]);+ }+ if !matches!(s, "homing" | "moving" | "selftest") {+ return out.ok(&stage_line(st), st.clone(), &hints);+ }+ if t.elapsed().as_secs() > 90 {+ out.err("the stage did not finish within 90 s", &["`smi-dash stage stop`".into()]);+ }+ }+ }+ Cmd::Calibrate { beam_safe, check_pulses, no_wait, status, stop } => {+ if *stop {+ let v = call(out, port, "POST", "/calibrate/stop", Some(json!({})));+ return out.ok("stop requested", v["data"].clone(), &[]);+ }+ if *status {+ let v = call(out, port, "GET", "/calibrate", None);+ return out.ok(&calib_text(&v["data"]), v["data"].clone(), &hints_of(&v));+ }+ let mut b = json!({});+ if *beam_safe {+ b["confirm"] = json!("beam-safe");+ }+ if let Some(c) = check_pulses {+ b["check_pulses"] = json!(c);+ }+ let v = call(out, port, "POST", "/calibrate", Some(b));+ if *no_wait {+ return out.ok("Calibrate started", v["data"].clone(), &hints_of(&v));+ }+ let t = Instant::now();+ let mut last = String::new();+ loop {+ std::thread::sleep(std::time::Duration::from_millis(500));+ let r = call(out, port, "GET", "/calibrate", None);+ let d = &r["data"];+ match d["status"].as_str() {+ Some("done") => return out.ok(&calib_text(d), d.clone(), &hints_of(&r)),+ Some("failed") => out.err(&calib_text(d), &hints_of(&json!({"hints": d["hints"]}))),+ _ => {+ let s = calib_text(d);+ if s != last && !out.json {+ eprintln!("{s}");+ last = s;+ }+ }+ }+ if t.elapsed().as_secs() > 300 {+ out.err("Calibrate did not finish within 300 s", &["`smi-dash calibrate --status`; `smi-dash calibrate --stop`".into()]);+ }+ }+ }+ _ => unreachable!(),+ }+}
software/dashboard/src/proto.rs+5@@ -8,6 +8,8 @@ pub const T_INFO: u8 = 4; pub const T_CMD: u8 = 0x10; pub const T_ACK: u8 = 0x11; pub const T_STATE: u8 = 0x12;+/// Test-stage state (firmware 1.3.1): 24-byte block (stage::StageState) + u64 pair index.+pub const T_STAGE: u8 = 0x13; const HDR: usize = 8; const BLOCK: usize = 64; @@ -34,6 +36,8 @@ pub enum Frame { Ack { seq: u16, payload: Vec<u8> }, /// Board control state, four times a second: controls::BoardState::parse(payload). State { seq: u16, payload: Vec<u8> },+ /// Test-stage state, every 50 ms while the driver is enabled, else every 500 ms.+ Stage { seq: u16, payload: Vec<u8> }, } fn u16le(b: &[u8]) -> u16 {@@ -195,6 +199,7 @@ fn parse(ty: u8, seq: u16, p: &[u8]) -> Option<Frame> { 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_STAGE if p.len() >= 24 => Some(Frame::Stage { 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+143−2@@ -70,6 +70,7 @@ impl App { "board_map_hash": format!("{:08X}", crate::controls::ControlMap::hash()), "enums": { "sim.profile": Profile::ALL,+ "stage.action": ["status", "home", "step", "move", "speed", "stop", "off", "current", "selftest"], "source.kind": ["sim", "serial"], "record.format": ["csv", "h5"], "settings.surface": ["wv", "pup"],@@ -143,7 +144,12 @@ pub async fn serve(app: Arc<App>, listener: tokio::net::TcpListener) { 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);+ // Also while the stage driver is enabled: firmware 1.3.1 disables+ // the stage when a dashboard host goes quiet for the same timeout.+ let on = {+ let e = a4.engine.lock().unwrap();+ e.board_state().is_some_and(|s| s.laser_on) || (!matches!(e.source, SourceKind::Sim) && e.stage_state().is_some_and(|s| s.enabled))+ }; if on { let _ = crate::tune::cmd(&a4, vec![crate::controls::OP_HEARTBEAT]).await; }@@ -195,6 +201,12 @@ pub async fn serve(app: Arc<App>, listener: tokio::net::TcpListener) { .route("/board/tune/stop", post(board_tune_stop)) .route("/board/clear_fault", post(board_clear_fault)) .route("/board/config", post(board_config))+ .route("/stage", get(stage_get))+ .route("/stage/cmd", post(stage_cmd))+ .route("/stage/align", post(stage_align))+ .route("/stage/selftest", get(stage_selftest_get))+ .route("/calibrate", get(calibrate_get).post(calibrate_post))+ .route("/calibrate/stop", post(calibrate_stop)) .with_state(app); axum::serve(listener, r).await.unwrap(); }@@ -488,7 +500,7 @@ async fn board_get(State(a): S) -> Response { 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"] }+ if matches!(e.source, SourceKind::Sim) { vec!["The simulator models the v1.1 board; turn the board 1.3 model on with `smi-dash sim --board on`"] } else { vec!["No STATE frames from the Pico: it needs firmware 1.3.1"] } } 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 {@@ -646,3 +658,132 @@ async fn board_config(State(a): S, Json(p): Json<Value>) -> Response { Err(f) => fail_resp(f), } }++// ------------------------------------------------------------------ stage --++use crate::stage;++fn stage_hints(a: &Arc<App>) -> Vec<&'static str> {+ if matches!(a.engine.lock().unwrap().source, SourceKind::Sim) {+ vec!["Simulated stage: the firmware's stage core on a simulated TMC2209 and mechanism. Nothing is assembled yet, so no result here is a measurement"]+ } else {+ vec![]+ }+}++async fn stage_get(State(a): S) -> Response {+ a.touch();+ let v = a.engine.lock().unwrap().stage_view();+ let h = stage_hints(&a);+ ok(v, &h)+}++/// {action: status|home|step|move|speed|stop|off|current|selftest, value, unit: "pulses"|"nm"}+async fn stage_cmd(State(a): S, Json(p): Json<Value>) -> Response {+ a.touch();+ let action = p.get("action").and_then(|v| v.as_str()).unwrap_or("status").to_string();+ let unit = p.get("unit").and_then(|v| v.as_str()).unwrap_or("pulses");+ let val = p.get("value").and_then(|v| v.as_f64().or_else(|| v.as_str().and_then(|s| s.parse().ok())));+ let scale = a.engine.lock().unwrap().stage_scale();+ let pulses = |v: f64| -> i32 { if unit == "nm" { (v / scale).round() as i32 } else { v.round() as i32 } };+ let need = |what: &str| refuse(StatusCode::BAD_REQUEST, &format!("'{action}' needs a value ({what})"), &[format!("e.g. {{\"action\": \"{action}\", \"value\": 128}}")]);+ let (sub, arg) = match action.as_str() {+ "status" => (stage::sub::STATUS, 0),+ "home" => (stage::sub::HOME, 0),+ "stop" => (stage::sub::STOP, 0),+ "off" => (stage::sub::OFF, 0),+ "current" => (stage::sub::CURRENT, 0),+ "speed" => (stage::sub::SPEED, val.map(|v| v.round() as i32).unwrap_or(0)),+ "step" => match val { Some(v) => (stage::sub::STEP, pulses(v)), None => return need("signed pulses, or nm with unit nm") },+ "move" => match val { Some(v) => (stage::sub::MOVE_TO, pulses(v)), None => return need("absolute pulses from HOME, 0..1600") },+ "selftest" => {+ stage::sim_follow_stage(&a);+ return match stage::spawn_selftest(a.clone()) {+ Ok(()) => ok(json!({"started": true}), &["About 17 s at 160 pulses/s (homes first if needed). Progress and result: `smi-dash stage selftest --status`"]),+ Err(f) => fail_resp(f),+ };+ }+ _ => return refuse(StatusCode::BAD_REQUEST, &format!("unknown stage action '{action}'"), &["Actions: status, home, step, move, speed, stop, off, current, selftest".into()]),+ };+ if matches!(sub, stage::sub::HOME | stage::sub::STEP | stage::sub::MOVE_TO) && stage::sim_follow_stage(&a) {+ a.push_state();+ a.broadcast("toast", json!({"text": "Simulator target: the stage mirror", "kind": "info"}));+ }+ if stage::CAL_RUNNING.load(std::sync::atomic::Ordering::SeqCst) && !matches!(sub, stage::sub::STATUS | stage::sub::STOP | stage::sub::OFF | stage::sub::CURRENT) {+ return refuse(StatusCode::CONFLICT, "Calibrate is moving the stage", &["Wait for it, or `smi-dash calibrate --stop`".into()]);+ }+ match stage::stage_ok(&a, sub, arg).await {+ Ok(st) => {+ let mut h: Vec<String> = stage_hints(&a).iter().map(|s| s.to_string()).collect();+ if sub == stage::sub::HOME {+ h.push("Homing: 80 pulses/s to the switch, back off, 32 pulses/s to the opening edge; `smi-dash stage home` waits until it is homed unless --no-wait".into());+ }+ if sub == stage::sub::OFF {+ h.push("Driver disabled; the position is invalid until the next home".into());+ }+ if sub == stage::sub::CURRENT {+ h.push("Winding current: IRUN = IHOLD = 27/31 of 0.469 A rms, about 0.41 A rms (stage map). Commission it against the measured winding current".into());+ }+ let hr: Vec<&str> = h.iter().map(|s| s.as_str()).collect();+ let mut v = st.view();+ v["action"] = json!(action);+ v["arg"] = json!(arg);+ v["nm_per_pulse"] = json!(scale);+ ok(v, &hr)+ }+ Err(f) => fail_resp(f),+ }+}++async fn stage_align(State(a): S) -> Response {+ a.touch();+ a.engine.lock().unwrap().stage_align();+ ok(json!({"aligned": true}), &["The counted trace now starts on the commanded one"])+}++async fn stage_selftest_get(State(a): S) -> Response {+ let v = a.engine.lock().unwrap().stage_selftest.clone();+ let h = stage_hints(&a);+ ok(v, &h)+}++async fn calibrate_get(State(a): S) -> Response {+ let v = a.engine.lock().unwrap().calib.clone();+ let h = stage_hints(&a);+ ok(v, &h)+}++async fn calibrate_post(State(a): S, Json(p): Json<Value>) -> Response {+ a.touch();+ let cp: stage::CalParams = match serde_json::from_value(p) {+ Ok(c) => c,+ Err(e) => return refuse(StatusCode::BAD_REQUEST, &format!("invalid calibrate parameters: {e}"), &["Keys: confirm, check_pulses, start_ma".into()]),+ };+ if !matches!(a.engine.lock().unwrap().source, SourceKind::Sim) {+ return refuse(StatusCode::CONFLICT, "Calibrate runs on the simulator only for now", &["The stage is not assembled; switch to the simulator with `smi-dash source sim`".into()]);+ }+ if !a.engine.lock().unwrap().sim_p.board {+ return refuse(StatusCode::CONFLICT, "Calibrate needs the board model (laser, offsets and gains from software)", &["`smi-dash sim --board on`".into()]);+ }+ if cp.confirm.as_deref() != Some("beam-safe") {+ return refuse(+ StatusCode::PRECONDITION_REQUIRED,+ "laser interlock: Calibrate turns the laser off and on; confirm the beam path is safe",+ &["`smi-dash calibrate --beam-safe` (the page asks you to tick the interlock box)".into()],+ );+ }+ if !(64..=1400).contains(&cp.check_pulses) {+ return refuse(StatusCode::BAD_REQUEST, "check_pulses must be 64 to 1400", &["The re-check moves from pulse 128, so it must stay inside 0..1600".into()]);+ }+ match stage::spawn_calibrate(a.clone(), cp) {+ Ok(()) => ok(json!({"started": true}), &["About a minute (simulated). Progress and report: `smi-dash calibrate --status`"]),+ Err(f) => fail_resp(f),+ }+}++async fn calibrate_stop(State(a): S) -> Response {+ stage::CAL_CANCEL.store(true, std::sync::atomic::Ordering::SeqCst);+ tune::TUNE_CANCEL.store(true, std::sync::atomic::Ordering::SeqCst);+ let _ = stage::stage_cmd(&a, stage::sub::STOP, 0).await;+ ok(json!({"stopping": stage::CAL_RUNNING.load(std::sync::atomic::Ordering::SeqCst)}), &[])+}
software/dashboard/src/sim.rs+48−1@@ -46,6 +46,9 @@ pub enum Profile { Step, Hand, Hold,+ /// The target is the test stage's mirror (board 1.3.1 STAGE connector),+ /// driven by the simulated stage running the firmware's stage core.+ Stage, } impl Profile {@@ -56,10 +59,11 @@ impl Profile { "step" => Self::Step, "hand" => Self::Hand, "hold" => Self::Hold,+ "stage" => Self::Stage, _ => return None, }) }- pub const ALL: [&'static str; 5] = ["constant", "sine", "step", "hand", "hold"];+ pub const ALL: [&'static str; 6] = ["constant", "sine", "step", "hand", "hold", "stage"]; } #[derive(Clone, Debug, Serialize, Deserialize)]@@ -352,6 +356,13 @@ pub struct Simulator { pos_origin: f64, /// Board mode: longitudinal modes keyed by (mode number * 2 + beat partner). bmodes: Vec<(i64, Mode)>,+ /// Stage profile: the mirror trajectory for the current chunk (nm, one per+ /// `stage_dt_us`), the time the chunk started, and the mirror position when+ /// the profile started (so switching to it never jumps the target).+ stage_traj: Vec<f64>,+ stage_dt_us: f64,+ stage_t0: f64,+ stage_ref: Option<f64>, } /// Laser model for board v1.2 (a 658 nm Fabry-Perot diode such as the HL6501MG).@@ -435,6 +446,10 @@ impl Simulator { t_profile_origin: 0.0, pos_origin: 0.0, bmodes: vec![],+ stage_traj: vec![],+ stage_dt_us: 50.0,+ stage_t0: 0.0,+ stage_ref: None, }; s.build_modes(); for i in 0..2 {@@ -474,8 +489,33 @@ impl Simulator { self.pos_origin = self.pos; self.ou = 0.0; self.drift = 0.0;+ self.stage_ref = None; } }++ /// The stage mirror's positions over the next chunk (Stage profile).+ pub fn set_stage(&mut self, nm: Vec<f64>, dt_us: f64) {+ self.stage_traj = nm;+ self.stage_dt_us = dt_us;+ self.stage_t0 = self.t;+ }++ fn stage_nm_now(&self) -> Option<f64> {+ let n = self.stage_traj.len();+ if n == 0 {+ return None;+ }+ let x = (self.t - self.stage_t0) * 1e6 / self.stage_dt_us - 1.0;+ if x <= 0.0 {+ return Some(self.stage_traj[0]);+ }+ let i = x.floor() as usize;+ if i + 1 >= n {+ return Some(self.stage_traj[n - 1]);+ }+ let f = x - i as f64;+ Some(self.stage_traj[i] * (1.0 - f) + self.stage_traj[i + 1] * f)+ } } impl Simulator {@@ -486,6 +526,13 @@ impl Simulator { let um = 1e-6; let (target, seg): (f64, i64) = match p.profile { Profile::Hold => (self.pos_origin, 0),+ Profile::Stage => match self.stage_nm_now() {+ Some(nm) => {+ let r = *self.stage_ref.get_or_insert(nm);+ (self.pos_origin + (nm - r) * 1e-9, 0)+ }+ None => (self.pos, 0),+ }, Profile::Constant => { let range = p.range_um.max(1.0) * um; let v = p.speed_um_s.abs().max(0.0) * um;
software/dashboard/src/stage.rsadded+1057@@ -0,0 +1,1057 @@+// SPDX-License-Identifier: MIT+//! Test stage on board 1.3.1's STAGE connector (J4): a TMC2209 on STEP, DIR,+//! EN_N and its single-wire UART, and a normally closed HOME switch.+//!+//! - The protocol: firmware/src/smi_stage.h (op 0x09 on the CMD/ACK channel,+//! STAGE frames 0x13).+//! - A simulated stage that runs the firmware's own smi_stage.c over FFI+//! against a simulated TMC2209 (CRC, registers, IFCNT) and a mechanism model+//! (screw, lever, lost motion at reversals, thermal drift, HOME switch).+//! - The self-test analysis (the stage map's step-out-and-back sequence) and+//! Calibrate, which uses the stage as the moving target that Tune needs.+//!+//! Nothing here has run on an assembled stage. Every result the simulator+//! produces is labelled "simulated".++use crate::engine::SourceKind;+use crate::server::App;+use crate::tune::{self, Fail};+use serde::Serialize;+use serde_json::{json, Value};+use std::os::raw::c_void;+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::Arc;+use std::time::{Duration, Instant};++pub const OP_STAGE: u8 = 0x09;+/// stage-map.json motion: 500 um lead / 3200 microsteps x 5 / 50 lever.+pub const NM_PER_PULSE: f64 = 15.625;+pub const GEOMETRY_NM_PER_PULSE: [f64; 2] = [14.64, 16.65];+pub const TRAVEL: i32 = 1600;+pub const RATE_DEFAULT: i32 = 160;+pub const RATE_MAX: i32 = 640;++pub mod sub {+ pub const STATUS: u8 = 0;+ pub const HOME: u8 = 1;+ pub const STEP: u8 = 2;+ pub const SPEED: u8 = 3;+ pub const STOP: u8 = 4;+ pub const OFF: u8 = 5;+ pub const CURRENT: u8 = 6;+ pub const SELFTEST: u8 = 7;+ pub const MOVE_TO: u8 = 8;+}++pub const ST_OFF: u8 = 0;+pub const ST_IDLE: u8 = 1;+pub const ST_SELFTEST: u8 = 4;+pub const ST_FAULTED: u8 = 5;++pub static SELFTEST_RUNNING: AtomicBool = AtomicBool::new(false);+pub static CAL_RUNNING: AtomicBool = AtomicBool::new(false);+pub static CAL_CANCEL: AtomicBool = AtomicBool::new(false);++pub fn cmd(sub: u8, arg: i32) -> Vec<u8> {+ let mut p = vec![OP_STAGE, sub];+ p.extend_from_slice(&arg.to_le_bytes());+ p+}++pub fn state_name(s: u8) -> &'static str {+ ["off", "idle", "homing", "moving", "selftest", "faulted"].get(s as usize).copied().unwrap_or("?")+}++pub fn fault_text(f: u8) -> &'static str {+ match f {+ 0 => "none",+ 1 => "TMC2209 configuration or status read failed",+ 2 => "HOME stayed high through the release search (stuck or disconnected switch)",+ 3 => "no HOME edge within the search limit",+ 4 => "HOME went high during a normal move",+ 5 => "host link lost while enabled",+ 6 => "TMC2209 reported over-temperature, a short or an open load",+ _ => "unknown",+ }+}++pub fn status_text(s: u8) -> &'static str {+ match s {+ 0 => "ok",+ 1 => "command too short",+ 2 => "unknown stage command",+ 11 => "the stage is not homed: only homing may move it",+ 12 => "outside the travel, 0 to 1600 pulses from HOME",+ 13 => "busy: a home, move or self-test is running",+ 14 => "the TMC2209 did not configure (UART, CRC, IFCNT or version)",+ 15 => "a stage fault is latched",+ 16 => "speed must be 1 to 640 pulses/s",+ _ => "unknown status",+ }+}++fn hint_for(s: u8) -> Vec<String> {+ match s {+ 11 => vec!["Home it first: `smi-dash stage home` (the Home button)".into()],+ 12 => vec!["Moves must stay within 0..1600 pulses (0 to 25 um at the mirror, nominal) from HOME".into()],+ 13 => vec!["Wait for it, or `smi-dash stage stop`".into()],+ 14 => vec!["Check the stage controller's power (10 to 13.2 V on VIN) and the J4 harness; the driver stays disabled".into()],+ 15 => vec!["Read the fault with `smi-dash stage`, then `smi-dash stage off` and `smi-dash stage home`".into()],+ 16 => vec!["The stage map's default is 160 pulses/s and its maximum 640".into()],+ _ => vec![],+ }+}++#[derive(Clone, Debug, Serialize, Default)]+pub struct StageState {+ pub state: u8,+ pub enabled: bool,+ pub homed: bool,+ pub home_in: bool,+ pub moving: bool,+ pub fault: u8,+ pub home_phase: u8,+ pub pos: i32,+ pub target: i32,+ pub rate: u16,+ pub st_index: u8,+ pub ifcnt: u8,+ pub steps_total: u32,+ pub drv_status: u32,+}++impl StageState {+ pub fn parse(p: &[u8]) -> Option<Self> {+ if p.len() < 24 {+ return None;+ }+ let i32le = |o: usize| i32::from_le_bytes([p[o], p[o + 1], p[o + 2], p[o + 3]]);+ let fl = p[1];+ Some(Self {+ state: p[0],+ enabled: fl & 1 != 0,+ homed: fl & 2 != 0,+ home_in: fl & 4 != 0,+ moving: fl & 8 != 0,+ fault: p[2],+ home_phase: p[3],+ pos: i32le(4),+ target: i32le(8),+ rate: u16::from_le_bytes([p[12], p[13]]),+ st_index: p[14],+ ifcnt: p[15],+ steps_total: i32le(16) as u32,+ drv_status: i32le(20) as u32,+ })+ }+ pub fn view(&self) -> Value {+ json!({+ "state": state_name(self.state), "enabled": self.enabled, "homed": self.homed, "home_in": self.home_in,+ "moving": self.moving, "fault": self.fault, "fault_text": fault_text(self.fault),+ "pos_pulses": self.pos, "target_pulses": self.target, "rate_pps": self.rate,+ "pos_nm_nominal": self.pos as f64 * NM_PER_PULSE, "selftest_rung": self.st_index,+ "steps_total": self.steps_total, "drv_status": format!("0x{:08X}", self.drv_status),+ })+ }+}++// ------------------------------------------------------------ simulated stage --++extern "C" {+ fn smi_stage_shim_size() -> usize;+ fn smi_stage_shim_init(+ s: *mut c_void,+ ctx: *mut c_void,+ put: extern "C" fn(*mut c_void, u8, bool),+ home: extern "C" fn(*mut c_void) -> bool,+ wait: extern "C" fn(*mut c_void, u32),+ uart: extern "C" fn(*mut c_void, *const u8, usize, *mut u8, usize) -> bool,+ );+ fn smi_stage_tick(s: *mut c_void, now_us: u32);+ fn smi_stage_command(s: *mut c_void, p: *const u8, n: usize, seq: u16, now_us: u32, resp: *mut u8) -> usize;+ fn smi_stage_state(s: *const c_void, out: *mut u8) -> usize;+}++/// Model values for the simulated mechanism, not measurements. The true scale+/// sits inside the stage map's geometry-only range (14.64 to 16.65 nm/pulse)+/// but off the nominal 15.625, so the self-test and Calibrate have something+/// real to find.+pub mod mech {+ pub const TRUE_NM_PER_PULSE: f64 = 15.31;+ /// Lost motion at each reversal (static friction and driver compliance), pulses.+ pub const LOST_PULSES: f64 = 1.6;+ /// Mirror follows the screw through the lever with this time constant, s.+ pub const TAU_S: f64 = 0.002;+ /// PETG warming drift of the apparent position, nm/s.+ pub const DRIFT_NM_S: f64 = 0.6;+ /// Where the screw is at power-up, pulses from the HOME edge.+ pub const START_PULSES: i64 = 830;+}++const SIM_STEP_GPIO: u8 = 10;+const SIM_DIR_GPIO: u8 = 11;+const SIM_EN_GPIO: u8 = 12;++/// The simulated TMC2209 and mechanism behind the HAL callbacks.+pub struct Mech {+ step: bool,+ dir: bool,+ en_n: bool,+ /// Screw position in pulses from the HOME switch edge (switch opens at <= 0).+ pub pulses: i64,+ /// Effective (after lost motion) position, pulses.+ eff: f64,+ regs: [u32; 128],+ ifcnt: u8,+ pub uart_ok: bool,+}++extern "C" fn m_put(ctx: *mut c_void, g: u8, v: bool) {+ // SAFETY: ctx is the Box<Mech> owned by the SimStage that registered it.+ let m = unsafe { &mut *(ctx as *mut Mech) };+ match g {+ SIM_STEP_GPIO => {+ if v && !m.step && !m.en_n {+ // Firmware DIR level true = positive (away from HOME).+ m.pulses += if m.dir { 1 } else { -1 };+ }+ m.step = v;+ }+ SIM_DIR_GPIO => m.dir = v,+ SIM_EN_GPIO => m.en_n = v,+ _ => {}+ }+}+extern "C" fn m_home(ctx: *mut c_void) -> bool {+ // SAFETY: as above.+ let m = unsafe { &*(ctx as *const Mech) };+ m.pulses <= 0+}+extern "C" fn m_wait(_ctx: *mut c_void, _us: u32) {}++fn tmc_crc(d: &[u8]) -> u8 {+ let mut crc = 0u8;+ for &x in d {+ let mut b = x;+ for _ in 0..8 {+ crc = if ((crc >> 7) ^ (b & 1)) != 0 { (crc << 1) ^ 0x07 } else { crc << 1 };+ b >>= 1;+ }+ }+ crc+}++extern "C" fn m_uart(ctx: *mut c_void, tx: *const u8, ntx: usize, rx: *mut u8, nrx: usize) -> bool {+ // SAFETY: ctx as above; tx has ntx bytes and rx room for nrx bytes (smi_stage.c).+ let m = unsafe { &mut *(ctx as *mut Mech) };+ let tx = unsafe { std::slice::from_raw_parts(tx, ntx) };+ if !m.uart_ok || ntx < 4 || tx[0] != 0x05 || tx[ntx - 1] != tmc_crc(&tx[..ntx - 1]) {+ return false;+ }+ let reg = (tx[2] & 0x7F) as usize;+ if ntx == 8 && tx[2] & 0x80 != 0 {+ let v = u32::from_be_bytes([tx[3], tx[4], tx[5], tx[6]]);+ if reg == 0x01 { m.regs[reg] &= !v } else { m.regs[reg] = v }+ m.ifcnt = m.ifcnt.wrapping_add(1);+ return nrx == 0;+ }+ if ntx != 4 || nrx != 8 {+ return false;+ }+ let v = match reg {+ 0x02 => m.ifcnt as u32,+ 0x06 => (0x21u32 << 24) | 0x40, // version 0x21, SPREAD high+ _ => m.regs[reg],+ };+ let b = v.to_be_bytes();+ let mut r = [0x05, 0xFF, reg as u8, b[0], b[1], b[2], b[3], 0];+ r[7] = tmc_crc(&r[..7]);+ // SAFETY: rx has room for 8 bytes.+ unsafe { std::ptr::copy_nonoverlapping(r.as_ptr(), rx, 8) };+ true+}++pub struct SimStage {+ core: Vec<u64>,+ pub mech: Box<Mech>,+ /// Mirror displacement, nm (lagging the effective screw position, plus drift).+ pub mirror_nm: f64,+ drift_nm: f64,+ last_us: u64,+}++/// Mirror positions over one chunk, one every `dt_us`.+pub struct StageTraj {+ pub nm: Vec<f64>,+ pub dt_us: f64,+}++impl SimStage {+ pub fn new(now_us: u64) -> Self {+ // SAFETY: plain C struct size.+ let n = unsafe { smi_stage_shim_size() };+ let mut regs = [0u32; 128];+ regs[0x01] = 1; // GSTAT reset flag set after power-up+ let mut s = SimStage {+ core: vec![0u64; n.div_ceil(8) + 1],+ mech: Box::new(Mech { step: false, dir: true, en_n: true, pulses: mech::START_PULSES, eff: mech::START_PULSES as f64, regs, ifcnt: 0, uart_ok: true }),+ mirror_nm: mech::START_PULSES as f64 * mech::TRUE_NM_PER_PULSE,+ drift_nm: 0.0,+ last_us: now_us,+ };+ let ctx = &mut *s.mech as *mut Mech as *mut c_void;+ // SAFETY: core is large enough for smi_stage_t; ctx outlives it (both owned here).+ unsafe { smi_stage_shim_init(s.core.as_mut_ptr() as *mut c_void, ctx, m_put, m_home, m_wait, m_uart) };+ s+ }++ pub fn command(&mut self, payload: &[u8], seq: u16, now_us: u64) -> Vec<u8> {+ let mut r = vec![0u8; 64];+ // SAFETY: r has room for the 28-byte ACK.+ let n = unsafe { smi_stage_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) -> StageState {+ let mut r = [0u8; 32];+ // SAFETY: r has room for the 24-byte state block.+ let n = unsafe { smi_stage_state(self.core.as_ptr() as *const c_void, r.as_mut_ptr()) };+ StageState::parse(&r[..n]).unwrap_or_default()+ }++ /// Run the firmware core every 50 us up to `now_us` and move the mechanism.+ pub fn advance(&mut self, now_us: u64) -> StageTraj {+ const DT: u64 = 50;+ let mut nm = vec![];+ let a = 1.0 - (-(DT as f64) * 1e-6 / mech::TAU_S).exp();+ while self.last_us + DT <= now_us {+ self.last_us += DT;+ // SAFETY: core initialised in new().+ unsafe { smi_stage_tick(self.core.as_mut_ptr() as *mut c_void, self.last_us as u32) };+ let m = &mut *self.mech;+ let p = m.pulses as f64;+ let half = mech::LOST_PULSES / 2.0;+ if p - m.eff > half {+ m.eff = p - half;+ } else if m.eff - p > half {+ m.eff = p + half;+ }+ self.drift_nm += mech::DRIFT_NM_S * DT as f64 * 1e-6;+ let want = m.eff * mech::TRUE_NM_PER_PULSE + self.drift_nm;+ self.mirror_nm += (want - self.mirror_nm) * a;+ nm.push(self.mirror_nm);+ }+ StageTraj { nm, dt_us: DT as f64 }+ }+}++// ----------------------------------------------------------------- analysis --++/// One point of the stage trace (50 Hz): what the stage reported and what the+/// fringes counted at the same sample.+#[derive(Clone, Debug, Serialize)]+pub struct TracePt {+ pub t_s: f64,+ pub pos: i32,+ pub moving: bool,+ pub state: u8,+ pub homed: bool,+ /// Counted displacement (raw fringe count x lambda/2), nm.+ pub meas_nm: f64,+ /// Simulated mirror position, nm (NaN on hardware).+ pub truth_nm: f64,+}++#[derive(Clone, Debug, Serialize)]+pub struct Plateau {+ pub pos: i32,+ pub t_s: f64,+ pub meas_nm: f64,+ pub truth_nm: f64,+ pub n: usize,+}++/// Plateaus of a self-test: runs of points in the self-test state, not moving,+/// at one position; the mean of the last 60 % of each (settled).+pub fn plateaus(tr: &[TracePt]) -> Vec<Plateau> {+ let mut out = vec![];+ let mut i = 0;+ while i < tr.len() {+ let p = &tr[i];+ if p.state != ST_SELFTEST || p.moving {+ i += 1;+ continue;+ }+ let mut j = i;+ while j < tr.len() && tr[j].state == ST_SELFTEST && !tr[j].moving && tr[j].pos == p.pos {+ j += 1;+ }+ let run = &tr[i..j];+ if run.len() >= 5 {+ let k = run.len() * 2 / 5;+ let s = &run[k..];+ let n = s.len() as f64;+ out.push(Plateau {+ pos: p.pos,+ t_s: s.iter().map(|x| x.t_s).sum::<f64>() / n,+ meas_nm: s.iter().map(|x| x.meas_nm).sum::<f64>() / n,+ truth_nm: s.iter().map(|x| x.truth_nm).sum::<f64>() / n,+ n: s.len(),+ });+ }+ i = j;+ }+ out+}++/// Least squares y = s p + d t + b. Returns (s, d, b).+fn fit3(ps: &[(f64, f64, f64)]) -> Option<(f64, f64, f64)> {+ let mut a = [[0.0f64; 3]; 3];+ let mut r = [0.0f64; 3];+ for &(p, t, y) in ps {+ let x = [p, t, 1.0];+ for i in 0..3 {+ for j in 0..3 {+ a[i][j] += x[i] * x[j];+ }+ r[i] += x[i] * y;+ }+ }+ // Gaussian elimination with partial pivoting.+ for c in 0..3 {+ let piv = (c..3).max_by(|&i, &j| a[i][c].abs().partial_cmp(&a[j][c].abs()).unwrap())?;+ if a[piv][c].abs() < 1e-12 {+ return None;+ }+ a.swap(c, piv);+ r.swap(c, piv);+ for i in 0..3 {+ if i != c {+ let f = a[i][c] / a[c][c];+ for j in 0..3 {+ a[i][j] -= f * a[c][j];+ }+ r[i] -= f * r[c];+ }+ }+ }+ Some((r[0] / a[0][0], r[1] / a[1][1], r[2] / a[2][2]))+}++/// The stage map's self-test analysis on one set of plateaus, for either the+/// counted (`truth = false`) or the simulated true (`truth = true`) position.+fn analyse_one(pl: &[Plateau], truth: bool) -> Value {+ let y = |p: &Plateau| if truth { p.truth_nm } else { p.meas_nm };+ let pts: Vec<(f64, f64, f64)> = pl.iter().map(|p| (p.pos as f64, p.t_s - pl[0].t_s, y(p))).collect();+ let Some((s, d, b)) = fit3(&pts) else { return json!(null) };+ let resid: Vec<f64> = pts.iter().map(|&(p, t, v)| v - (s * p + d * t + b)).collect();+ let rms = (resid.iter().map(|r| r * r).sum::<f64>() / resid.len() as f64).sqrt();+ // Matched forward and reverse plateaus at the same commanded position.+ let mut rev = vec![];+ for i in 1..pl.len() {+ for j in (i + 1)..pl.len() {+ if pl[i].pos == pl[j].pos && j != pl.len() - 1 {+ let e = (y(&pl[j]) - y(&pl[i])) - d * (pl[j].t_s - pl[i].t_s);+ rev.push(json!({"pos_pulses": pl[i].pos, "reverse_minus_forward_nm": (e * 10.0).round() / 10.0}));+ }+ }+ }+ let last = pl.len() - 1;+ let ret_raw = y(&pl[last]) - y(&pl[0]);+ let ret = ret_raw - d * (pl[last].t_s - pl[0].t_s);+ json!({+ "nm_per_pulse": s, "scale_vs_nominal_pct": (s / NM_PER_PULSE - 1.0) * 100.0,+ "drift_nm_s": d, "fit_rms_nm": rms, "reversal": rev,+ "return_residual_nm": ret_raw, "return_residual_drift_corrected_nm": ret,+ "plateau_residuals_nm": resid.iter().map(|r| (r * 10.0).round() / 10.0).collect::<Vec<_>>(),+ })+}++/// Scale from the fringe edges of one-direction motion: each change of the+/// count is placed at the stage position where it happened, and a straight+/// line through (pulses, counted nm) gives the slope far below one fringe.+/// Returns (nm per pulse, edges, rms of the fit in nm).+pub fn edge_fit(tr: &[TracePt]) -> Option<(f64, usize, f64)> {+ let mut pts = vec![];+ for w in tr.windows(2) {+ if (w[1].meas_nm - w[0].meas_nm).abs() > 1.0 && w[1].pos != w[0].pos {+ pts.push(((w[0].pos + w[1].pos) as f64 / 2.0, w[1].meas_nm));+ }+ }+ if pts.len() < 6 {+ return None;+ }+ let n = pts.len() as f64;+ let (mx, my) = (pts.iter().map(|p| p.0).sum::<f64>() / n, pts.iter().map(|p| p.1).sum::<f64>() / n);+ let sxx: f64 = pts.iter().map(|p| (p.0 - mx).powi(2)).sum();+ if sxx <= 0.0 {+ return None;+ }+ let k = pts.iter().map(|p| (p.0 - mx) * (p.1 - my)).sum::<f64>() / sxx;+ let rms = (pts.iter().map(|p| (p.1 - my - k * (p.0 - mx)).powi(2)).sum::<f64>() / n).sqrt();+ Some((k, pts.len(), rms))+}++pub fn analyse(pl: &[Plateau], simulated: bool, half_wave_nm: f64) -> Value {+ let counted = analyse_one(pl, false);+ let mut v = json!({+ "status": "done",+ "simulated": simulated,+ "label": if simulated { "simulated" } else { "measured" },+ "plateaus": pl,+ "counted": counted,+ "resolution_nm": half_wave_nm,+ "note": format!("The fringe counter resolves whole fringes, {half_wave_nm:.0} nm, so a residual below that is not resolved by counting. The headline scale is fitted to the counted fringe edges, each placed at the stage position where it happened, which resolves the slope far below one fringe; the plateau fit uses whole-fringe plateaus and is coarser."),+ });+ if simulated {+ v["truth"] = analyse_one(pl, true);+ v["truth_note"] = json!(format!("Simulated mechanism: true {:.3} nm/pulse, {:.1} pulses of lost motion at each reversal, {:.1} nm/s drift (model values)", mech::TRUE_NM_PER_PULSE, mech::LOST_PULSES, mech::DRIFT_NM_S));+ }+ v+}++// ------------------------------------------------------------------ commands --++fn fail(m: impl Into<String>, h: &[&str]) -> Fail {+ (m.into(), h.iter().map(|s| s.to_string()).collect())+}++/// Send one stage command to the simulated stage or the Pico.+pub async fn stage_cmd(a: &Arc<App>, s: u8, arg: i32) -> Result<(u8, StageState), Fail> {+ let (sim, link) = {+ let e = a.engine.lock().unwrap();+ (matches!(e.source, SourceKind::Sim), e.cmdlink.clone())+ };+ let payload = cmd(s, arg);+ let r = if sim {+ a.engine.lock().unwrap().sim_stage_command(&payload)+ } else {+ match tokio::task::spawn_blocking(move || link.call(&payload)).await {+ Ok(Ok(ack)) => {+ let mut v = vec![0u8, 0, ack.op, ack.status];+ v.extend_from_slice(&ack.data);+ v+ }+ Ok(Err(m)) => return Err((m, vec!["The Pico needs firmware 1.3.1 for the stage (`smi-dash status` shows its info line)".into()])),+ Err(e) => return Err(fail(format!("command task failed: {e}"), &[])),+ }+ };+ if r.len() < 28 || r[2] != OP_STAGE {+ return Err(fail("no stage answer: the firmware may predate 1.3.1", &["Flash smi_pico.uf2 1.3.1"]));+ }+ let st = StageState::parse(&r[4..]).ok_or_else(|| fail("malformed stage ACK", &[]))?;+ if !sim {+ a.engine.lock().unwrap().pico_stage = Some((st.clone(), Instant::now()));+ }+ Ok((r[3], st))+}++/// As stage_cmd, but a refusal is an error with the firmware's reason.+pub async fn stage_ok(a: &Arc<App>, s: u8, arg: i32) -> Result<StageState, Fail> {+ let (code, st) = stage_cmd(a, s, arg).await?;+ if code != 0 {+ let mut h = hint_for(code);+ if code == 15 || st.fault != 0 {+ h.insert(0, format!("Fault: {}", fault_text(st.fault)));+ }+ return Err((status_text(code).to_string(), h));+ }+ Ok(st)+}++pub fn current_state(a: &Arc<App>) -> Option<StageState> {+ a.engine.lock().unwrap().stage_state()+}++/// Wait until the stage is not homing, moving or self-testing.+pub async fn wait_idle(a: &Arc<App>, max: Duration) -> Result<StageState, Fail> {+ let t = Instant::now();+ loop {+ tokio::time::sleep(Duration::from_millis(40)).await;+ let Some(st) = current_state(a) else { return Err(fail("no stage state", &["Is the Pico running firmware 1.3.1?"])) };+ if st.state == ST_FAULTED {+ return Err((format!("stage fault: {}", fault_text(st.fault)), vec!["`smi-dash stage off`, fix the cause, then `smi-dash stage home`".into()]));+ }+ if !matches!(st.state, 2..=4) {+ return Ok(st);+ }+ if t.elapsed() > max {+ return Err(fail(format!("the stage did not finish within {} s", max.as_secs()), &["`smi-dash stage stop`"]));+ }+ if CAL_CANCEL.load(Ordering::SeqCst) && CAL_RUNNING.load(Ordering::SeqCst) {+ let _ = stage_cmd(a, sub::STOP, 0).await;+ return Err(fail("stopped", &[]));+ }+ }+}++/// The simulator's target becomes the stage mirror (profile "stage").+pub fn sim_follow_stage(a: &Arc<App>) -> bool {+ let mut e = a.engine.lock().unwrap();+ if matches!(e.source, SourceKind::Sim) && e.sim_p.profile != crate::sim::Profile::Stage {+ e.sim_p.profile = crate::sim::Profile::Stage;+ e.sim_rev += 1;+ return true;+ }+ false+}++/// Counted displacement now (raw count x lambda/2), nm.+fn counted(a: &Arc<App>) -> f64 {+ a.engine.lock().unwrap().det.displacement_nm()+}++/// Home if needed; returns the state.+pub async fn ensure_homed(a: &Arc<App>) -> Result<StageState, Fail> {+ let st = current_state(a).ok_or_else(|| fail("no stage state", &[]))?;+ if st.homed && st.enabled {+ return Ok(st);+ }+ stage_ok(a, sub::HOME, 0).await?;+ let st = wait_idle(a, Duration::from_secs(60)).await?;+ if !st.homed {+ return Err(fail("homing did not complete", &[]));+ }+ Ok(st)+}++// ----------------------------------------------------------------- self-test --++fn st_progress(a: &Arc<App>, v: Value) {+ a.engine.lock().unwrap().stage_selftest = v;+}++/// Run the firmware self-test (origin 128, +128 x 4, -128 x 4, 1 s dwells) and+/// analyse the plateaus from the stage trace.+pub async fn selftest(a: &Arc<App>) -> Result<Value, Fail> {+ sim_follow_stage(a);+ ensure_homed(a).await?;+ let t0 = a.engine.lock().unwrap().head as f64 / crate::sim::FS;+ st_progress(a, json!({"status": "running", "rung": 0}));+ stage_ok(a, sub::SELFTEST, 0).await?;+ let t = Instant::now();+ loop {+ tokio::time::sleep(Duration::from_millis(100)).await;+ let st = current_state(a).ok_or_else(|| fail("no stage state", &[]))?;+ if st.state == ST_FAULTED {+ return Err((format!("stage fault during the self-test: {}", fault_text(st.fault)), vec![]));+ }+ if st.state != ST_SELFTEST {+ break;+ }+ st_progress(a, json!({"status": "running", "rung": st.st_index, "pos_pulses": st.pos}));+ if t.elapsed() > Duration::from_secs(90) {+ let _ = stage_cmd(a, sub::STOP, 0).await;+ return Err(fail("the self-test did not finish within 90 s", &[]));+ }+ }+ tokio::time::sleep(Duration::from_millis(60)).await;+ let (tr, sim, half) = {+ let e = a.engine.lock().unwrap();+ let tr: Vec<TracePt> = e.stage_trace.iter().filter(|p| p.t_s >= t0).cloned().collect();+ (tr, matches!(e.source, SourceKind::Sim), e.det.half_wave_nm())+ };+ let pl = plateaus(&tr);+ if pl.len() != 9 {+ return Err((format!("found {} plateaus, expected 9 (origin plus 8 rungs)", pl.len()), vec!["Was the self-test stopped? Run it again".into()]));+ }+ let mut v = analyse(&pl, sim, half);+ // Sub-fringe scale from the counted fringe edges, outbound and return sweeps.+ for (k, a0, a1) in [("edge_fit_out", pl[0].t_s, pl[4].t_s), ("edge_fit_back", pl[4].t_s, pl[8].t_s)] {+ let seg: Vec<TracePt> = tr.iter().filter(|p| p.t_s >= a0 && p.t_s <= a1).cloned().collect();+ v["counted"][k] = match edge_fit(&seg) {+ Some((s, n, r)) => json!({"nm_per_pulse": s, "edges": n, "rms_nm": r}),+ None => Value::Null,+ };+ }+ v["seconds"] = json!(t.elapsed().as_secs_f64());+ // Headline scale: the edge fits, weighted by their edge counts; else the plateau fit.+ let (mut sw, mut nw) = (0.0, 0.0);+ for k in ["edge_fit_out", "edge_fit_back"] {+ if let (Some(x), Some(n)) = (v["counted"][k]["nm_per_pulse"].as_f64(), v["counted"][k]["edges"].as_f64()) {+ sw += x.abs() * n;+ nw += n;+ }+ }+ let both = !v["counted"]["edge_fit_out"].is_null() && !v["counted"]["edge_fit_back"].is_null();+ v["scale_nm_per_pulse"] = if both { json!(sw / nw) } else { Value::Null };+ v["scale_edges"] = json!(nw);+ let slope = if both { sw / nw } else { 0.0 };+ if slope < 0.5 * GEOMETRY_NM_PER_PULSE[0] || slope > 1.5 * GEOMETRY_NM_PER_PULSE[1] {+ let on = a.engine.lock().unwrap().board_state().is_some_and(|s| s.laser_on);+ v["warning"] = json!(if !on {+ "No fringes were counted: the laser is off. Turn it on (`smi-dash laser on --beam-safe`) or run `smi-dash calibrate --beam-safe`"+ } else {+ "The counted scale is far from the stage's geometry range: fringes were missed. Run `smi-dash calibrate --beam-safe` (or Tune with the stage moving)"+ });+ }+ st_progress(a, v.clone());+ Ok(v)+}++pub fn spawn_selftest(a: Arc<App>) -> Result<(), Fail> {+ if SELFTEST_RUNNING.swap(true, Ordering::SeqCst) {+ return Err(fail("a self-test is already running", &["Watch it with `smi-dash stage selftest --status`"]));+ }+ st_progress(&a, json!({"status": "running", "rung": 0}));+ tokio::spawn(async move {+ match selftest(&a).await {+ Ok(v) => {+ let c = &v["counted"];+ let txt = match v["scale_nm_per_pulse"].as_f64() {+ Some(sc) => format!("Self-test ({}): {:.3} nm/pulse, return residual {:.0} nm (counted)", v["label"].as_str().unwrap_or(""), sc, c["return_residual_nm"].as_f64().unwrap_or(0.0)),+ None => format!("Self-test ({}): fringes missed; see the warning", v["label"].as_str().unwrap_or("")),+ };+ a.broadcast("toast", json!({"text": txt, "kind": if v["warning"].is_null() { "success" } else { "error" }}));+ }+ Err((m, h)) => {+ st_progress(&a, json!({"status": "failed", "error": m, "hints": h}));+ a.broadcast("toast", json!({"text": format!("Self-test: {m}"), "kind": "error"}));+ }+ }+ SELFTEST_RUNNING.store(false, Ordering::SeqCst);+ });+ Ok(())+}++// ----------------------------------------------------------------- calibrate --++fn cal_progress(a: &Arc<App>, step: &str, k: usize, extra: Value) {+ let mut e = a.engine.lock().unwrap();+ let mut v = e.calib.clone();+ v["status"] = json!("running");+ v["step"] = json!(step);+ v["step_n"] = json!(k);+ v["steps_total"] = json!(6);+ if let Some(o) = extra.as_object() {+ for (key, val) in o {+ v[key] = val.clone();+ }+ }+ e.calib = v;+}++fn cancelled() -> Result<(), Fail> {+ if CAL_CANCEL.load(Ordering::SeqCst) {+ return Err(fail("calibration stopped", &[]));+ }+ Ok(())+}++/// Settings and fringe score now, for the before/after report.+fn snapshot_settings(a: &Arc<App>) -> Value {+ let e = a.engine.lock().unwrap();+ let st = e.board_state();+ let map = &e.map;+ let s1 = e.chan_stats(1, 50_000);+ let gain = |ch: u8| map.find("gain", Some(ch), Some("amp")).and_then(|i| st.as_ref().and_then(|s| s.targets.get(i).copied()));+ let off = |ch: u8| map.find("offset", Some(ch), None).and_then(|i| st.as_ref().and_then(|s| s.targets.get(i).copied()));+ json!({+ "laser_on": st.as_ref().is_some_and(|s| s.laser_on),+ "laser_mA": st.as_ref().map(|s| s.laser_target_ma),+ "measured_mA": st.as_ref().filter(|s| s.isense_valid).map(|s| s.isense_ma),+ "isense_zero_code": st.as_ref().and_then(|s| s.zero_code),+ "ch1_gain": gain(1), "ch2_gain": gain(2), "ch1_offset_V": off(1), "ch2_offset_V": off(2),+ "ch1_mean": s1.mean.round(),+ })+}++/// Step the stage +pulses from its present position, count the fringes, and+/// come back. Returns the counted distance against the commanded one.+async fn check_distance(a: &Arc<App>, start: i32, pulses: i32, rate: i32) -> Result<Value, Fail> {+ stage_ok(a, sub::SPEED, rate).await?;+ stage_ok(a, sub::MOVE_TO, start).await?;+ wait_idle(a, Duration::from_secs(30)).await?;+ tokio::time::sleep(Duration::from_millis(400)).await;+ // Put the plot's counted trace on the commanded one here (laser changes+ // before this, such as Tune's current steps, also make fringes).+ a.engine.lock().unwrap().stage_align();+ let c0 = counted(a);+ let t0 = truth(a);+ let ts0 = a.engine.lock().unwrap().head as f64 / crate::sim::FS;+ stage_ok(a, sub::MOVE_TO, start + pulses).await?;+ // The fringe swing and noise while the target moves (mid-move, 1 s).+ let move_s = pulses as f64 / rate as f64;+ tokio::time::sleep(Duration::from_secs_f64((move_s / 2.0 + 0.5).min(move_s - 0.1).max(0.2))).await;+ let ms = a.engine.lock().unwrap().chan_stats(1, ((move_s * 0.4).min(1.0) * 250_000.0) as usize);+ wait_idle(a, Duration::from_secs(30)).await?;+ let ts1 = a.engine.lock().unwrap().head as f64 / crate::sim::FS;+ let seg: Vec<TracePt> = a.engine.lock().unwrap().stage_trace.iter().filter(|p| p.t_s >= ts0 && p.t_s <= ts1).cloned().collect();+ let fit = edge_fit(&seg);+ tokio::time::sleep(Duration::from_millis(400)).await;+ let c1 = counted(a);+ let t1 = truth(a);+ stage_ok(a, sub::MOVE_TO, start).await?;+ wait_idle(a, Duration::from_secs(30)).await?;+ tokio::time::sleep(Duration::from_millis(400)).await;+ let c2 = counted(a);+ let t2 = truth(a);+ let nominal = pulses as f64 * NM_PER_PULSE;+ let cnt = c1 - c0;+ Ok(json!({+ "pulses": pulses, "commanded_nm_nominal": nominal, "counted_nm": cnt,+ "counted_fringes": (cnt / a.engine.lock().unwrap().det.half_wave_nm()).round(),+ "error_vs_nominal_nm": cnt - nominal, "error_vs_nominal_pct": if nominal != 0.0 { (cnt / nominal - 1.0) * 100.0 } else { 0.0 },+ "nm_per_pulse_counted": cnt / pulses as f64,+ "nm_per_pulse_edge_fit": fit.map(|f| f.0), "edge_fit_edges": fit.map(|f| f.1), "edge_fit_rms_nm": fit.map(|f| f.2),+ "moving_swing_codes": ms.swing.round(), "moving_noise_codes": (ms.noise * 100.0).round() / 100.0, "moving_score": (tune::score(&ms) * 10.0).round() / 10.0,+ "error_vs_truth_nm": cnt - (t1 - t0),+ "return_counted_nm": c2 - c0,+ "truth_nm": t1 - t0, "truth_return_nm": t2 - t0,+ }))+}++fn truth(a: &Arc<App>) -> f64 {+ a.engine.lock().unwrap().readout()["truth_nm"].as_f64().unwrap_or(f64::NAN)+}++/// Move the stage back and forth until `stop` is set (the moving target for Tune).+fn spawn_bounce(a: Arc<App>, stop: Arc<AtomicBool>) -> tokio::task::JoinHandle<()> {+ tokio::spawn(async move {+ let mut up = true;+ let _ = stage_cmd(&a, sub::SPEED, RATE_MAX).await;+ while !stop.load(Ordering::SeqCst) {+ let st = current_state(&a);+ if st.as_ref().is_some_and(|s| s.state == ST_IDLE) {+ let _ = stage_cmd(&a, sub::MOVE_TO, if up { TRAVEL - 200 } else { 200 }).await;+ up = !up;+ }+ if st.as_ref().is_some_and(|s| s.state == ST_FAULTED || s.state == ST_OFF) {+ break;+ }+ tokio::time::sleep(Duration::from_millis(30)).await;+ }+ let _ = stage_cmd(&a, sub::STOP, 0).await;+ })+}++#[derive(Clone, Debug, serde::Deserialize)]+#[serde(default)]+pub struct CalParams {+ pub confirm: Option<String>,+ /// Pulses for the re-check move.+ pub check_pulses: i32,+ /// Laser current to start from when the laser is off (mA).+ pub start_ma: f64,+}++impl Default for CalParams {+ fn default() -> Self {+ Self { confirm: None, check_pulses: 1024, start_ma: 75.0 }+ }+}++/// Calibrate: the stage is the moving target. Home; record the settings and a+/// counted-against-commanded check as they are; zero the current readback with+/// the laser off; turn it back on; auto-centre; tune while the stage moves back+/// and forth; check again; report before and after.+pub async fn calibrate(a: &Arc<App>, p: &CalParams) -> Result<Value, Fail> {+ let t0 = Instant::now();+ let sim = matches!(a.engine.lock().unwrap().source, SourceKind::Sim);+ let li = a.engine.lock().unwrap().map.laser();+ sim_follow_stage(a);+ cal_progress(a, "home", 1, json!({}));+ ensure_homed(a).await?;+ cancelled()?;++ // 1. Before: as the board is, laser on (from the start current if it was off).+ let was_on = a.engine.lock().unwrap().board_state().is_some_and(|s| s.laser_on);+ cal_progress(a, "before", 2, json!({}));+ if !was_on {+ let cur = a.engine.lock().unwrap().board_state().map(|s| s.laser_target_ma as f64).unwrap_or(0.0);+ tune::laser(a, true).await?;+ if cur < 1.0 {+ tune::set(a, li, 0, p.start_ma).await?;+ }+ tune::wait_settled(a).await?;+ tokio::time::sleep(Duration::from_millis(300)).await;+ }+ let before = snapshot_settings(a);+ let before_check = check_distance(a, 128, p.check_pulses, RATE_DEFAULT).await?;+ cancelled()?;++ // 2. Current-readback zero: laser off, wait for the zero code to settle.+ cal_progress(a, "readback zero", 3, json!({"before": {"settings": before, "check": before_check}}));+ let keep_ma = a.engine.lock().unwrap().board_state().map(|s| s.laser_target_ma as f64).unwrap_or(p.start_ma);+ tune::laser(a, false).await?;+ let tz = Instant::now();+ let zero = loop {+ tokio::time::sleep(Duration::from_millis(100)).await;+ let st = a.engine.lock().unwrap().board_state();+ let z = st.as_ref().and_then(|s| s.zero_code);+ let ma = st.as_ref().filter(|s| s.isense_valid).map(|s| s.isense_ma);+ if tz.elapsed() > Duration::from_millis(1500) && z.is_some() {+ break json!({"zero_code": z, "reading_with_laser_off_mA": ma, "seconds": tz.elapsed().as_secs_f64()});+ }+ if tz.elapsed() > Duration::from_secs(6) {+ return Err(fail("the current readback did not validate its zero within 6 s with the laser off", &["Check the head ADS1115 with `smi-dash board`"]));+ }+ };+ cancelled()?;++ // 3. Back on at the same set-point, then auto-centre both channels.+ cal_progress(a, "auto-centre", 4, json!({"zero": zero}));+ tune::laser(a, true).await?;+ tune::set(a, li, 0, keep_ma).await?;+ tune::wait_settled(a).await?;+ let mut centre = vec![];+ for ch in [1u8, 2] {+ centre.push(tune::auto_centre(a, ch).await.unwrap_or_else(|(m, _)| json!({"channel": ch, "error": m})));+ }+ cancelled()?;++ // 4. Tune with the stage moving back and forth at its maximum rate.+ cal_progress(a, "tune (stage moving)", 5, json!({"centre": centre}));+ if tune::TUNE_RUNNING.swap(true, Ordering::SeqCst) {+ return Err(fail("a tune is already running", &["Stop it with `smi-dash tune --stop`"]));+ }+ tune::TUNE_CANCEL.store(false, Ordering::SeqCst);+ let stop = Arc::new(AtomicBool::new(false));+ let bounce = spawn_bounce(a.clone(), stop.clone());+ let tuned = tune::tune(a.clone(), tune::TuneParams::default()).await;+ stop.store(true, Ordering::SeqCst);+ let _ = bounce.await;+ tune::TUNE_RUNNING.store(false, Ordering::SeqCst);+ let tuned = tuned?;+ wait_idle(a, Duration::from_secs(30)).await?;+ cancelled()?;++ // 5. Re-check: counted against commanded distance with the new settings.+ cal_progress(a, "re-check", 6, json!({"tune": {"best_mA": tuned["best_mA"], "gain": tuned["gain"], "final_score": tuned["final_score"], "steps": tuned["steps"].as_array().map(|s| s.len())}}));+ let after = snapshot_settings(a);+ let after_check = check_distance(a, 128, p.check_pulses, RATE_DEFAULT).await?;+ stage_ok(a, sub::SPEED, RATE_DEFAULT).await?;++ // 6. Report, and keep the counted scale for the commanded trace.+ let scale = after_check["nm_per_pulse_edge_fit"].as_f64().or(after_check["nm_per_pulse_counted"].as_f64()).unwrap_or(f64::NAN);+ let plausible = scale.abs() > 0.5 * GEOMETRY_NM_PER_PULSE[0] && scale.abs() < 1.5 * GEOMETRY_NM_PER_PULSE[1];+ if plausible {+ a.engine.lock().unwrap().stage_cal = Some(json!({"nm_per_pulse": scale.abs(), "sign": scale.signum(), "simulated": sim, "at": chrono::Local::now().to_rfc3339()}));+ }+ let report = json!({+ "status": "done",+ "simulated": sim,+ "label": if sim { "simulated" } else { "measured" },+ "seconds": t0.elapsed().as_secs_f64(),+ "before": {"settings": before, "check": before_check},+ "zero": zero,+ "centre": centre,+ "tune": {"best_mA": tuned["best_mA"], "gain": tuned["gain"], "final_score": tuned["final_score"], "note": tuned["note"], "steps": tuned["steps"].as_array().map(|s| s.len())},+ "after": {"settings": after, "check": after_check},+ "scale_nm_per_pulse": if plausible { json!(scale.abs()) } else { Value::Null },+ "scale_note": if plausible { json!(format!("Commanded positions now use {:.3} nm/pulse (fitted to the counted fringe edges of the re-check) instead of the nominal 15.625", scale.abs())) } else { json!("The counted scale is outside the plausible range; the nominal 15.625 nm/pulse stays") },+ "laser_left_on": true,+ "note": if was_on { "The laser was on before and is on after." } else { "The laser was off before; Calibrate turned it on with the interlock confirmed and leaves it on. `smi-dash laser off` turns it off." },+ });+ a.engine.lock().unwrap().calib = report.clone();+ Ok(report)+}++pub fn spawn_calibrate(a: Arc<App>, p: CalParams) -> Result<(), Fail> {+ if CAL_RUNNING.swap(true, Ordering::SeqCst) {+ return Err(fail("Calibrate is already running", &["Watch it with `smi-dash calibrate --status`"]));+ }+ CAL_CANCEL.store(false, Ordering::SeqCst);+ a.engine.lock().unwrap().calib = json!({"status": "running", "step": "start", "step_n": 0, "steps_total": 6});+ tokio::spawn(async move {+ match calibrate(&a, &p).await {+ Ok(r) => {+ let ca = &r["after"]["check"];+ let cb = &r["before"]["check"];+ a.broadcast("toast", json!({"text": format!("Calibrate ({}): counted {:.0} of {:.0} nm before, {:.0} after", r["label"].as_str().unwrap_or(""), cb["counted_nm"].as_f64().unwrap_or(0.0), cb["commanded_nm_nominal"].as_f64().unwrap_or(0.0), ca["counted_nm"].as_f64().unwrap_or(0.0)), "kind": "success"}));+ }+ Err((m, h)) => {+ tune::TUNE_CANCEL.store(true, Ordering::SeqCst);+ let mut e = a.engine.lock().unwrap();+ let mut v = e.calib.clone();+ v["status"] = json!("failed");+ v["error"] = json!(m);+ v["hints"] = json!(h);+ e.calib = v;+ drop(e);+ a.broadcast("toast", json!({"text": format!("Calibrate: {m}"), "kind": "error"}));+ }+ }+ CAL_RUNNING.store(false, Ordering::SeqCst);+ });+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ fn run(s: &mut SimStage, t: &mut u64, us: u64) {+ *t += us;+ s.advance(*t);+ }++ #[test]+ fn sim_stage_homes_moves_and_refuses() {+ let mut s = SimStage::new(0);+ let mut t = 0u64;+ let st = s.state();+ assert_eq!(st.state, ST_OFF);+ assert!(!st.enabled && !st.homed, "disabled at boot");+ // Not homed: a step is refused.+ let r = s.command(&cmd(sub::STEP, 10), 1, t);+ assert_eq!(r[3], 11);+ let r = s.command(&cmd(sub::HOME, 0), 2, t);+ assert_eq!(r[3], 0, "home accepted (driver configured over the simulated UART)");+ for _ in 0..400 {+ run(&mut s, &mut t, 100_000);+ if s.state().state == ST_IDLE {+ break;+ }+ }+ let st = s.state();+ assert!(st.homed && st.pos == 0, "homed at the switch edge: {st:?}");+ assert_eq!(s.mech.pulses, 0);+ // Limits.+ assert_eq!(s.command(&cmd(sub::MOVE_TO, 1601), 3, t)[3], 12);+ assert_eq!(s.command(&cmd(sub::STEP, -1), 4, t)[3], 12);+ // A move at 640 pulses/s; a retried sequence number issues no new pulses.+ assert_eq!(s.command(&cmd(sub::SPEED, 640), 5, t)[3], 0);+ assert_eq!(s.command(&cmd(sub::STEP, 320), 6, t)[3], 0);+ let again = s.command(&cmd(sub::STEP, 320), 6, t);+ assert_eq!(again[3], 0);+ run(&mut s, &mut t, 600_000);+ assert_eq!(s.state().pos, 320);+ assert_eq!(s.mech.pulses, 320, "the duplicate did not move it");+ // The mirror follows at the true scale.+ let want = 320.0 * mech::TRUE_NM_PER_PULSE;+ assert!((s.mirror_nm - want).abs() < 30.0, "mirror {} vs {want}", s.mirror_nm);+ // Off: disabled, position invalid.+ assert_eq!(s.command(&cmd(sub::OFF, 0), 7, t)[3], 0);+ assert!(!s.state().homed);+ }++ #[test]+ fn selftest_analysis_recovers_scale_and_drift() {+ let mut tr = vec![];+ let mut t = 0.0;+ let positions = [128, 256, 384, 512, 640, 512, 384, 256, 128];+ for (k, &p) in positions.iter().enumerate() {+ for i in 0..50 {+ let tt = t + i as f64 * 0.02;+ let truth = p as f64 * 15.3 + 0.6 * tt;+ // Counted: whole fringes of 329 nm.+ let meas = (truth / 329.0).round() * 329.0;+ tr.push(TracePt { t_s: tt, pos: p, moving: false, state: ST_SELFTEST, homed: true, meas_nm: meas, truth_nm: truth });+ }+ t += 1.0;+ if k < 8 {+ tr.push(TracePt { t_s: t - 0.01, pos: p, moving: true, state: ST_SELFTEST, homed: true, meas_nm: 0.0, truth_nm: 0.0 });+ }+ }+ let pl = plateaus(&tr);+ assert_eq!(pl.len(), 9);+ let v = analyse(&pl, true, 329.0);+ let s = v["truth"]["nm_per_pulse"].as_f64().unwrap();+ assert!((s - 15.3).abs() < 0.01, "truth slope {s}");+ assert!((v["truth"]["drift_nm_s"].as_f64().unwrap() - 0.6).abs() < 0.05);+ let sc = v["counted"]["nm_per_pulse"].as_f64().unwrap();+ assert!((sc - 15.3).abs() < 0.6, "counted slope {sc}");+ }+}
software/dashboard/src/tune.rs+3−3@@ -29,7 +29,7 @@ pub async fn cmd(a: &Arc<App>, payload: Vec<u8>) -> Result<Ack, Fail> { }; 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`"]));+ return Err(fail("the simulator is modelling the v1.1 board, which has no software controls", &["Turn the board 1.3 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", &[]));@@ -50,7 +50,7 @@ pub async fn cmd(a: &Arc<App>, payload: Vec<u8>) -> Result<Ack, Fail> { } 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()])),+ Ok(Err(m)) => Err((m, vec!["Check the link with `smi-dash status`; the Pico must run firmware 1.3.1 (`smi-dash board map`)".into()])), Err(e) => Err(fail(format!("command task failed: {e}"), &[])), } }@@ -210,7 +210,7 @@ pub async fn wait_ramp(a: &Arc<App>) -> Result<(), Fail> { // 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?"])),+ None => return Err(fail("no board state", &["Is the Pico running firmware 1.3.1?"])), _ => {} } if t.elapsed() > Duration::from_secs(15) {
software/dist/SHA256SUMS+3−3@@ -1,3 +1,3 @@-e263677d31d6af4d997db00ee92a4a135ac3a28830cda2afbc0f02213fbbc9c4 smi_pico.uf2-ae81a40ab4841d8525d5a8a63db6f8dcdec75dfdfa86d84aa05d60241e5ba89e smi-dash-linux-x64-b4c2f0e8dd6642aee31db46ef500549d75474103be79323800685ccde5db962b smi-dash-windows-x64.exe+9e6ea6edd1152440192da80cd69a12549b87dc5095f2131bd4e5c364e78367ff smi_pico.uf2+5b906c365b67bdb5f9ac8f84d9674fc0d536e549bd7688d42e6874ff13c8ba98 smi-dash-linux-x64+389f7e30c5707fa7a31610ca49d9c7f57b5c6303693658ed7fd553164f94fef9 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+1@@ -11,6 +11,7 @@ add_executable(smi_pico src/smi_frame.c src/smi_ctl.c src/smi_text.c+ src/smi_stage.c src/usb_descriptors.c ) target_include_directories(smi_pico PRIVATE ${CMAKE_CURRENT_LIST_DIR}/src)
software/firmware/README.md+10−6@@ -1,6 +1,6 @@ # Pico firmware: smi_pico -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.+Turns a Raspberry Pi Pico (RP2040, SC0915) into the interferometer's two-channel digitizer and, since board 1.2 (now 1.3), 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. On board 1.3 it also drives the test stage on J4. | Pin | Use | |---|---|@@ -13,8 +13,11 @@ Turns a Raspberry Pi Pico (RP2040, SC0915) into the interferometer's two-channel | 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 |+| GPIO10, GPIO11, GPIO12 | Stage (J4) STEP, DIR, EN_N (active low; driven high at boot before anything else touches the port) |+| GPIO13 | Stage TMC2209 PDN_UART, one wire, 115200 8N1, bit-banged half duplex (driven only while sending, released after the stop bit) |+| GPIO14 | Stage HOME, normally closed to ground with the board's 10 k pull-up (high = open or disconnected) | -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.+The board's pins and devices come from its control map: `controls/gen_controls.py` writes them into `src/smi_controls_gen.h`. Rebuild after changing the map. ## Flashing @@ -29,7 +32,8 @@ The v1.2 pins and devices come from the board's control map: `controls/gen_contr - 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`, 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.+- Controls (board 1.2 and 1.3): 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.+- Test stage (board 1.3, `src/smi_stage.c`, rules in `src/smi_stage.h`): disabled at boot; the TMC2209 is configured over its UART with EN_N high, every write checked by IFCNT, before it is enabled; homing as `test-stage/design/stage-map.json` describes; moves only inside 0 to 1600 pulses from HOME after homing; 160 pulses/s by default, at most 640; disabled on a fault, `stage off`, USB loss, or (after the first binary command) 3 s without a host command. Binary op 0x09 (status, home, step, speed, stop, off, current, selftest, move) with sequence-number duplicate suppression; text `stage ...` lines. A STAGE frame every 50 ms while enabled, else every 500 ms. `DIR_POS_LEVEL` in `smi_stage.c` sets the DIR polarity for commissioning. Board 1.4 keeps the same GPIO numbers. - 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@@ -39,7 +43,7 @@ All fields little-endian. Every frame: | Bytes | Field | |---|---| | 2 | sync word `A5 5A` |-| 1 | type: 1 DATA, 2 SYNC, 3 STATUS, 4 INFO, 0x10 CMD (host to Pico), 0x11 ACK, 0x12 STATE |+| 1 | type: 1 DATA, 2 SYNC, 3 STATUS, 4 INFO, 0x10 CMD (host to Pico), 0x11 ACK, 0x12 STATE, 0x13 STAGE | | 1 | flags, 0 | | 2 | payload length | | 2 | sequence number, wraps |@@ -48,7 +52,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`, then (1.2.0) `u32 adc2_pauses`, `u16 rail_mV`. 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. STAGE payload (1.3.1): `u8 state` (0 off, 1 idle, 2 homing, 3 moving, 4 selftest, 5 faulted), `u8 flags` (1 enabled, 2 homed, 4 HOME high, 8 moving), `u8 fault`, `u8 home_phase`, `i32 pos`, `i32 target`, `u16 rate`, `u8 selftest_rung`, `u8 ifcnt`, `u32 steps_total`, `u32 drv_status`, then `u64 pair` (the sample-pair count when sent). 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. @@ -64,7 +68,7 @@ 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_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/test_stage.c` runs the stage core against a mock TMC2209 and screw (62 checks; `cc -O2 -Isrc test/test_stage.c src/smi_stage.c`). `test/ctl_pty.c` serves the control, stage, text-command and frame code behind a pseudo-terminal (`cc -O2 -Isrc test/ctl_pty.c src/smi_ctl.c src/smi_text.c src/smi_frame.c src/smi_stage.c -lm`), so the dashboard's serial command path and the text commands (`test/text_cmd_test.py`, 20 checks including the stage) 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+123−6@@ -54,8 +54,9 @@ #include "smi_ctl.h" #include "smi_controls_gen.h" #include "smi_text.h"+#include "smi_stage.h" -#define FW_VERSION "1.2.1"+#define FW_VERSION "1.3.1" #define SYNC_GPIO 15 #define RAIL_GPIO 28 #define PAIRS_PER_BUF 1024@@ -86,6 +87,7 @@ 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;+static smi_stage_t stage; #define I2C_INST (SMI_I2C_BUS ? i2c1 : i2c0) @@ -236,11 +238,95 @@ static bool ads_read(int32_t *v) { return true; } ++// ------------------------------------------------------------------- stage --+// TMC2209 stage on J4 (smi_stage.c). STEP, DIR and EN_N are plain outputs; HOME+// has the board's 10 k pull-up. PDN_UART is one wire, bit-banged at 115200 8N1:+// the Pico drives it only while it sends and releases it right after the stop+// bit, then listens for the reply. Each byte runs with interrupts off (87 us);+// the ADC DMA keeps running and its completion IRQ is only delayed.+#define STAGE_BIT_US (1000000.0f / 115200.0f)++static void stage_put(void *ctx, uint8_t g, bool v) { (void)ctx; gpio_put(g, v); }+static bool stage_home(void *ctx) { (void)ctx; return gpio_get(SMI_STAGE_HOME_GPIO); }+static void stage_wait(void *ctx, uint32_t us) { (void)ctx; busy_wait_us_32(us); }++static void wait_until(uint32_t t0, float off_us) {+ while ((float)(time_us_32() - t0) < off_us) tight_loop_contents();+}++static void uart_tx_byte(uint8_t b) {+ uint32_t irq = save_and_disable_interrupts();+ uint32_t t0 = time_us_32();+ uint16_t frame = (uint16_t)(0x200u | ((uint16_t)b << 1)); // start 0, 8 data LSB first, stop 1+ for (int i = 0; i < 10; i++) {+ gpio_put(SMI_STAGE_UART_GPIO, (frame >> i) & 1u);+ wait_until(t0, STAGE_BIT_US * (float)(i + 1));+ }+ restore_interrupts(irq);+}++static bool uart_rx_byte(uint8_t *b, uint32_t timeout_us) {+ uint32_t t = time_us_32();+ while (gpio_get(SMI_STAGE_UART_GPIO)) { // wait for the start bit+ if (time_us_32() - t > timeout_us) return false;+ }+ uint32_t irq = save_and_disable_interrupts();+ uint32_t t0 = time_us_32();+ uint8_t v = 0;+ for (int i = 0; i < 8; i++) {+ wait_until(t0, STAGE_BIT_US * (1.5f + (float)i)); // middle of data bit i+ v |= (uint8_t)(gpio_get(SMI_STAGE_UART_GPIO) << i);+ }+ wait_until(t0, STAGE_BIT_US * 9.5f);+ bool stop_ok = gpio_get(SMI_STAGE_UART_GPIO);+ restore_interrupts(irq);+ *b = v;+ return stop_ok;+}++static bool stage_uart(void *ctx, const uint8_t *tx, size_t ntx, uint8_t *rxb, size_t nrx) {+ (void)ctx;+ gpio_put(SMI_STAGE_UART_GPIO, 1);+ gpio_set_dir(SMI_STAGE_UART_GPIO, GPIO_OUT);+ for (size_t i = 0; i < ntx; i++) uart_tx_byte(tx[i]);+ gpio_set_dir(SMI_STAGE_UART_GPIO, GPIO_IN); // release the line after the stop bit+ busy_wait_us_32(200); // writes need a gap before the next datagram+ for (size_t i = 0; i < nrx; i++) {+ if (!uart_rx_byte(&rxb[i], i == 0 ? 2000u : 300u)) return false;+ watchdog_update();+ }+ return true;+}++static void stage_init(void) {+ // EN_N high (driver off) before anything else touches the stage port.+ gpio_init(SMI_STAGE_EN_N_GPIO);+ gpio_put(SMI_STAGE_EN_N_GPIO, 1);+ gpio_set_dir(SMI_STAGE_EN_N_GPIO, GPIO_OUT);+ gpio_init(SMI_STAGE_STEP_GPIO);+ gpio_put(SMI_STAGE_STEP_GPIO, 0);+ gpio_set_dir(SMI_STAGE_STEP_GPIO, GPIO_OUT);+ gpio_init(SMI_STAGE_DIR_GPIO);+ gpio_set_dir(SMI_STAGE_DIR_GPIO, GPIO_OUT);+ gpio_init(SMI_STAGE_HOME_GPIO);+ gpio_set_dir(SMI_STAGE_HOME_GPIO, GPIO_IN);+ gpio_disable_pulls(SMI_STAGE_HOME_GPIO); // 10 k to 3V3 on the board+ gpio_init(SMI_STAGE_UART_GPIO);+ gpio_set_dir(SMI_STAGE_UART_GPIO, GPIO_IN);+ gpio_pull_up(SMI_STAGE_UART_GPIO); // idle high while released+ smi_stage_hal_t h = { .ctx = NULL, .put = stage_put, .home_in = stage_home, .wait_us = stage_wait, .uart = stage_uart };+ smi_stage_init(&stage, &h);+}++static void stage_service(void) { smi_stage_tick(&stage, time_us_32()); }+ 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);+ stage_init(); // stage driver disabled on boot 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++) {@@ -431,6 +517,7 @@ static bool cdc_write_all(const uint8_t *p, size_t n) { if (avail == 0) { tud_task(); laser_service();+ stage_service(); if (time_us_32() - t0 > 50000u) return false; continue; }@@ -495,11 +582,18 @@ static void send_state(void) { send_small(SMI_T_STATE, pl, (uint16_t)n); } +static void send_stage(void) {+ uint8_t pl[32];+ size_t n = smi_stage_state(&stage, pl);+ smi_put_u64(pl + n, (uint64_t)bufs_done * PAIRS_PER_BUF);+ send_small(SMI_T_STAGE, pl, (uint16_t)(n + 8));+}+ static void send_info(void) { 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; "- "map=" SMI_MAP_VERSION "; map_hash=%08lx; controls=%u; head_io=%s; head_adc=%s; boot=%s",+ "map=" SMI_MAP_VERSION "; map_hash=%08lx; controls=%u; head_io=%s; head_adc=%s; boot=%s; stage=J4 GP10-14", 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);@@ -508,6 +602,9 @@ static void send_info(void) { // -------------------------------------------------------------- commands in -- static uint8_t rx[8 + 160 + 2];+// Set by the first binary command after a connect (a dashboard host, which sends+// heartbeats). Text-only sessions rely on the USB disconnect rule alone.+static bool stage_host_watch; static int rx_len; static void handle_cmd_frame(void) {@@ -516,7 +613,12 @@ static void handle_cmd_frame(void) { 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);+ // Any binary command is host activity; from the first one on, the stage+ // also stops if the host goes quiet (see the main loop).+ ctl.last_host_us = time_us_32();+ stage_host_watch = true;+ size_t n = (len >= 1 && rx[8] == SMI_OP_STAGE) ? smi_stage_command(&stage, rx + 8, len, cseq, time_us_32(), resp)+ : smi_ctl_command(&ctl, rx + 8, len, cseq, time_us_32(), resp); send_small(SMI_T_ACK, resp, (uint16_t)n); } @@ -526,8 +628,14 @@ static void text_send(void *ctx, const char *t) { (void)ctx; send_small(SMI_T_IN 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 void text_stage(void *ctx, const char *c) {+ (void)ctx;+ char r[200];+ smi_stage_text(&stage, c, time_us_32(), r, sizeof r);+ send_small(SMI_T_INFO, (const uint8_t *)r, (uint16_t)strlen(r));+} 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 };+ .stop = text_stop, .info = text_info, .stage = text_stage, .exp_base = SMI_EXP_BASE, .gain_base = 7 }; static void poll_commands(void) { while (tud_cdc_available()) {@@ -579,7 +687,7 @@ int main(void) { watchdog_enable(WATCHDOG_MS, true); bool was_connected = false;- uint32_t last_status = 0, last_state = 0, next_isense = time_us_32(), next_rail = time_us_32();+ uint32_t last_stage = 0, last_status = 0, last_state = 0, next_isense = time_us_32(), next_rail = time_us_32(); while (true) { watchdog_update(); tud_task();@@ -588,9 +696,15 @@ int main(void) { if (usb_gone) { usb_gone = false; smi_ctl_link_lost(&ctl, SMI_OFF_USB);+ smi_stage_link_lost(&stage); } if (conn && !was_connected) { send_info(); acq_start(); }- if (!conn && was_connected) { acq_stop(); smi_ctl_link_lost(&ctl, SMI_OFF_USB); }+ if (!conn && was_connected) { acq_stop(); smi_ctl_link_lost(&ctl, SMI_OFF_USB); smi_stage_link_lost(&stage); stage_host_watch = false; }+ // A dashboard host that stops sending (crash, hang) for the heartbeat+ // timeout also disables the stage driver; the position becomes invalid.+ if (stage_host_watch && stage.enabled && ctl.hb_timeout_ms &&+ (uint32_t)(now - ctl.last_host_us) > (uint32_t)ctl.hb_timeout_ms * 1000u)+ smi_stage_link_lost(&stage); was_connected = conn; if ((int32_t)(now - next_isense) >= 0) {@@ -606,6 +720,7 @@ int main(void) { rail_mv = (uint16_t)(adc2_read() * SMI_RAIL_SCALE * 1000.0f + 0.5f); } laser_service();+ stage_service(); if (!conn) continue; poll_commands(); @@ -629,10 +744,12 @@ int main(void) { bufs_sent++; poll_commands(); // commands are answered between frames laser_service();+ stage_service(); } now = time_us_32(); if (now - last_status > 500000) { last_status = now; send_status(); } if (now - last_state > 250000) { last_state = now; send_state(); }+ if (now - last_stage > (stage.enabled ? 50000u : 500000u)) { last_stage = now; send_stage(); } } }
software/firmware/src/smi_controls_gen.h+3−3@@ -1,12 +1,12 @@ // 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+// map_version 1.3.0-revision-1.3-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_MAP_HASH 0x46E9CADBu+#define SMI_MAP_VERSION "1.3.0-revision-1.3-controller-contract" #define SMI_I2C_BUS 0 #define SMI_I2C_SDA 4 #define SMI_I2C_SCL 5
software/firmware/src/smi_stage.cadded+341@@ -0,0 +1,341 @@+// SPDX-License-Identifier: MIT+// Test-stage control core. See smi_stage.h for the rules it enforces.+#include "smi_stage.h"+#include <stdio.h>+#include <string.h>+#include <stdlib.h>++// DIR level for positive motion (away from HOME). The stage map leaves the+// polarity to commissioning; flip this if the first homing search runs away.+#define DIR_POS_LEVEL true++enum { HP_NONE = 0, HP_RELEASE = 1, HP_APPROACH = 2, HP_VERIFY = 3, HP_BACKOFF = 4, HP_SLOW = 5 };+static const int16_t ST_DELTAS[SMI_STAGE_SELFTEST_RUNGS] = { 128, 128, 128, 128, -128, -128, -128, -128 };++uint8_t smi_tmc_crc(const uint8_t *d, size_t n) {+ uint8_t crc = 0;+ for (size_t i = 0; i < n; i++) {+ uint8_t b = d[i];+ for (int j = 0; j < 8; j++) {+ if (((crc >> 7) ^ (b & 1)) != 0) crc = (uint8_t)((crc << 1) ^ 0x07);+ else crc = (uint8_t)(crc << 1);+ b >>= 1;+ }+ }+ return crc;+}++static bool tmc_read(smi_stage_t *s, uint8_t reg, uint32_t *v) {+ uint8_t tx[4] = { 0x05, SMI_TMC_ADDR, reg, 0 };+ tx[3] = smi_tmc_crc(tx, 3);+ uint8_t rx[8];+ if (!s->hal.uart || !s->hal.uart(s->hal.ctx, tx, 4, rx, 8)) return false;+ if (rx[0] != 0x05 || rx[1] != 0xFF || rx[2] != reg || rx[7] != smi_tmc_crc(rx, 7)) return false;+ *v = ((uint32_t)rx[3] << 24) | ((uint32_t)rx[4] << 16) | ((uint32_t)rx[5] << 8) | rx[6];+ return true;+}++static bool tmc_write(smi_stage_t *s, uint8_t reg, uint32_t v) {+ uint8_t tx[8] = { 0x05, SMI_TMC_ADDR, (uint8_t)(reg | 0x80), (uint8_t)(v >> 24), (uint8_t)(v >> 16), (uint8_t)(v >> 8), (uint8_t)v, 0 };+ tx[7] = smi_tmc_crc(tx, 7);+ if (!s->hal.uart || !s->hal.uart(s->hal.ctx, tx, 8, NULL, 0)) return false;+ uint32_t c;+ if (!tmc_read(s, SMI_TMC_IFCNT, &c)) return false;+ // Every successful write increments IFCNT, modulo 256.+ if ((uint8_t)c != (uint8_t)(s->ifcnt + 1)) return false;+ s->ifcnt = (uint8_t)c;+ return true;+}++static void set_enable(smi_stage_t *s, bool on) {+ s->hal.put(s->hal.ctx, SMI_STAGE_EN_N_GPIO, !on); // EN_N is active low+ s->enabled = on;+}++static void disable(smi_stage_t *s, uint8_t fault) {+ set_enable(s, false);+ s->homed = false; // position invalid after disable+ s->home_phase = HP_NONE;+ s->fault = fault;+ s->state = fault ? SMI_STAGE_FAULTED : SMI_STAGE_OFF;+}++// Configure the driver with EN_N high; enable only if every step verified.+static bool driver_config(smi_stage_t *s) {+ set_enable(s, false);+ uint32_t v;+ if (!tmc_read(s, SMI_TMC_IOIN, &v)) return false;+ s->ioin = v;+ if ((v >> 24) != SMI_TMC_VERSION) return false;+ if (!tmc_read(s, SMI_TMC_IFCNT, &v)) return false;+ s->ifcnt = (uint8_t)v;+ if (!tmc_write(s, SMI_TMC_GCONF, SMI_TMC_GCONF_VAL)) return false;+ if (!tmc_write(s, SMI_TMC_SLAVECONF, SMI_TMC_SLAVECONF_VAL)) return false;+ if (!tmc_write(s, SMI_TMC_IHOLD_IRUN, SMI_TMC_IHOLD_IRUN_VAL)) return false;+ if (!tmc_write(s, SMI_TMC_CHOPCONF, SMI_TMC_CHOPCONF_VAL)) return false;+ if (!tmc_write(s, SMI_TMC_VACTUAL, 0)) return false;+ if (!tmc_write(s, SMI_TMC_GSTAT, 0x7)) return false; // clear reset, drv_err, uv_cp+ if (!tmc_read(s, SMI_TMC_GSTAT, &v) || (v & 0x6)) return false; // drv_err or uv_cp still set+ if (!tmc_read(s, SMI_TMC_GCONF, &v) || v != SMI_TMC_GCONF_VAL) return false;+ if (!tmc_read(s, SMI_TMC_CHOPCONF, &v) || v != SMI_TMC_CHOPCONF_VAL) return false;+ if (!tmc_read(s, SMI_TMC_DRV_STATUS, &v)) return false;+ s->drv_status = v;+ set_enable(s, true);+ return true;+}++void smi_stage_init(smi_stage_t *s, const smi_stage_hal_t *hal) {+ memset(s, 0, sizeof *s);+ s->hal = *hal;+ s->rate = SMI_STAGE_RATE_DEFAULT;+ s->hal.put(s->hal.ctx, SMI_STAGE_STEP_GPIO, false);+ s->hal.put(s->hal.ctx, SMI_STAGE_DIR_GPIO, DIR_POS_LEVEL);+ s->dir_pos = true;+ disable(s, SMI_STAGE_FAULT_NONE); // disabled on boot+}++static bool home_high(smi_stage_t *s) { return s->hal.home_in(s->hal.ctx); }++static void pulse(smi_stage_t *s, bool positive, uint32_t now) {+ if (positive != s->dir_pos) {+ s->hal.put(s->hal.ctx, SMI_STAGE_DIR_GPIO, positive ? DIR_POS_LEVEL : !DIR_POS_LEVEL);+ s->dir_pos = positive;+ if (s->hal.wait_us) s->hal.wait_us(s->hal.ctx, SMI_STAGE_DIR_SETUP_US);+ }+ s->hal.put(s->hal.ctx, SMI_STAGE_STEP_GPIO, true);+ if (s->hal.wait_us) s->hal.wait_us(s->hal.ctx, SMI_STAGE_STEP_HIGH_US);+ s->hal.put(s->hal.ctx, SMI_STAGE_STEP_GPIO, false);+ if (s->hal.wait_us) s->hal.wait_us(s->hal.ctx, SMI_STAGE_DIR_SETUP_US); // DIR hold after the edge+ s->pos += positive ? 1 : -1;+ s->steps_total++;+ s->last_step_us = now;+}++static void schedule(smi_stage_t *s, uint32_t now, uint16_t rate) {+ s->move_rate = rate;+ s->next_us = now + 1000000u / rate;+}++// True when a pulse is due now; keeps the rate exact without bursts after a stall.+static bool due(smi_stage_t *s, uint32_t now) {+ if ((int32_t)(now - s->next_us) < 0) return false;+ uint32_t per = 1000000u / s->move_rate;+ s->next_us += per;+ if ((int32_t)(now - s->next_us) >= 0) s->next_us = now + per;+ return true;+}++static void home_fail(smi_stage_t *s, uint8_t f) { disable(s, f); }++static void homing_tick(smi_stage_t *s, uint32_t now) {+ bool hi = home_high(s);+ switch (s->home_phase) {+ case HP_RELEASE: // started on the switch: release search only+ if (!hi) { s->home_phase = HP_APPROACH; s->phase_count = 0; schedule(s, now, SMI_STAGE_RATE_HOME); return; }+ if (s->phase_count >= SMI_STAGE_HOME_MAX_RELEASE) { home_fail(s, SMI_STAGE_FAULT_HOME_STUCK); return; }+ if (due(s, now)) { pulse(s, true, now); s->phase_count++; }+ return;+ case HP_APPROACH: // negative at 80 pulses/s until the first high+ if (hi) { s->home_phase = HP_VERIFY; s->high_since_us = now; return; }+ if (s->phase_count >= SMI_STAGE_HOME_MAX_SEARCH) { home_fail(s, SMI_STAGE_FAULT_HOME_TIMEOUT); return; }+ if (due(s, now)) { pulse(s, false, now); s->phase_count++; }+ return;+ case HP_VERIFY: // high must hold for 5 ms+ if (!hi) { s->home_phase = HP_APPROACH; schedule(s, now, SMI_STAGE_RATE_HOME); return; }+ if (now - s->high_since_us >= SMI_STAGE_HOME_VERIFY_US) {+ s->home_phase = HP_BACKOFF; s->phase_count = 0; s->high_seen = false; schedule(s, now, SMI_STAGE_RATE_HOME);+ }+ return;+ case HP_BACKOFF: // positive until low, then 32 more+ if (!s->high_seen && !hi) { s->high_seen = true; s->target = SMI_STAGE_HOME_BACKOFF; s->phase_count = 0; }+ if (s->high_seen && s->phase_count >= s->target) { s->home_phase = HP_SLOW; s->phase_count = 0; schedule(s, now, SMI_STAGE_RATE_HOME_SLOW); return; }+ if (!s->high_seen && s->phase_count >= SMI_STAGE_HOME_MAX_SEARCH) { home_fail(s, SMI_STAGE_FAULT_HOME_STUCK); return; }+ if (due(s, now)) { pulse(s, true, now); s->phase_count++; }+ return;+ case HP_SLOW: // re-approach at 32 pulses/s; zero on the opening edge+ if (hi) {+ s->pos = 0; s->target = 0; s->homed = true; s->home_phase = HP_NONE; s->state = SMI_STAGE_IDLE;+ return;+ }+ if (s->phase_count >= SMI_STAGE_HOME_BACKOFF + SMI_STAGE_HOME_MAX_RELEASE) { home_fail(s, SMI_STAGE_FAULT_HOME_TIMEOUT); return; }+ if (due(s, now)) { pulse(s, false, now); s->phase_count++; }+ return;+ default:+ return;+ }+}++// One step of a normal move toward s->target. Returns true when it arrived.+static bool move_tick(smi_stage_t *s, uint32_t now) {+ if (s->pos == s->target) return true;+ if (!due(s, now)) return false;+ pulse(s, s->target > s->pos, now);+ if (home_high(s) && s->pos > SMI_STAGE_HOME_ZONE) { disable(s, SMI_STAGE_FAULT_HOME_UNEXPECTED); return false; }+ return s->pos == s->target;+}++void smi_stage_tick(smi_stage_t *s, uint32_t now) {+ switch (s->state) {+ case SMI_STAGE_HOMING: homing_tick(s, now); break;+ case SMI_STAGE_MOVING:+ if (move_tick(s, now) && s->state == SMI_STAGE_MOVING) s->state = SMI_STAGE_IDLE;+ break;+ case SMI_STAGE_SELFTEST:+ if (s->dwell_until_us) {+ if ((int32_t)(now - s->dwell_until_us) < 0) break;+ s->dwell_until_us = 0;+ if (s->st_index >= SMI_STAGE_SELFTEST_RUNGS) { s->state = SMI_STAGE_IDLE; break; }+ s->target = s->pos + ST_DELTAS[s->st_index++];+ schedule(s, now, s->rate);+ break;+ }+ if (move_tick(s, now) && s->state == SMI_STAGE_SELFTEST) s->dwell_until_us = now + SMI_STAGE_SELFTEST_DWELL_US;+ break;+ case SMI_STAGE_IDLE:+ // Watch the driver while it holds position.+ if (s->enabled && now - s->last_poll_us > 500000u) {+ s->last_poll_us = now;+ uint32_t v;+ if (!tmc_read(s, SMI_TMC_DRV_STATUS, &v)) { disable(s, SMI_STAGE_FAULT_DRIVER); break; }+ s->drv_status = v;+ if (v & 0x3Eu) disable(s, SMI_STAGE_FAULT_DRV_STATUS); // ot, s2ga, s2gb, s2vsa, s2vsb+ }+ break;+ default: break;+ }+}++void smi_stage_link_lost(smi_stage_t *s) {+ if (s->enabled) disable(s, SMI_STAGE_FAULT_LINK);+}++static uint8_t do_cmd(smi_stage_t *s, uint8_t sub, int32_t arg, uint32_t now) {+ bool busy = s->state == SMI_STAGE_HOMING || s->state == SMI_STAGE_MOVING || s->state == SMI_STAGE_SELFTEST;+ switch (sub) {+ case SMI_STAGE_SUB_STATUS: return SMI_STAGE_OK;+ case SMI_STAGE_SUB_OFF: disable(s, SMI_STAGE_FAULT_NONE); return SMI_STAGE_OK;+ case SMI_STAGE_SUB_STOP:+ if (s->state == SMI_STAGE_HOMING) { s->home_phase = HP_NONE; s->homed = false; s->state = SMI_STAGE_IDLE; }+ else if (busy) { s->target = s->pos; s->dwell_until_us = 0; s->state = SMI_STAGE_IDLE; }+ return SMI_STAGE_OK;+ case SMI_STAGE_SUB_SPEED:+ if (arg == 0) return SMI_STAGE_OK;+ if (arg < 1 || arg > SMI_STAGE_RATE_MAX) return SMI_STAGE_E_RATE;+ s->rate = (uint16_t)arg;+ if (s->state == SMI_STAGE_MOVING || (s->state == SMI_STAGE_SELFTEST && !s->dwell_until_us)) s->move_rate = s->rate;+ return SMI_STAGE_OK;+ case SMI_STAGE_SUB_CURRENT: {+ if (!s->enabled) return SMI_STAGE_OK;+ if (busy) return SMI_STAGE_E_BUSY;+ uint32_t v;+ if (!tmc_read(s, SMI_TMC_DRV_STATUS, &v)) { disable(s, SMI_STAGE_FAULT_DRIVER); return SMI_STAGE_E_DRIVER; }+ s->drv_status = v;+ return SMI_STAGE_OK;+ }+ case SMI_STAGE_SUB_HOME:+ if (s->state == SMI_STAGE_FAULTED) return SMI_STAGE_E_FAULT;+ if (busy) return SMI_STAGE_E_BUSY;+ if (!s->enabled && !driver_config(s)) { disable(s, SMI_STAGE_FAULT_DRIVER); return SMI_STAGE_E_DRIVER; }+ s->homed = false; s->pos = 0; s->phase_count = 0;+ s->home_phase = home_high(s) ? HP_RELEASE : HP_APPROACH;+ s->state = SMI_STAGE_HOMING;+ schedule(s, now, SMI_STAGE_RATE_HOME);+ return SMI_STAGE_OK;+ case SMI_STAGE_SUB_STEP:+ case SMI_STAGE_SUB_MOVE_TO:+ case SMI_STAGE_SUB_SELFTEST: {+ if (s->state == SMI_STAGE_FAULTED) return SMI_STAGE_E_FAULT;+ if (!s->enabled || !s->homed) return SMI_STAGE_E_NOT_HOMED;+ if (busy) return SMI_STAGE_E_BUSY;+ int32_t t = sub == SMI_STAGE_SUB_STEP ? s->pos + arg : sub == SMI_STAGE_SUB_MOVE_TO ? arg : SMI_STAGE_SELFTEST_ORIGIN;+ if (t < 0 || t > SMI_STAGE_TRAVEL_MAX) return SMI_STAGE_E_LIMIT;+ s->target = t;+ schedule(s, now, s->rate);+ if (sub == SMI_STAGE_SUB_SELFTEST) { s->st_index = 0; s->dwell_until_us = 0; s->state = SMI_STAGE_SELFTEST; }+ else s->state = t == s->pos ? SMI_STAGE_IDLE : SMI_STAGE_MOVING;+ return SMI_STAGE_OK;+ }+ default: return SMI_STAGE_E_SUB;+ }+}++static void put32(uint8_t *p, uint32_t v) { p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); p[2] = (uint8_t)(v >> 16); p[3] = (uint8_t)(v >> 24); }++size_t smi_stage_state(const smi_stage_t *s, uint8_t *o) {+ uint8_t fl = (s->enabled ? SMI_STAGE_FLAG_ENABLED : 0) | (s->homed ? SMI_STAGE_FLAG_HOMED : 0) |+ (s->hal.home_in(s->hal.ctx) ? SMI_STAGE_FLAG_HOME_IN : 0) |+ ((s->state == SMI_STAGE_MOVING || s->state == SMI_STAGE_HOMING || (s->state == SMI_STAGE_SELFTEST && !s->dwell_until_us)) ? SMI_STAGE_FLAG_MOVING : 0);+ o[0] = s->state; o[1] = fl; o[2] = s->fault; o[3] = s->home_phase;+ put32(o + 4, (uint32_t)s->pos); put32(o + 8, (uint32_t)s->target);+ o[12] = (uint8_t)s->rate; o[13] = (uint8_t)(s->rate >> 8);+ o[14] = s->st_index; o[15] = s->ifcnt;+ put32(o + 16, s->steps_total); put32(o + 20, s->drv_status);+ return 24;+}++size_t smi_stage_command(smi_stage_t *s, const uint8_t *p, size_t n, uint16_t seq, uint32_t now, uint8_t *resp) {+ // A retried command (same nonzero seq) gets the cached answer and no new pulses.+ if (seq && s->have_last && seq == s->last_seq) { memcpy(resp, s->last_resp, s->last_len); return s->last_len; }+ uint8_t st;+ if (n < 6) st = SMI_STAGE_E_LEN;+ else {+ int32_t arg = (int32_t)((uint32_t)p[2] | ((uint32_t)p[3] << 8) | ((uint32_t)p[4] << 16) | ((uint32_t)p[5] << 24));+ st = do_cmd(s, p[1], arg, now);+ }+ resp[0] = (uint8_t)seq; resp[1] = (uint8_t)(seq >> 8); resp[2] = SMI_OP_STAGE; resp[3] = st;+ size_t len = 4 + smi_stage_state(s, resp + 4);+ if (seq) { s->have_last = true; s->last_seq = seq; memcpy(s->last_resp, resp, len); s->last_len = len; }+ return len;+}++const char *smi_stage_state_name(uint8_t st) {+ static const char *n[] = { "off", "idle", "homing", "moving", "selftest", "faulted" };+ return st < 6 ? n[st] : "?";+}++const char *smi_stage_fault_name(uint8_t f) {+ static const char *n[] = { "none", "driver", "home_stuck", "home_timeout", "home_unexpected", "link_lost", "drv_status" };+ return f < 7 ? n[f] : "?";+}++static const char *status_text(uint8_t st) {+ switch (st) {+ case SMI_STAGE_OK: return "ok";+ case SMI_STAGE_E_NOT_HOMED: return "not homed: run stage home first";+ case SMI_STAGE_E_LIMIT: return "outside 0..1600 pulses from HOME";+ case SMI_STAGE_E_BUSY: return "busy: stage stop first";+ case SMI_STAGE_E_DRIVER: return "TMC2209 did not configure (UART, CRC, IFCNT or version)";+ case SMI_STAGE_E_FAULT: return "fault latched: stage off, then stage home";+ case SMI_STAGE_E_RATE: return "speed must be 1..640 pulses/s";+ default: return "bad command";+ }+}++void smi_stage_text(smi_stage_t *s, const char *c, uint32_t now, char *r, size_t nr) {+ uint8_t sub = 0xFF; int32_t arg = 0;+ if (!strcmp(c, "stage status")) sub = SMI_STAGE_SUB_STATUS;+ else if (!strcmp(c, "stage home")) sub = SMI_STAGE_SUB_HOME;+ else if (!strcmp(c, "stage stop")) sub = SMI_STAGE_SUB_STOP;+ else if (!strcmp(c, "stage off")) sub = SMI_STAGE_SUB_OFF;+ else if (!strcmp(c, "stage current")) sub = SMI_STAGE_SUB_CURRENT;+ else if (!strcmp(c, "stage selftest")) sub = SMI_STAGE_SUB_SELFTEST;+ else if (!strcmp(c, "stage speed")) sub = SMI_STAGE_SUB_SPEED;+ else if (!strncmp(c, "stage speed ", 12) || !strncmp(c, "stage step ", 11) || !strncmp(c, "stage move ", 11)) {+ const char *a = strchr(c + 6, ' ') + 1;+ char *end;+ long v = strtol(a, &end, 10);+ if (*a && !*end && v > -100000 && v < 100000) {+ arg = (int32_t)v;+ sub = c[6] == 's' && c[7] == 'p' ? SMI_STAGE_SUB_SPEED : c[6] == 's' ? SMI_STAGE_SUB_STEP : SMI_STAGE_SUB_MOVE_TO;+ }+ }+ uint8_t st = sub == 0xFF ? SMI_STAGE_E_SUB : do_cmd(s, sub, arg, now);+ if (st != SMI_STAGE_OK) { snprintf(r, nr, "error: %s: %s", c, status_text(st)); return; }+ if (sub == SMI_STAGE_SUB_CURRENT)+ snprintf(r, nr, "stage current: IRUN=IHOLD=27/31 of 0.469 A rms (0.410 A rms set), driver %s, DRV_STATUS=0x%08lX",+ s->enabled ? "enabled" : "off", (unsigned long)s->drv_status);+ else+ snprintf(r, nr, "stage %s homed=%d pos=%ld target=%ld speed=%u fault=%s home_in=%d steps=%lu",+ smi_stage_state_name(s->state), s->homed, (long)s->pos, (long)s->target, s->rate,+ smi_stage_fault_name(s->fault), s->hal.home_in(s->hal.ctx) ? 1 : 0, (unsigned long)s->steps_total);+}
software/firmware/src/smi_stage.hadded+163@@ -0,0 +1,163 @@+// SPDX-License-Identifier: MIT+// Test-stage control core (board 1.3.1, STAGE connector J4): a TMC2209 stepper+// driver on STEP/DIR/EN_N with its single-wire PDN_UART, and a normally closed+// HOME switch. Portable C99 behind a small hardware interface, so the same file+// runs in the Pico firmware, in the host-side test and in the dashboard's+// simulator.+//+// Contract: the main board's design/control-map.json "stage" entry (pins) and+// test-stage/design/stage-map.json (motion, UART registers, homing, limits,+// self-test). Rules this core enforces:+// - Disabled at boot (EN_N high) and on fault, link loss or "stage off".+// Position becomes invalid whenever the driver is disabled.+// - The driver is configured over UART with EN_N high; every write is checked+// against IFCNT; motion is enabled only if all of it verified.+// - Before homing only the homing search may move the stage. After homing+// every move must stay inside 0..1600 pulses from HOME.+// - Steps are rate limited (default 160, at most 640 pulses/s), with the+// contract's STEP/DIR timing; an unexpected HOME during a normal move+// disables the driver and invalidates the position.+// - Moves carry a sequence number: a retried command returns its cached+// result without issuing new pulses.+#ifndef SMI_STAGE_H+#define SMI_STAGE_H+#include <stdint.h>+#include <stdbool.h>+#include <stddef.h>++// Pico GPIOs (control-map.json stage entry: J4 pins 2 to 6).+#define SMI_STAGE_STEP_GPIO 10+#define SMI_STAGE_DIR_GPIO 11+#define SMI_STAGE_EN_N_GPIO 12+#define SMI_STAGE_UART_GPIO 13+#define SMI_STAGE_HOME_GPIO 14++// stage-map.json motion, homing and self-test.+#define SMI_STAGE_TRAVEL_MAX 1600 // pulses from HOME+#define SMI_STAGE_NM_PER_PULSE 15.625f // nominal; calibrate on the bench+#define SMI_STAGE_RATE_DEFAULT 160 // pulses/s+#define SMI_STAGE_RATE_MAX 640+#define SMI_STAGE_RATE_HOME 80+#define SMI_STAGE_RATE_HOME_SLOW 32+#define SMI_STAGE_HOME_VERIFY_US 5000+#define SMI_STAGE_HOME_BACKOFF 32+#define SMI_STAGE_HOME_MAX_SEARCH 1920+#define SMI_STAGE_HOME_MAX_RELEASE 128+#define SMI_STAGE_STEP_HIGH_US 3 // contract minimum 2 us high and low+#define SMI_STAGE_DIR_SETUP_US 3 // contract minimum 2 us setup and hold+#define SMI_STAGE_SELFTEST_ORIGIN 128+#define SMI_STAGE_SELFTEST_RUNGS 8+#define SMI_STAGE_SELFTEST_DWELL_US 1000000u+// A normal move may see HOME high only this close to zero (the switch opens at 0).+#define SMI_STAGE_HOME_ZONE 4++// TMC2209 (stage-map.json uart.registers).+#define SMI_TMC_ADDR 0+#define SMI_TMC_GCONF 0x00+#define SMI_TMC_GSTAT 0x01+#define SMI_TMC_IFCNT 0x02+#define SMI_TMC_SLAVECONF 0x03+#define SMI_TMC_IOIN 0x06+#define SMI_TMC_IHOLD_IRUN 0x10+#define SMI_TMC_VACTUAL 0x22+#define SMI_TMC_CHOPCONF 0x6C+#define SMI_TMC_DRV_STATUS 0x6F+#define SMI_TMC_GCONF_VAL 0x000000C0u+#define SMI_TMC_SLAVECONF_VAL 0x00000200u+#define SMI_TMC_IHOLD_IRUN_VAL 0x00001B1Bu+#define SMI_TMC_CHOPCONF_VAL 0x040101C3u+#define SMI_TMC_VERSION 0x21++// Pushed by the firmware: SMI_T_STAGE frame = state block (24 bytes) + u64 ADC pair+// index at the time of sending, every 50 ms while the driver is enabled, else every 500 ms.+#define SMI_T_STAGE 0x13++// Binary command (on the existing CMD/ACK channel): op SMI_OP_STAGE, u8 sub, i32 arg.+#define SMI_OP_STAGE 0x09+enum {+ SMI_STAGE_SUB_STATUS = 0,+ SMI_STAGE_SUB_HOME = 1, // configure the driver, enable and home+ SMI_STAGE_SUB_STEP = 2, // arg: signed pulse count, relative+ SMI_STAGE_SUB_SPEED = 3, // arg: pulses/s (0 = report only)+ SMI_STAGE_SUB_STOP = 4, // stop motion, stay enabled, keep position+ SMI_STAGE_SUB_OFF = 5, // disable the driver; position becomes invalid+ SMI_STAGE_SUB_CURRENT = 6, // read DRV_STATUS and report the current set point+ SMI_STAGE_SUB_SELFTEST = 7, // origin 128, +128 x4, -128 x4, 1 s dwells+ SMI_STAGE_SUB_MOVE_TO = 8, // arg: absolute pulse position (homed only)+};+enum {+ SMI_STAGE_OK = 0,+ SMI_STAGE_E_LEN = 1,+ SMI_STAGE_E_SUB = 2,+ SMI_STAGE_E_NOT_HOMED = 11, // only homing may move an unhomed stage+ SMI_STAGE_E_LIMIT = 12, // outside 0..1600 pulses+ SMI_STAGE_E_BUSY = 13, // a home, move or self-test is running+ SMI_STAGE_E_DRIVER = 14, // TMC2209 did not answer, CRC or IFCNT mismatch, wrong version+ SMI_STAGE_E_FAULT = 15, // a fault is latched: stage off, then home again+ SMI_STAGE_E_RATE = 16, // speed outside 1..640 pulses/s+};+enum { SMI_STAGE_OFF = 0, SMI_STAGE_IDLE = 1, SMI_STAGE_HOMING = 2, SMI_STAGE_MOVING = 3, SMI_STAGE_SELFTEST = 4, SMI_STAGE_FAULTED = 5 };+enum {+ SMI_STAGE_FAULT_NONE = 0,+ SMI_STAGE_FAULT_DRIVER = 1, // configuration or status read failed+ SMI_STAGE_FAULT_HOME_STUCK = 2, // HOME stayed high through the release search+ SMI_STAGE_FAULT_HOME_TIMEOUT = 3, // no HOME edge within the search limit+ SMI_STAGE_FAULT_HOME_UNEXPECTED = 4, // HOME went high during a normal move+ SMI_STAGE_FAULT_LINK = 5, // host link lost while enabled+ SMI_STAGE_FAULT_DRV_STATUS = 6, // over-temperature, short or open load reported+};+#define SMI_STAGE_FLAG_ENABLED 0x01+#define SMI_STAGE_FLAG_HOMED 0x02+#define SMI_STAGE_FLAG_HOME_IN 0x04 // HOME input high now+#define SMI_STAGE_FLAG_MOVING 0x08++typedef struct {+ void *ctx;+ void (*put)(void *ctx, uint8_t gpio, bool level); // STEP, DIR, EN_N+ bool (*home_in)(void *ctx); // HOME level, true = high+ void (*wait_us)(void *ctx, uint32_t us);+ // One half-duplex UART exchange: send ntx bytes, then (nrx > 0) receive+ // exactly nrx bytes. Return false on timeout.+ bool (*uart)(void *ctx, const uint8_t *tx, size_t ntx, uint8_t *rx, size_t nrx);+} smi_stage_hal_t;++typedef struct {+ smi_stage_hal_t hal;+ uint8_t state, fault, home_phase;+ bool enabled, homed, dir_pos;+ int32_t pos; // pulses from HOME (valid when homed)+ int32_t target; // move target+ int32_t phase_count; // pulses issued in the current homing phase+ uint16_t rate, move_rate;+ uint32_t next_us, high_since_us, dwell_until_us, last_step_us;+ bool high_seen;+ uint8_t st_index; // self-test rung (0 = going to the origin)+ uint32_t steps_total;+ uint8_t ifcnt;+ uint32_t drv_status, ioin;+ uint32_t last_poll_us;+ // duplicate suppression+ bool have_last;+ uint16_t last_seq;+ uint8_t last_resp[40];+ size_t last_len;+} smi_stage_t;++void smi_stage_init(smi_stage_t *s, const smi_stage_hal_t *hal);+// Call often (every 100 us or faster): issues due pulses and runs homing and+// the self-test.+void smi_stage_tick(smi_stage_t *s, uint32_t now_us);+// Binary command: p = sub, i32 arg. Writes an ACK body (u16 seq, u8 op, u8 status,+// then the state block) to resp and returns its length.+size_t smi_stage_command(smi_stage_t *s, const uint8_t *p, size_t n, uint16_t seq, uint32_t now_us, uint8_t *resp);+// State block (24 bytes): u8 state, u8 flags, u8 fault, u8 home_phase, i32 pos,+// i32 target, u16 rate, u8 st_index, u8 ifcnt, u32 steps_total, u32 drv_status.+size_t smi_stage_state(const smi_stage_t *s, uint8_t *out);+void smi_stage_link_lost(smi_stage_t *s);+// Text command ("stage ..."); writes a one-line reply.+void smi_stage_text(smi_stage_t *s, const char *cmd, uint32_t now_us, char *reply, size_t nreply);+// TMC2209 datagram CRC-8 (polynomial 0x07, LSB first), exported for tests.+uint8_t smi_tmc_crc(const uint8_t *d, size_t n);+const char *smi_stage_state_name(uint8_t st);+const char *smi_stage_fault_name(uint8_t f);+#endif
software/firmware/src/smi_text.c+1@@ -60,6 +60,7 @@ void smi_text_command(smi_text_t *x, const char *c) { const smi_control_def_t *defs = ctl->defs; for (int i = 0; i < ctl->n; i++) if (defs[i].is_laser) li = i;+ if (!strncmp(c, "stage ", 6)) { if (x->stage) x->stage(x->ctx, c); return; } 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); }
software/firmware/src/smi_text.h+2−1@@ -2,7 +2,7 @@ // 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,+// and "hb MS"; "stage ..." lines go to the stage core when the firmware wires it. 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).@@ -18,6 +18,7 @@ typedef struct { void (*start)(void *ctx); void (*stop)(void *ctx); void (*info)(void *ctx);+ void (*stage)(void *ctx, const char *line); // "stage ..." commands (smi_stage.c); NULL = absent 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
software/firmware/test/ctl_pty.c+54−6@@ -3,8 +3,10 @@ // 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+// current reading that follows the DAC like the head's ADS1115 would. The+// stage core (smi_stage.c) runs against a mock TMC2209 and screw with a HOME+// switch, answers op 0x09 and "stage ..." lines, and sends STAGE frames.+// cc -O2 -I../src ctl_pty.c ../src/smi_ctl.c ../src/smi_text.c ../src/smi_frame.c ../src/smi_stage.c -lm -o ctl_pty // ./ctl_pty SECONDS (prints the pty path, then serves it) #define _XOPEN_SOURCE 600 #define _DEFAULT_SOURCE@@ -20,6 +22,30 @@ #include "smi_ctl.h" #include "smi_controls_gen.h" #include "smi_text.h"+#include "smi_stage.h"++// Mock stage: screw position in pulses (HOME opens at <= 0), TMC2209 registers.+static long mech = 700;+static bool st_step, st_dir = true, st_en_n = true;+static uint32_t tmc[128];+static uint8_t tmc_if;+static void s_put(void *c, uint8_t g, bool v) {+ (void)c;+ if (g == SMI_STAGE_STEP_GPIO) { if (v && !st_step && !st_en_n) mech += st_dir ? 1 : -1; st_step = v; }+ else if (g == SMI_STAGE_DIR_GPIO) st_dir = v;+ else if (g == SMI_STAGE_EN_N_GPIO) st_en_n = v;+}+static bool s_home(void *c) { (void)c; return mech <= 0; }+static bool s_uart(void *c, const uint8_t *tx, size_t ntx, uint8_t *rx, size_t nrx) {+ (void)c;+ if (ntx < 4 || tx[ntx - 1] != smi_tmc_crc(tx, ntx - 1)) return false;+ uint8_t reg = tx[2] & 0x7F;+ if (ntx == 8) { uint32_t v = ((uint32_t)tx[3] << 24) | ((uint32_t)tx[4] << 16) | ((uint32_t)tx[5] << 8) | tx[6]; if (reg == 1) tmc[1] &= ~v; else tmc[reg] = v; tmc_if++; return nrx == 0; }+ uint32_t v = reg == 2 ? tmc_if : reg == 6 ? (0x21u << 24) : tmc[reg];+ rx[0] = 5; rx[1] = 0xFF; rx[2] = reg; rx[3] = (uint8_t)(v >> 24); rx[4] = (uint8_t)(v >> 16); rx[5] = (uint8_t)(v >> 8); rx[6] = (uint8_t)v; rx[7] = smi_tmc_crc(rx, 7);+ return true;+}+static smi_stage_t stage; static uint16_t dac[4][8]; static bool gp[64];@@ -33,6 +59,7 @@ 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 text_stage(void *x, const char *c) { (void)x; char r[200]; smi_stage_text(&stage, c, now_us(), r, sizeof r); send(SMI_T_INFO, (const uint8_t *)r, (uint16_t)strlen(r)); } static void send(uint8_t type, const uint8_t *pl, uint16_t n) { uint8_t f[256]; memcpy(f + SMI_HDR_LEN, pl, n);@@ -58,10 +85,15 @@ int main(int argc, char **argv) { 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;+ smi_stage_hal_t sh = { .ctx = NULL, .put = s_put, .home_in = s_home, .wait_us = NULL, .uart = s_uart };+ smi_stage_init(&stage, &sh);+ bool host_watch = false;+ uint32_t last_stage = 0;+ unsigned stage_acks = 0;+ const char *info = "ctl_pty host stand-in; map=" SMI_MAP_VERSION "; stage=J4 GP10-14"; 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 };+ smi_text_t tx = { .ctl = &c, .now_us = text_now, .reply = text_send, .stage = text_stage, .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;@@ -82,7 +114,12 @@ int main(int argc, char **argv) { 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);+ uint16_t cs = (uint16_t)(rx[6] | (rx[7] << 8));+ c.last_host_us = now_us(); // as main.c: any binary command is host activity+ host_watch = true;+ size_t n;+ if (len >= 1 && rx[8] == SMI_OP_STAGE) { n = smi_stage_command(&stage, rx + 8, len, cs, now_us(), r); stage_acks++; }+ else n = smi_ctl_command(&c, rx + 8, len, cs, now_us(), r); send(SMI_T_ACK, r, (uint16_t)n); acks++; }@@ -92,6 +129,16 @@ int main(int argc, char **argv) { } uint32_t t = now_us(); smi_ctl_tick(&c, t);+ smi_stage_tick(&stage, t);+ if (host_watch && stage.enabled && c.hb_timeout_ms && (uint32_t)(t - c.last_host_us) > (uint32_t)c.hb_timeout_ms * 1000u)+ smi_stage_link_lost(&stage);+ if (t - last_stage > (stage.enabled ? 50000u : 500000u)) {+ last_stage = t;+ uint8_t sp[40];+ size_t n = smi_stage_state(&stage, sp);+ memset(sp + n, 0, 8);+ send(SMI_T_STAGE, sp, (uint16_t)(n + 8));+ } 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;@@ -107,8 +154,9 @@ int main(int argc, char **argv) { uint8_t st[200]; send(SMI_T_STATE, st, (uint16_t)smi_ctl_state(&c, t, st)); }- usleep(500);+ usleep(200); }+ fprintf(stderr, "ctl_pty: stage %s pos %ld (screw %ld), fault %s, %u stage commands, %lu pulses; ", smi_stage_state_name(stage.state), (long)stage.pos, mech, smi_stage_fault_name(stage.fault), stage_acks, (unsigned long)stage.steps_total); 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_stage.cadded+228@@ -0,0 +1,228 @@+// SPDX-License-Identifier: MIT+// Host test of the stage core (src/smi_stage.c) against a mock mechanism and a+// mock TMC2209 that checks CRCs, keeps registers and counts IFCNT.+// cc -O2 -Wall -Wextra -I../src test_stage.c ../src/smi_stage.c -o test_stage && ./test_stage+#include "smi_stage.h"+#include <stdio.h>+#include <string.h>+#include <stdlib.h>++static int fails, checks;+#define CHECK(c, ...) do { checks++; if (!(c)) { fails++; printf("FAIL %s:%d ", __FILE__, __LINE__); printf(__VA_ARGS__); printf("\n"); } } while (0)++typedef struct {+ uint32_t now;+ bool step, dir, en_n;+ long mech; // true screw position in pulses; HOME switch opens at mech <= 0+ long home_offset; // shifts the switch (simulates a bumped or broken switch)+ bool home_stuck_high, home_never;+ uint32_t regs[128];+ uint8_t ifcnt;+ bool tmc_dead, tmc_ifcnt_stuck;+ uint8_t version;+ long pulses;+ uint32_t last_pulse_us, min_gap_us;+ bool pulse_while_disabled;+ bool write_while_enabled; // a UART register write with EN_N low+} mock_t;++static void put(void *c, uint8_t g, bool v) {+ mock_t *m = c;+ if (g == SMI_STAGE_STEP_GPIO) {+ if (v && !m->step) {+ if (m->en_n) m->pulse_while_disabled = true;+ m->mech += m->dir ? 1 : -1;+ m->pulses++;+ if (m->last_pulse_us && m->now - m->last_pulse_us < m->min_gap_us) m->min_gap_us = m->now - m->last_pulse_us;+ m->last_pulse_us = m->now;+ }+ m->step = v;+ } else if (g == SMI_STAGE_DIR_GPIO) m->dir = v;+ else if (g == SMI_STAGE_EN_N_GPIO) m->en_n = v;+}+static bool home_in(void *c) {+ mock_t *m = c;+ if (m->home_stuck_high) return true;+ if (m->home_never) return false;+ return m->mech + m->home_offset <= 0;+}+static void wait_us(void *c, uint32_t us) { ((mock_t *)c)->now += us; }+static bool uart(void *c, const uint8_t *tx, size_t ntx, uint8_t *rx, size_t nrx) {+ mock_t *m = c;+ if (m->tmc_dead) return false;+ if (tx[0] != 0x05 || tx[ntx - 1] != smi_tmc_crc(tx, ntx - 1)) return false;+ uint8_t reg = tx[2] & 0x7F;+ if (ntx == 8 && (tx[2] & 0x80)) {+ if (!m->en_n) m->write_while_enabled = true;+ uint32_t v = ((uint32_t)tx[3] << 24) | ((uint32_t)tx[4] << 16) | ((uint32_t)tx[5] << 8) | tx[6];+ if (reg == SMI_TMC_GSTAT) m->regs[reg] &= ~v; else m->regs[reg] = v;+ if (!m->tmc_ifcnt_stuck) m->ifcnt++;+ return nrx == 0;+ }+ if (ntx != 4 || nrx != 8) return false;+ uint32_t v = reg == SMI_TMC_IFCNT ? m->ifcnt : reg == SMI_TMC_IOIN ? ((uint32_t)m->version << 24) | 0x40 : m->regs[reg];+ rx[0] = 0x05; rx[1] = 0xFF; rx[2] = reg;+ rx[3] = (uint8_t)(v >> 24); rx[4] = (uint8_t)(v >> 16); rx[5] = (uint8_t)(v >> 8); rx[6] = (uint8_t)v;+ rx[7] = smi_tmc_crc(rx, 7);+ return true;+}++static mock_t M;+static smi_stage_t S;+static void reset(long mech) {+ memset(&M, 0, sizeof M);+ M.mech = mech; M.version = SMI_TMC_VERSION; M.min_gap_us = 0xFFFFFFFFu; M.regs[SMI_TMC_GSTAT] = 0x1; M.now = 1000;+ smi_stage_hal_t h = { .ctx = &M, .put = put, .home_in = home_in, .wait_us = wait_us, .uart = uart };+ smi_stage_init(&S, &h);+}+static void run(uint32_t us) { // tick every 50 us+ for (uint32_t t = 0; t < us; t += 50) { M.now += 50; smi_stage_tick(&S, M.now); }+}+static uint8_t cmd(uint8_t sub, int32_t arg, uint16_t seq) {+ uint8_t p[6] = { SMI_OP_STAGE, sub, (uint8_t)arg, (uint8_t)(arg >> 8), (uint8_t)(arg >> 16), (uint8_t)(arg >> 24) };+ uint8_t r[40];+ smi_stage_command(&S, p, 6, seq, M.now, r);+ return r[3];+}+static void run_until_idle(uint32_t max_us) {+ for (uint32_t t = 0; t < max_us && (S.state == SMI_STAGE_HOMING || S.state == SMI_STAGE_MOVING || S.state == SMI_STAGE_SELFTEST); t += 50) {+ M.now += 50; smi_stage_tick(&S, M.now);+ }+}++int main(void) {+ // CRC: the datasheet algorithm against a published datagram (read GCONF: 05 00 00 48).+ { uint8_t d[3] = { 0x05, 0x00, 0x00 }; CHECK(smi_tmc_crc(d, 3) == 0x48, "crc of 05 00 00 = %02X", smi_tmc_crc(d, 3)); }++ // Boot: disabled, unhomed, moves refused.+ reset(300);+ CHECK(M.en_n, "EN_N high at boot");+ CHECK(S.state == SMI_STAGE_OFF && !S.homed, "off at boot");+ CHECK(cmd(SMI_STAGE_SUB_STEP, 10, 1) == SMI_STAGE_E_NOT_HOMED, "step before home refused");+ CHECK(cmd(SMI_STAGE_SUB_SELFTEST, 0, 2) == SMI_STAGE_E_NOT_HOMED, "selftest before home refused");+ CHECK(M.pulses == 0, "no pulses before home");++ // Home from 300 pulses out: configures the driver, finds the opening edge.+ CHECK(cmd(SMI_STAGE_SUB_HOME, 0, 3) == SMI_STAGE_OK, "home accepted");+ CHECK(!M.en_n, "enabled after a verified configuration");+ CHECK(M.regs[SMI_TMC_GCONF] == SMI_TMC_GCONF_VAL && M.regs[SMI_TMC_CHOPCONF] == SMI_TMC_CHOPCONF_VAL &&+ M.regs[SMI_TMC_IHOLD_IRUN] == SMI_TMC_IHOLD_IRUN_VAL && M.regs[SMI_TMC_SLAVECONF] == SMI_TMC_SLAVECONF_VAL, "registers written");+ run_until_idle(20000000);+ CHECK(S.state == SMI_STAGE_IDLE && S.homed && S.pos == 0, "homed: state %s pos %ld", smi_stage_state_name(S.state), (long)S.pos);+ CHECK(M.mech == 0, "zero on the opening edge (mech %ld)", M.mech);+ CHECK(M.min_gap_us >= 1000000u / SMI_STAGE_RATE_HOME - 60, "homing rate at most 80/s (gap %u us)", M.min_gap_us);+ CHECK(!M.pulse_while_disabled, "no pulses while disabled");+ CHECK(!M.write_while_enabled, "every configuration write made with EN_N high");++ // Moves: limits, rate, arrival.+ CHECK(cmd(SMI_STAGE_SUB_STEP, -1, 4) == SMI_STAGE_E_LIMIT, "below 0 refused");+ CHECK(cmd(SMI_STAGE_SUB_STEP, 1601, 5) == SMI_STAGE_E_LIMIT, "beyond 1600 refused");+ CHECK(cmd(SMI_STAGE_SUB_SPEED, 641, 6) == SMI_STAGE_E_RATE, "speed above 640 refused");+ CHECK(cmd(SMI_STAGE_SUB_SPEED, 0, 7) == SMI_STAGE_OK && S.rate == 160, "default speed 160");+ M.min_gap_us = 0xFFFFFFFFu; M.last_pulse_us = 0;+ CHECK(cmd(SMI_STAGE_SUB_STEP, 200, 8) == SMI_STAGE_OK, "step 200");+ CHECK(cmd(SMI_STAGE_SUB_STEP, 5, 9) == SMI_STAGE_E_BUSY, "busy while moving");+ run_until_idle(5000000);+ CHECK(S.pos == 200 && M.mech == 200, "arrived at 200 (pos %ld mech %ld)", (long)S.pos, M.mech);+ CHECK(M.min_gap_us >= 1000000u / 160 - 60, "rate 160/s (gap %u us)", M.min_gap_us);+ CHECK(cmd(SMI_STAGE_SUB_SPEED, 640, 10) == SMI_STAGE_OK, "speed 640");+ M.min_gap_us = 0xFFFFFFFFu; M.last_pulse_us = 0;+ CHECK(cmd(SMI_STAGE_SUB_STEP, 1400, 11) == SMI_STAGE_OK, "step to 1600");+ run_until_idle(5000000);+ CHECK(S.pos == 1600, "at the 1600 limit");+ CHECK(M.min_gap_us >= 1000000u / 640 - 60, "rate 640/s (gap %u us)", M.min_gap_us);+ CHECK(cmd(SMI_STAGE_SUB_STEP, 1, 12) == SMI_STAGE_E_LIMIT, "one past the limit refused");++ // Duplicate seq: cached answer, no new pulses.+ long p0 = M.pulses;+ CHECK(cmd(SMI_STAGE_SUB_MOVE_TO, 1000, 13) == SMI_STAGE_OK, "move to 1000");+ run_until_idle(5000000);+ long p1 = M.pulses;+ CHECK(cmd(SMI_STAGE_SUB_MOVE_TO, 1000, 13) == SMI_STAGE_OK, "retry answered");+ CHECK(cmd(SMI_STAGE_SUB_STEP, 50, 14) == SMI_STAGE_OK, "step 50");+ run_until_idle(5000000);+ long p2 = M.pulses;+ CHECK(cmd(SMI_STAGE_SUB_STEP, 50, 14) == SMI_STAGE_OK, "retry of step 50 answered");+ run(2000000);+ CHECK(p1 - p0 == 600 && p2 - p1 == 50 && M.pulses == p2 && S.pos == 1050, "retry issued no pulses (pos %ld)", (long)S.pos);++ // Stop mid-move keeps a valid position.+ cmd(SMI_STAGE_SUB_SPEED, 160, 15);+ cmd(SMI_STAGE_SUB_STEP, -500, 16);+ run(500000);+ CHECK(cmd(SMI_STAGE_SUB_STOP, 0, 17) == SMI_STAGE_OK && S.state == SMI_STAGE_IDLE && S.homed, "stop keeps homed");+ CHECK(S.pos == M.mech, "position tracks the mechanism after stop (%ld vs %ld)", (long)S.pos, M.mech);++ // Self-test: origin 128, +128 x4, -128 x4, 1 s dwells.+ long visits[12]; int nv = 0; uint32_t t0 = M.now;+ CHECK(cmd(SMI_STAGE_SUB_SELFTEST, 0, 18) == SMI_STAGE_OK, "selftest");+ int32_t lastpos = S.pos; uint32_t still_since = M.now;+ while (S.state == SMI_STAGE_SELFTEST && M.now - t0 < 60000000u) {+ M.now += 50; smi_stage_tick(&S, M.now);+ if (S.pos != lastpos) { lastpos = S.pos; still_since = M.now; }+ else if (M.now - still_since == 900000u && nv < 12) visits[nv++] = S.pos;+ }+ long want[] = { 128, 256, 384, 512, 640, 512, 384, 256, 128 };+ CHECK(nv == 9, "selftest plateaus: %d", nv);+ for (int i = 0; i < nv && i < 9; i++) CHECK(visits[i] == want[i], "plateau %d at %ld (want %ld)", i, visits[i], want[i]);+ CHECK(S.state == SMI_STAGE_IDLE && S.pos == 128, "selftest ends idle at 128");++ // Unexpected HOME during a normal move: disable and invalidate.+ M.home_offset = -400; // switch now reads high anywhere below 400+ cmd(SMI_STAGE_SUB_MOVE_TO, 1000, 19); run_until_idle(10000000);+ M.home_offset = -2000;+ cmd(SMI_STAGE_SUB_STEP, -10, 20); run_until_idle(1000000);+ CHECK(S.state == SMI_STAGE_FAULTED && S.fault == SMI_STAGE_FAULT_HOME_UNEXPECTED && M.en_n && !S.homed, "unexpected HOME faults (state %s)", smi_stage_state_name(S.state));+ CHECK(cmd(SMI_STAGE_SUB_HOME, 0, 21) == SMI_STAGE_E_FAULT, "home refused while faulted");+ CHECK(cmd(SMI_STAGE_SUB_OFF, 0, 22) == SMI_STAGE_OK && S.state == SMI_STAGE_OFF && S.fault == 0, "stage off clears the fault");++ // Homing starting on the switch: release search first.+ reset(-20);+ CHECK(cmd(SMI_STAGE_SUB_HOME, 0, 1) == SMI_STAGE_OK, "home from on the switch");+ run_until_idle(20000000);+ CHECK(S.homed && M.mech == 0, "homed after release (mech %ld)", M.mech);++ // Stuck HOME: release search fails after 128 pulses.+ reset(500); M.home_stuck_high = true;+ cmd(SMI_STAGE_SUB_HOME, 0, 1); run_until_idle(20000000);+ CHECK(S.fault == SMI_STAGE_FAULT_HOME_STUCK && M.en_n && M.pulses <= SMI_STAGE_HOME_MAX_RELEASE, "stuck HOME faults after %ld pulses", M.pulses);++ // Disconnected switch reads high: same as stuck. Missing switch edge: timeout.+ reset(500); M.home_never = true;+ cmd(SMI_STAGE_SUB_HOME, 0, 1); run_until_idle(60000000);+ CHECK(S.fault == SMI_STAGE_FAULT_HOME_TIMEOUT && M.pulses <= SMI_STAGE_HOME_MAX_SEARCH, "search timeout after %ld pulses", M.pulses);++ // Driver configuration failures leave the stage disabled.+ reset(300); M.version = 0x20;+ CHECK(cmd(SMI_STAGE_SUB_HOME, 0, 1) == SMI_STAGE_E_DRIVER && M.en_n && M.pulses == 0, "wrong driver version refused");+ reset(300); M.tmc_dead = true;+ CHECK(cmd(SMI_STAGE_SUB_HOME, 0, 1) == SMI_STAGE_E_DRIVER && M.en_n, "silent driver refused");+ reset(300); M.tmc_ifcnt_stuck = true;+ CHECK(cmd(SMI_STAGE_SUB_HOME, 0, 1) == SMI_STAGE_E_DRIVER && M.en_n, "IFCNT not counting refused");++ // DRV_STATUS fault while holding, and link loss.+ reset(100); cmd(SMI_STAGE_SUB_HOME, 0, 1); run_until_idle(20000000);+ M.regs[SMI_TMC_DRV_STATUS] = 0x2; // ot+ run(600000);+ CHECK(S.fault == SMI_STAGE_FAULT_DRV_STATUS && M.en_n, "over-temperature disables");+ reset(100); cmd(SMI_STAGE_SUB_HOME, 0, 1); run_until_idle(20000000);+ smi_stage_link_lost(&S);+ CHECK(S.fault == SMI_STAGE_FAULT_LINK && M.en_n && !S.homed, "link loss disables and invalidates");++ // Text commands.+ reset(100);+ char r[200];+ smi_stage_text(&S, "stage step 10", M.now, r, sizeof r);+ CHECK(strstr(r, "not homed") != NULL, "text: %s", r);+ smi_stage_text(&S, "stage home", M.now, r, sizeof r); run_until_idle(20000000);+ smi_stage_text(&S, "stage step 64", M.now, r, sizeof r); run_until_idle(2000000);+ smi_stage_text(&S, "stage status", M.now, r, sizeof r);+ CHECK(strstr(r, "pos=64") != NULL && strstr(r, "homed=1") != NULL, "text status: %s", r);+ smi_stage_text(&S, "stage speed 999", M.now, r, sizeof r);+ CHECK(strstr(r, "1..640") != NULL, "text speed: %s", r);+ smi_stage_text(&S, "stage current", M.now, r, sizeof r);+ CHECK(strstr(r, "0.410 A") != NULL, "text current: %s", r);++ printf("%d checks, %d failed\n", checks, fails);+ return fails ? 1 : 0;+}
software/firmware/test/text_cmd_test.py+35@@ -108,5 +108,40 @@ check(not state()["on"], "over-long line disarms") cmd("laser 3000", 0.6) cmd("laser off") check(not state()["on"], "laser off")++# Stage (firmware 1.3.1, the stage map's text commands), if the stand-in has one.+def stage_reply(line, wait=0.3):+ os.write(fd, (line + "\n").encode())+ return [p.decode() for t, p in frames(wait) if t == 4 and p.decode().startswith(("stage", "error"))]+++def stage_frame(wait=0.6):+ st = [p for t, p in frames(wait) if t == 0x13]+ return st[-1] if st else None+++r = stage_reply("stage status")+if any(x.startswith("stage ") for x in r):+ check(any("stage off homed=0" in x for x in r), f"stage disabled at boot: {r}")+ check(any("not homed" in x for x in stage_reply("stage step 10")), "stage step refused before homing")+ check(any("speed must be" in x for x in stage_reply("stage speed 700")), "stage speed 700 refused")+ stage_reply("stage home", 0.1)+ t = time.time()+ while time.time() - t < 30:+ f = stage_frame(0.3)+ if f and f[0] == 1 and f[1] & 2:+ break+ check(f is not None and f[0] == 1 and f[1] & 2 and struct.unpack_from("<i", f, 4)[0] == 0, "stage home: idle, homed, position 0 (STAGE frame)")+ check(f is not None and len(f) == 32, "STAGE frame is the 24-byte state block plus the u64 pair index")+ check(any("outside" in x for x in stage_reply("stage move 1601")), "stage move 1601 refused")+ stage_reply("stage speed 640")+ stage_reply("stage step 200", 0.8)+ f = stage_frame(0.3)+ check(f is not None and struct.unpack_from("<i", f, 4)[0] == 200, "stage step 200 at 640 pulses/s arrives in 0.8 s")+ r = stage_reply("stage current")+ check(any("IRUN=IHOLD=27/31" in x for x in r), f"stage current: {r}")+ stage_reply("stage off")+ f = stage_frame(0.7)+ check(f is not None and f[0] == 0 and not f[1] & 3, "stage off: disabled, position invalid") print(f"{'OK' if not fails else 'FAIL'}: {checks} text-command checks, {fails} failed") sys.exit(1 if fails else 0)
software/screenshots/controls-tuned.png⋯ 1 unchanged line ⋯
software/screenshots/stage-calibrate.pngadded⋯ 1 unchanged line ⋯
software/screenshots/stage-selftest.pngadded⋯ 1 unchanged line ⋯
software/screenshots/stage-step.pngadded⋯ 1 unchanged line ⋯