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/: Pico firmware (500 ksps two-channel ADC over DMA, SYNC on GPIO15, framed delta-packed USB stream), smi-dash dashboard with simulator, fringe detector and CLI, built .uf2 and binaries, sub-readme with screenshots and the detector's error table
36 files changed
+6925
software/README.md+148software/dashboard/Cargo.lock+1988software/dashboard/Cargo.toml+35software/dashboard/README.md+51software/dashboard/SKILL.md+44software/dashboard/assets/icon.svg+1software/dashboard/assets/index.html+552software/dashboard/src/dsp.rs+262software/dashboard/src/engine.rs+599software/dashboard/src/eval.rs+134software/dashboard/src/main.rs+636software/dashboard/src/proto.rs+235software/dashboard/src/record.rs+243software/dashboard/src/server.rs+448software/dashboard/src/sim.rs+557software/dashboard/src/util.rs+150software/dist/SHA256SUMS+3software/dist/smi-dash-linux-x64software/dist/smi-dash-windows-x64.exesoftware/dist/smi_pico.uf2software/firmware/CMakeLists.txt+27software/firmware/README.md+63software/firmware/pico_sdk_import.cmake+121software/firmware/src/main.c+281software/firmware/src/smi_frame.c+94software/firmware/src/smi_frame.h+59software/firmware/src/tusb_config.h+16software/firmware/src/usb_descriptors.c+71software/firmware/test/stream_gen.c+38software/firmware/test/test_pack.c+69software/firmware/test/vectors.binsoftware/screenshots/dashboard-constant-speed.pngsoftware/screenshots/direction-reversal.pngsoftware/screenshots/multimode-fading.pngsoftware/screenshots/settings.pngsoftware/screenshots/sine-return-to-zero.pngsoftware/README.mdadded+148@@ -0,0 +1,148 @@+# Software: Pico firmware and the SMI dashboard++Firmware for the Raspberry Pi Pico that plugs into this board, and a dashboard that shows both photodiode channels live, finds every fringe, reads its lean for direction and keeps a running position in nanometres. With no hardware attached the dashboard runs a physical simulator of the laser, the optics and this board's analog chain, so everything here can be tried today.++++| 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. |+| [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`. |++## Quick start++1. Flash the Pico: hold BOOTSEL, plug it into USB, and copy `dist/smi_pico.uf2` onto the `RPI-RP2` drive that appears. It reboots into the digitizer.+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**.++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.++## What the numbers are++| Quantity | Value | Where it comes from |+|---|---|---|+| Laser wavelength | 658 nm (HL6501MG) | One fringe is half a wavelength of target travel: 329 nm |+| Sampling | 500 ksps total, 250 ksps per channel | RP2040 ADC free-running at 48 MHz / 96, round robin over ADC0 and ADC1; channel 2 is sampled 2 us after channel 1 |+| Channel 1 | ADC0, pin 31 | Monitor photodiode, TIA, offset, gain, anti-alias filter |+| Channel 2 | ADC1, pin 32 | External photodiode, same chain |+| SYNC | GPIO15, pin 20 | SN74LVC1G17 Schmitt buffer, non-inverting, 100 k pull-down at its input |+| Anti-alias filter | 40.8 kHz pole plus a 44.4 kHz Sallen-Key (Q 0.98) | `design/calcs.json` |+| Multimode beat | 1.46 mm | Breaking Taps' first laser; the simulator reproduces it with two longitudinal modes |++## The dashboard++Both channels scroll live. Detected fringes are marked along the top of channel 1, teal pointing up for motion away from the laser and purple pointing down for motion towards it; SYNC edges from the motion stage are dashed lines. Below them are the running displacement (with the simulator's ground truth dashed when simulating), a spectrum of both channels, and the readouts. Scroll a channel plot to zoom from 0.1 ms to 2 s; freeze the display and drag to look back.++When the target reverses, the sawtooth's lean flips and so do the markers. This capture caught a reversal and its SYNC pulse in a 50 ms window:++++A sinusoidal move: the count follows the target out and back through zero.++++The problem a single-mode laser fixes. With a second longitudinal mode the fringe envelope fades every 1.46 mm of travel, fringes are lost in the fades, and the counted position (solid) walks away from the truth (dashed):++++Settings live on the server, so the page, the CLI and an AI see the same values:++++### Recording++The record button (or `smi-dash record start --format csv --seconds 10`) saves both channels, SYNC, the fringes and the running displacement.++- **CSV** streams to disk: `pair,t_s,ch1,ch2,ch1_v,ch2_v,sync,fringe,disp_nm,truth_nm`, with a commented header giving the source, rates and detector settings.+- **HDF5** (Linux build) keeps up to 120 s in memory and writes on stop: datasets `ch1`, `ch2`, `disp_nm`, `truth_nm`, groups `fringes/{pair,dir}` and `sync/{pair,level}`, and attributes for the sample rate, the 2 us channel offset, the LSB in volts and the wavelength.++### CLI++Every verb prints `OK:` or `ERROR:` first and a `Hint:` with the next command; `--json` returns `{status, data, hints}`. The CLI calls the same HTTP endpoints as the page, so anything the page can do, a script or an AI can do.++```+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 detect --lp-hz 10000 --threshold 0.35 --invert on|off+smi-dash view --window-ms 20 --history-s 6 --pause | --resume+smi-dash zero+smi-dash record start --format csv|h5 --seconds 10 | record stop | record status+smi-dash ui toast "text" | ui click '#btn-zero' | ui reveal '#s-fps'+smi-dash settings get | settings set fps=30 record_format=h5+smi-dash eval --suite+```++## Fringe detection, and how well it works++The detector is classical DSP on channel 1:++1. Low-pass, 2nd-order Butterworth, 10 kHz by default (the Detector LP slider).+2. Envelope: a decaying running maximum and minimum give the fringe's peak-to-peak.+3. Edge detection: the difference `y[n] - y[n-D]`, with `D` matched to the filter's rise time. A run above `threshold x peak-to-peak` is an edge candidate.+4. Direction: the sawtooth's sharp edge always runs against its ramp. At higher fringe rates the ramp itself crosses the threshold, with the opposite sign and a smaller size, so candidates are weighed by size squared and only those that agree with the running sign are counted. Each counted edge is one fringe, plus or minus 329 nm.++`smi-dash eval --suite` runs the simulator and the detector together, 1.5 s per case, and compares the count with the simulator's ground truth. These are the results of that command for this release, not estimates:++| Case | C | Motion | LP | True fringes | Detected | Direction errors | Final error | RMS error | Max error |+|---|---|---|---|---|---|---|---|---|---|+| constant 1 mm/s | 3 | 1000 um/s | 10 kHz | 4557 | 4556 | 0 | 12 nm | 380 nm | 644 nm |+| constant 5 mm/s, 10 kHz LP | 3 | 5000 um/s | 10 kHz | 22797 | 16892 | 7303 | -671100 nm | 1164355 nm | 1977628 nm |+| constant 5 mm/s, 60 kHz LP | 3 | 5000 um/s | 60 kHz | 22797 | 22787 | 0 | -2243 nm | 2247 nm | 2665 nm |+| constant 10 mm/s, 60 kHz LP | 3 | 10000 um/s | 60 kHz | 45593 | 55558 | 23732 | 986462 nm | 1303766 nm | 2853106 nm |+| sine 5 um, 2 Hz | 3 | 5 um at 2 Hz | 10 kHz | 185 | 180 | 0 | 0 nm | 123 nm | 256 nm |+| sine 50 um, 5 Hz | 3 | 50 um at 5 Hz | 10 kHz | 4544 | 4550 | 0 | -2638 nm | 1951 nm | 3308 nm |+| step 10 um and return | 3 | 10 um steps | 10 kHz | 60 | 60 | 0 | 0 nm | 99 nm | 251 nm |+| hand jitter | 3 | 1.5 um wander | 10 kHz | 188 | 43 | 0 | -21 nm | 115 nm | 255 nm |+| very weak feedback C 0.1 | 0.1 | 1000 um/s | 10 kHz | 4557 | 4560 | 1 | -646 nm | 414 nm | 871 nm |+| weak feedback C 0.5 | 0.5 | 1000 um/s | 10 kHz | 4557 | 4559 | 0 | -317 nm | 346 nm | 562 nm |+| C 1.2 | 1.2 | 1000 um/s | 10 kHz | 4557 | 4559 | 0 | -317 nm | 349 nm | 566 nm |+| C 6 | 6 | 1000 um/s | 10 kHz | 4557 | 4509 | 0 | -12819 nm | 9089 nm | 13958 nm |+| noise x10 | 3 | 1000 um/s | 10 kHz | 4557 | 4556 | 0 | 12 nm | 379 nm | 645 nm |+| single mode, 2 mm/s over 3 mm | 3 | 2000 um/s | 10 kHz | 9118 | 9116 | 0 | -828 nm | 885 nm | 1044 nm |+| multimode, 2 mm/s over 3 mm | 3 | 2000 um/s | 10 kHz | 9118 | 14756 | 3921 | -725286 nm | 399648 nm | 725501 nm |++How to read it:++- **Resolution is one fringe.** Counting resolves 329 nm, so an RMS error of a few hundred nanometres is the expected quantisation, not drift. Where the motion is within the limits below, the error does not grow with travel (12 nm after 4557 fringes at 1 mm/s).+- **Speed limit.** Keep the fringe rate below about two thirds of the detector's low-pass corner. At the default 10 kHz that is about 2 mm/s (6 kHz fringes). Raising the corner to 60 kHz carries 5 mm/s with 7 fringes lost in 22,797. At 10 mm/s (30 kHz fringes, about 8 samples per fringe) this detector fails; the board's anti-alias filter passes those fringes, so a faster detector is possible but not built.+- **Feedback.** It counts from C 0.1 to about 1.2 in the simulator because the residual asymmetry of the fringe still picks the direction; real weak-feedback signals are noisier than this, so aim for the sawtooth (C above 1). Above about C 4.6 the laser can jump more than one fringe at once, and at C 6 it loses about 1 % of fringes.+- **"True fringes" over-counts small oscillations.** It counts every crossing of a half-wavelength boundary, and a tremor across a boundary crosses it many times; the laser's hysteresis rightly ignores those. Judge the hand-jitter and sine rows by the error columns.+- **Multimode** is the failure the video describes: fringes vanish in the fades and the count is wrong by hundreds of micrometres.+- **Start-up.** A fresh detector needs about 15 ms of fringes to learn the envelope and the jump direction. Fringes in that time are not counted (5 fringes in the serial test below).++## 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 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.++## The USB stream++The 16-bit raw stream that dropped packets in the video would need 1 MB/s. This firmware packs each 64-sample block of one channel as its first sample plus 63 zigzag deltas at the smallest bit width that fits, falling back to raw 12-bit when deltas would be wider. On the simulator's realistic signal that is 287 kB/s for both channels together, 4.6 bits per sample with all headers and CRCs, against 750 kB/s for plain 12-bit packing. Frames carry a sync word, type, length, sequence number and CRC-16, and the absolute index of their first sample pair, so a lost frame shows as a counted gap rather than a silent time shift. The format is in [firmware/README.md](software/firmware/README.md).++## What was tested, and what was not++- The firmware builds with Pico SDK 2.1.1 and arm-none-eabi-gcc 13.2 to `smi_pico.uf2` with no warnings.+- The firmware's packer (`firmware/src/smi_frame.c`) round-trips 40,000 blocks exactly in `firmware/test/test_pack.c`, including noise that forces raw blocks, constant blocks and wrapping ramps, and its CRC matches the CRC-16/CCITT-FALSE check value.+- The dashboard's Rust decoder decodes the C packer's reference stream exactly, resynchronises after garbage and drops a corrupted frame with the gap counted (`cargo test`).+- End to end over a serial port: 4 s of simulated samples packed by the firmware's C code and replayed in real time through a pseudo-terminal into `smi-dash source serial` arrived as 797 frames with no CRC errors, gaps or drops at 498 ksps.+- **Not yet run on a physical Pico or board.** No hardware was available. The DMA ring, the SYNC capture timing and the USB throughput on the RP2040 itself are untested; check the STATUS frame's dropped-buffer count (shown in the dashboard's status bar) on first use.++## Building from source++```+# firmware+export PICO_SDK_PATH=/path/to/pico-sdk # 2.1.1, with lib/tinyusb+cmake -S firmware -B firmware/build -DCMAKE_BUILD_TYPE=Release+cmake --build firmware/build # firmware/build/smi_pico.uf2++# dashboard (Linux needs libudev-dev and libhdf5-dev)+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+```++MIT licence, as the rest of this page.
software/dashboard/Cargo.lockadded+1988@@ -0,0 +1,1988 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "aho-corasick"+version = "1.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"+dependencies = [+ "memchr",+]++[[package]]+name = "android_system_properties"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc"+dependencies = [+ "libc",+]++[[package]]+name = "anstream"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"+dependencies = [+ "anstyle",+ "anstyle-parse",+ "anstyle-query",+ "anstyle-wincon",+ "colorchoice",+ "is_terminal_polyfill",+ "utf8parse",+]++[[package]]+name = "anstyle"+version = "1.0.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"++[[package]]+name = "anstyle-parse"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"+dependencies = [+ "utf8parse",+]++[[package]]+name = "anstyle-query"+version = "1.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"+dependencies = [+ "windows-sys 0.61.2",+]++[[package]]+name = "anstyle-wincon"+version = "3.0.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"+dependencies = [+ "anstyle",+ "once_cell_polyfill",+ "windows-sys 0.61.2",+]++[[package]]+name = "ascii"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16"++[[package]]+name = "async-trait"+version = "0.1.92"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.10",+]++[[package]]+name = "atomic-waker"+version = "1.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"++[[package]]+name = "autocfg"+version = "1.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"++[[package]]+name = "axum"+version = "0.7.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "edca88bc138befd0323b20752846e6587272d3b03b0343c8ea28a6f819e6e71f"+dependencies = [+ "async-trait",+ "axum-core",+ "bytes",+ "futures-util",+ "http",+ "http-body",+ "http-body-util",+ "hyper",+ "hyper-util",+ "itoa",+ "matchit",+ "memchr",+ "mime",+ "percent-encoding",+ "pin-project-lite",+ "rustversion",+ "serde",+ "serde_json",+ "serde_path_to_error",+ "serde_urlencoded",+ "sync_wrapper",+ "tokio",+ "tower",+ "tower-layer",+ "tower-service",+ "tracing",+]++[[package]]+name = "axum-core"+version = "0.4.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09f2bd6146b97ae3359fa0cc6d6b376d9539582c7b4220f041a33ec24c226199"+dependencies = [+ "async-trait",+ "bytes",+ "futures-util",+ "http",+ "http-body",+ "http-body-util",+ "mime",+ "pin-project-lite",+ "rustversion",+ "sync_wrapper",+ "tower-layer",+ "tower-service",+ "tracing",+]++[[package]]+name = "base64"+version = "0.22.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"++[[package]]+name = "bitflags"+version = "1.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"++[[package]]+name = "bitflags"+version = "2.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"++[[package]]+name = "bumpalo"+version = "3.20.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db"++[[package]]+name = "bytes"+version = "1.12.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c"++[[package]]+name = "cc"+version = "1.11.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69"+dependencies = [+ "find-msvc-tools",+ "shlex",+]++[[package]]+name = "cfg-if"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"++[[package]]+name = "chrono"+version = "0.4.45"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"+dependencies = [+ "iana-time-zone",+ "num-traits",+ "windows-link",+]++[[package]]+name = "clap"+version = "4.6.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "844c5c0b65be192cb68d570cca1b21a6444431d24e39c084dc0336177015337c"+dependencies = [+ "clap_builder",+ "clap_derive",+]++[[package]]+name = "clap_builder"+version = "4.6.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"+dependencies = [+ "anstream",+ "anstyle",+ "clap_lex",+ "strsim",+]++[[package]]+name = "clap_derive"+version = "4.6.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7"+dependencies = [+ "heck",+ "proc-macro2",+ "quote",+ "syn 3.0.10",+]++[[package]]+name = "clap_lex"+version = "1.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79"++[[package]]+name = "colorchoice"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"++[[package]]+name = "core-foundation"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"+dependencies = [+ "core-foundation-sys",+ "libc",+]++[[package]]+name = "core-foundation-sys"+version = "0.8.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"++[[package]]+name = "displaydoc"+version = "0.2.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.10",+]++[[package]]+name = "equivalent"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"++[[package]]+name = "errno"+version = "0.3.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776"+dependencies = [+ "libc",+ "windows-sys 0.61.2",+]++[[package]]+name = "find-msvc-tools"+version = "0.1.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"++[[package]]+name = "form_urlencoded"+version = "1.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e"+dependencies = [+ "percent-encoding",+]++[[package]]+name = "futures"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3"+dependencies = [+ "futures-channel",+ "futures-core",+ "futures-executor",+ "futures-io",+ "futures-sink",+ "futures-task",+ "futures-util",+]++[[package]]+name = "futures-channel"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4"+dependencies = [+ "futures-core",+ "futures-sink",+]++[[package]]+name = "futures-core"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"++[[package]]+name = "futures-executor"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432"+dependencies = [+ "futures-core",+ "futures-task",+ "futures-util",+]++[[package]]+name = "futures-io"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed"++[[package]]+name = "futures-macro"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.10",+]++[[package]]+name = "futures-sink"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d"++[[package]]+name = "futures-task"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"++[[package]]+name = "futures-util"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"+dependencies = [+ "futures-channel",+ "futures-core",+ "futures-io",+ "futures-macro",+ "futures-sink",+ "futures-task",+ "memchr",+ "pin-project-lite",+ "slab",+]++[[package]]+name = "getrandom"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"+dependencies = [+ "cfg-if",+ "libc",+ "wasi",+]++[[package]]+name = "hashbrown"+version = "0.17.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc"++[[package]]+name = "hdf5-metno"+version = "0.9.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "44c9b4d0d095403ced0b9d8b727c55212f1d09526944d84b8d3dca02ee3c0a82"+dependencies = [+ "bitflags 2.13.2",+ "cfg-if",+ "hdf5-metno-derive",+ "hdf5-metno-sys",+ "hdf5-metno-types",+ "lazy_static",+ "libc",+ "ndarray",+ "paste",+]++[[package]]+name = "hdf5-metno-derive"+version = "0.9.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "205c825c5140aa2791cec795068e8aa8d299862009b7fbd59bd4d876b47842c5"+dependencies = [+ "proc-macro-crate",+ "proc-macro-error2",+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "hdf5-metno-sys"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "de20d5ba22c244493bdfefb91d8e9de08e3e58d96a792532da5e0df545aed279"+dependencies = [+ "libc",+ "libloading",+ "parking_lot",+ "pkg-config",+ "regex",+ "serde",+ "serde_derive",+ "winreg",+]++[[package]]+name = "hdf5-metno-types"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1698f197367c277fac6c3a35ad12397941b57f7554778d925ceb54c3fe754723"+dependencies = [+ "ascii",+ "cfg-if",+ "hdf5-metno-sys",+ "libc",+]++[[package]]+name = "heck"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"++[[package]]+name = "http"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"+dependencies = [+ "bytes",+ "itoa",+]++[[package]]+name = "http-body"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c"+dependencies = [+ "bytes",+ "http",+]++[[package]]+name = "http-body-util"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c"+dependencies = [+ "bytes",+ "futures-core",+ "http",+ "http-body",+ "pin-project-lite",+]++[[package]]+name = "httparse"+version = "1.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"++[[package]]+name = "httpdate"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"++[[package]]+name = "hyper"+version = "1.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c"+dependencies = [+ "atomic-waker",+ "bytes",+ "futures-core",+ "http",+ "http-body",+ "httparse",+ "httpdate",+ "itoa",+ "pin-project-lite",+ "smallvec",+ "tokio",+]++[[package]]+name = "hyper-util"+version = "0.1.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff"+dependencies = [+ "bytes",+ "http",+ "http-body",+ "hyper",+ "pin-project-lite",+ "tokio",+ "tower-service",+]++[[package]]+name = "iana-time-zone"+version = "0.1.65"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"+dependencies = [+ "android_system_properties",+ "core-foundation-sys",+ "iana-time-zone-haiku",+ "js-sys",+ "log",+ "wasm-bindgen",+ "windows-core",+]++[[package]]+name = "iana-time-zone-haiku"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"+dependencies = [+ "cc",+]++[[package]]+name = "icu_collections"+version = "2.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd"+dependencies = [+ "displaydoc",+ "potential_utf",+ "utf8_iter",+ "yoke",+ "zerofrom",+ "zerovec",+]++[[package]]+name = "icu_locale_core"+version = "2.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0"+dependencies = [+ "displaydoc",+ "litemap",+ "tinystr",+ "writeable",+ "zerovec",+]++[[package]]+name = "icu_normalizer"+version = "2.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599"+dependencies = [+ "icu_collections",+ "icu_normalizer_data",+ "icu_properties",+ "icu_provider",+ "smallvec",+ "zerovec",+]++[[package]]+name = "icu_normalizer_data"+version = "2.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc"++[[package]]+name = "icu_properties"+version = "2.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f"+dependencies = [+ "displaydoc",+ "icu_collections",+ "icu_locale_core",+ "icu_properties_data",+ "icu_provider",+ "zerotrie",+ "zerovec",+]++[[package]]+name = "icu_properties_data"+version = "2.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf"++[[package]]+name = "icu_provider"+version = "2.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514"+dependencies = [+ "displaydoc",+ "icu_locale_core",+ "writeable",+ "yoke",+ "zerofrom",+ "zerotrie",+ "zerovec",+]++[[package]]+name = "idna"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"+dependencies = [+ "idna_adapter",+ "smallvec",+ "utf8_iter",+]++[[package]]+name = "idna_adapter"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"+dependencies = [+ "icu_normalizer",+ "icu_properties",+]++[[package]]+name = "indexmap"+version = "2.14.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"+dependencies = [+ "equivalent",+ "hashbrown",+]++[[package]]+name = "io-kit-sys"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "617ee6cf8e3f66f3b4ea67a4058564628cde41901316e19f559e14c7c72c5e7b"+dependencies = [+ "core-foundation-sys",+ "mach2",+]++[[package]]+name = "is_terminal_polyfill"+version = "1.70.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"++[[package]]+name = "itoa"+version = "1.0.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"++[[package]]+name = "js-sys"+version = "0.3.107"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a"+dependencies = [+ "cfg-if",+ "futures-util",+ "wasm-bindgen",+]++[[package]]+name = "lazy_static"+version = "1.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"++[[package]]+name = "libc"+version = "0.2.191"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"++[[package]]+name = "libloading"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"+dependencies = [+ "cfg-if",+ "windows-link",+]++[[package]]+name = "libm"+version = "0.2.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"++[[package]]+name = "libudev"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "78b324152da65df7bb95acfcaab55e3097ceaab02fb19b228a9eb74d55f135e0"+dependencies = [+ "libc",+ "libudev-sys",+]++[[package]]+name = "libudev-sys"+version = "0.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3c8469b4a23b962c1396b9b451dda50ef5b283e8dd309d69033475fa9b334324"+dependencies = [+ "libc",+ "pkg-config",+]++[[package]]+name = "litemap"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"++[[package]]+name = "lock_api"+version = "0.4.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"+dependencies = [+ "scopeguard",+]++[[package]]+name = "log"+version = "0.4.35"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"++[[package]]+name = "mach2"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d640282b302c0bb0a2a8e0233ead9035e3bed871f0b7e81fe4a1ec829765db44"+dependencies = [+ "libc",+]++[[package]]+name = "matchit"+version = "0.7.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94"++[[package]]+name = "matrixmultiply"+version = "0.3.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f607c237553f086e7043417a51df26b2eb899d3caff94e6a67592ff992fedc7"+dependencies = [+ "autocfg",+ "rawpointer",+]++[[package]]+name = "memchr"+version = "2.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"++[[package]]+name = "mime"+version = "0.3.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1"++[[package]]+name = "mio"+version = "1.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a"+dependencies = [+ "libc",+ "wasi",+ "windows-sys 0.61.2",+]++[[package]]+name = "ndarray"+version = "0.16.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "882ed72dce9365842bf196bdeedf5055305f11fc8c03dee7bb0194a6cad34841"+dependencies = [+ "matrixmultiply",+ "num-complex",+ "num-integer",+ "num-traits",+ "portable-atomic",+ "portable-atomic-util",+ "rawpointer",+]++[[package]]+name = "nix"+version = "0.26.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "598beaf3cc6fdd9a5dfb1630c2800c7acd31df7aaf0f565796fba2b53ca1af1b"+dependencies = [+ "bitflags 1.3.2",+ "cfg-if",+ "libc",+]++[[package]]+name = "num-complex"+version = "0.4.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"+dependencies = [+ "num-traits",+]++[[package]]+name = "num-integer"+version = "0.1.47"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"+dependencies = [+ "num-traits",+]++[[package]]+name = "num-traits"+version = "0.2.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"+dependencies = [+ "autocfg",+ "libm",+]++[[package]]+name = "once_cell"+version = "1.21.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"++[[package]]+name = "once_cell_polyfill"+version = "1.70.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"++[[package]]+name = "parking_lot"+version = "0.12.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"+dependencies = [+ "lock_api",+ "parking_lot_core",+]++[[package]]+name = "parking_lot_core"+version = "0.9.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"+dependencies = [+ "cfg-if",+ "libc",+ "redox_syscall",+ "smallvec",+ "windows-link",+]++[[package]]+name = "paste"+version = "1.0.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"++[[package]]+name = "percent-encoding"+version = "2.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"++[[package]]+name = "pin-project-lite"+version = "0.2.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752"++[[package]]+name = "pkg-config"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"++[[package]]+name = "portable-atomic"+version = "1.15.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"++[[package]]+name = "portable-atomic-util"+version = "0.2.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715"+dependencies = [+ "portable-atomic",+]++[[package]]+name = "potential_utf"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661"+dependencies = [+ "zerovec",+]++[[package]]+name = "ppv-lite86"+version = "0.2.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"+dependencies = [+ "zerocopy",+]++[[package]]+name = "primal-check"+version = "0.3.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc0d895b311e3af9902528fbb8f928688abbd95872819320517cc24ca6b2bd08"+dependencies = [+ "num-integer",+]++[[package]]+name = "proc-macro-crate"+version = "3.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"+dependencies = [+ "toml_edit",+]++[[package]]+name = "proc-macro-error-attr2"+version = "2.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5"+dependencies = [+ "proc-macro2",+ "quote",+]++[[package]]+name = "proc-macro-error2"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802"+dependencies = [+ "proc-macro-error-attr2",+ "proc-macro2",+ "quote",+]++[[package]]+name = "proc-macro2"+version = "1.0.107"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "quote"+version = "1.0.47"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"+dependencies = [+ "proc-macro2",+]++[[package]]+name = "rand"+version = "0.8.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c"+dependencies = [+ "libc",+ "rand_chacha",+ "rand_core",+]++[[package]]+name = "rand_chacha"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"+dependencies = [+ "ppv-lite86",+ "rand_core",+]++[[package]]+name = "rand_core"+version = "0.6.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"+dependencies = [+ "getrandom",+]++[[package]]+name = "rand_distr"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32cb0b9bc82b0a0876c2dd994a7e7a2683d3e7390ca40e6886785ef0c7e3ee31"+dependencies = [+ "num-traits",+ "rand",+]++[[package]]+name = "rawpointer"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3"++[[package]]+name = "redox_syscall"+version = "0.5.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"+dependencies = [+ "bitflags 2.13.2",+]++[[package]]+name = "regex"+version = "1.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-automata",+ "regex-syntax",+]++[[package]]+name = "regex-automata"+version = "0.4.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-syntax",+]++[[package]]+name = "regex-syntax"+version = "0.8.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"++[[package]]+name = "rustfft"+version = "6.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "21db5f9893e91f41798c88680037dba611ca6674703c1a18601b01a72c8adb89"+dependencies = [+ "num-complex",+ "num-integer",+ "num-traits",+ "primal-check",+ "strength_reduce",+ "transpose",+]++[[package]]+name = "rustversion"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"++[[package]]+name = "ryu"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"++[[package]]+name = "scopeguard"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"++[[package]]+name = "serde"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"+dependencies = [+ "serde_core",+ "serde_derive",+]++[[package]]+name = "serde_core"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"+dependencies = [+ "serde_derive",+]++[[package]]+name = "serde_derive"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.10",+]++[[package]]+name = "serde_json"+version = "1.0.154"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"+dependencies = [+ "itoa",+ "memchr",+ "serde",+ "serde_core",+ "zmij",+]++[[package]]+name = "serde_path_to_error"+version = "0.1.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457"+dependencies = [+ "itoa",+ "serde",+ "serde_core",+]++[[package]]+name = "serde_urlencoded"+version = "0.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"+dependencies = [+ "form_urlencoded",+ "itoa",+ "ryu",+ "serde",+]++[[package]]+name = "serialport"+version = "4.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ba5f8f29aa20853c4e3e85a33ec580eb66be1f057142e77a333834a318bacf2"+dependencies = [+ "bitflags 2.13.2",+ "cfg-if",+ "core-foundation",+ "core-foundation-sys",+ "io-kit-sys",+ "libudev",+ "mach2",+ "nix",+ "scopeguard",+ "unescaper",+ "windows-sys 0.52.0",+]++[[package]]+name = "shlex"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"++[[package]]+name = "signal-hook-registry"+version = "1.4.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"+dependencies = [+ "errno",+ "libc",+]++[[package]]+name = "slab"+version = "0.4.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"++[[package]]+name = "smallvec"+version = "1.16.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59"++[[package]]+name = "smi-dash"+version = "1.0.0"+dependencies = [+ "axum",+ "chrono",+ "clap",+ "futures",+ "hdf5-metno",+ "rand",+ "rand_distr",+ "rustfft",+ "serde",+ "serde_json",+ "serialport",+ "tokio",+ "tokio-stream",+ "ureq",+]++[[package]]+name = "socket2"+version = "0.6.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"+dependencies = [+ "libc",+ "windows-sys 0.61.2",+]++[[package]]+name = "stable_deref_trait"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"++[[package]]+name = "strength_reduce"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fe895eb47f22e2ddd4dabc02bce419d2e643c8e3b585c78158b349195bc24d82"++[[package]]+name = "strsim"+version = "0.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"++[[package]]+name = "syn"+version = "2.0.119"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "syn"+version = "3.0.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "sync_wrapper"+version = "1.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"++[[package]]+name = "synstructure"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.10",+]++[[package]]+name = "thiserror"+version = "2.0.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"+dependencies = [+ "thiserror-impl",+]++[[package]]+name = "thiserror-impl"+version = "2.0.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.10",+]++[[package]]+name = "tinystr"+version = "0.8.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a"+dependencies = [+ "displaydoc",+ "zerovec",+]++[[package]]+name = "tokio"+version = "1.54.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3"+dependencies = [+ "libc",+ "mio",+ "pin-project-lite",+ "signal-hook-registry",+ "socket2",+ "tokio-macros",+ "windows-sys 0.61.2",+]++[[package]]+name = "tokio-macros"+version = "2.7.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.10",+]++[[package]]+name = "tokio-stream"+version = "0.1.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b"+dependencies = [+ "futures-core",+ "pin-project-lite",+ "tokio",+ "tokio-util",+]++[[package]]+name = "tokio-util"+version = "0.7.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b"+dependencies = [+ "bytes",+ "futures-core",+ "futures-sink",+ "pin-project-lite",+ "tokio",+]++[[package]]+name = "toml_datetime"+version = "1.1.3+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49"+dependencies = [+ "serde_core",+]++[[package]]+name = "toml_edit"+version = "0.25.20+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e76360e201d6dbd6583e17795ba71a88f47365a9139c8450a7979c32303b8e73"+dependencies = [+ "indexmap",+ "toml_datetime",+ "toml_parser",+ "winnow",+]++[[package]]+name = "toml_parser"+version = "1.1.6+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e6769c452d71ba30696c6b37770c439a9cc9110f47f7d5cdbeda79840ef5ea31"+dependencies = [+ "winnow",+]++[[package]]+name = "tower"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"+dependencies = [+ "futures-core",+ "futures-util",+ "pin-project-lite",+ "sync_wrapper",+ "tokio",+ "tower-layer",+ "tower-service",+ "tracing",+]++[[package]]+name = "tower-layer"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"++[[package]]+name = "tower-service"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"++[[package]]+name = "tracing"+version = "0.1.44"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"+dependencies = [+ "log",+ "pin-project-lite",+ "tracing-core",+]++[[package]]+name = "tracing-core"+version = "0.1.36"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"+dependencies = [+ "once_cell",+]++[[package]]+name = "transpose"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1ad61aed86bc3faea4300c7aee358b4c6d0c8d6ccc36524c96e4c92ccf26e77e"+dependencies = [+ "num-integer",+ "strength_reduce",+]++[[package]]+name = "unescaper"+version = "0.1.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7285e83a80ce76f5e7bce79fa41f68d78ba62d1003cf27bf748ab24413808cf4"+dependencies = [+ "thiserror",+]++[[package]]+name = "unicode-ident"+version = "1.0.27"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"++[[package]]+name = "ureq"+version = "2.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "02d1a66277ed75f640d608235660df48c8e3c19f3b4edb6a263315626cc3c01d"+dependencies = [+ "base64",+ "log",+ "once_cell",+ "serde",+ "serde_json",+ "url",+]++[[package]]+name = "url"+version = "2.5.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a"+dependencies = [+ "form_urlencoded",+ "idna",+ "percent-encoding",+ "serde",+]++[[package]]+name = "utf8_iter"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0"+dependencies = [+ "utf_types",+]++[[package]]+name = "utf8parse"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"++[[package]]+name = "utf_types"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6"++[[package]]+name = "wasi"+version = "0.11.1+wasi-snapshot-preview1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"++[[package]]+name = "wasm-bindgen"+version = "0.2.130"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c"+dependencies = [+ "cfg-if",+ "rustversion",+ "wasm-bindgen-macro",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-macro"+version = "0.2.130"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9"+dependencies = [+ "quote",+ "wasm-bindgen-macro-support",+]++[[package]]+name = "wasm-bindgen-macro-support"+version = "0.2.130"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a"+dependencies = [+ "bumpalo",+ "proc-macro2",+ "quote",+ "syn 3.0.10",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-shared"+version = "0.2.130"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "windows-core"+version = "0.62.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"+dependencies = [+ "windows-implement",+ "windows-interface",+ "windows-link",+ "windows-result",+ "windows-strings",+]++[[package]]+name = "windows-implement"+version = "0.60.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "windows-interface"+version = "0.59.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"++[[package]]+name = "windows-result"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-strings"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-sys"+version = "0.48.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"+dependencies = [+ "windows-targets 0.48.5",+]++[[package]]+name = "windows-sys"+version = "0.52.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"+dependencies = [+ "windows-targets 0.52.6",+]++[[package]]+name = "windows-sys"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-targets"+version = "0.48.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c"+dependencies = [+ "windows_aarch64_gnullvm 0.48.5",+ "windows_aarch64_msvc 0.48.5",+ "windows_i686_gnu 0.48.5",+ "windows_i686_msvc 0.48.5",+ "windows_x86_64_gnu 0.48.5",+ "windows_x86_64_gnullvm 0.48.5",+ "windows_x86_64_msvc 0.48.5",+]++[[package]]+name = "windows-targets"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"+dependencies = [+ "windows_aarch64_gnullvm 0.52.6",+ "windows_aarch64_msvc 0.52.6",+ "windows_i686_gnu 0.52.6",+ "windows_i686_gnullvm",+ "windows_i686_msvc 0.52.6",+ "windows_x86_64_gnu 0.52.6",+ "windows_x86_64_gnullvm 0.52.6",+ "windows_x86_64_msvc 0.52.6",+]++[[package]]+name = "windows_aarch64_gnullvm"+version = "0.48.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"++[[package]]+name = "windows_aarch64_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"++[[package]]+name = "windows_aarch64_msvc"+version = "0.48.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"++[[package]]+name = "windows_aarch64_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"++[[package]]+name = "windows_i686_gnu"+version = "0.48.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"++[[package]]+name = "windows_i686_gnu"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"++[[package]]+name = "windows_i686_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"++[[package]]+name = "windows_i686_msvc"+version = "0.48.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"++[[package]]+name = "windows_i686_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"++[[package]]+name = "windows_x86_64_gnu"+version = "0.48.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"++[[package]]+name = "windows_x86_64_gnu"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"++[[package]]+name = "windows_x86_64_gnullvm"+version = "0.48.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"++[[package]]+name = "windows_x86_64_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"++[[package]]+name = "windows_x86_64_msvc"+version = "0.48.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"++[[package]]+name = "windows_x86_64_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"++[[package]]+name = "winnow"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef"+dependencies = [+ "memchr",+]++[[package]]+name = "winreg"+version = "0.52.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a277a57398d4bfa075df44f501a17cfdf8542d224f0d36095a2adc7aee4ef0a5"+dependencies = [+ "cfg-if",+ "serde",+ "windows-sys 0.48.0",+]++[[package]]+name = "writeable"+version = "0.6.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"++[[package]]+name = "yoke"+version = "0.8.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3"+dependencies = [+ "stable_deref_trait",+ "yoke-derive",+ "zerofrom",+]++[[package]]+name = "yoke-derive"+version = "0.8.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.10",+ "synstructure",+]++[[package]]+name = "zerocopy"+version = "0.8.64"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed43f3060383c64b000f3c630550aebdfa9d3b76d48de32390483dd2cc7e0865"+dependencies = [+ "zerocopy-derive",+]++[[package]]+name = "zerocopy-derive"+version = "0.8.64"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a5cbd820fe3e35fb38c83b6dc7e6b1618bc46e0cd10073ae94e8d52dc468d8b9"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "zerofrom"+version = "0.1.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"+dependencies = [+ "zerofrom-derive",+]++[[package]]+name = "zerofrom-derive"+version = "0.1.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.10",+ "synstructure",+]++[[package]]+name = "zerotrie"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f"+dependencies = [+ "displaydoc",+ "yoke",+ "zerofrom",+]++[[package]]+name = "zerovec"+version = "0.11.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40"+dependencies = [+ "yoke",+ "zerofrom",+ "zerovec-derive",+]++[[package]]+name = "zerovec-derive"+version = "0.11.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.10",+]++[[package]]+name = "zmij"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
software/dashboard/Cargo.tomladded+35@@ -0,0 +1,35 @@+[package]+name = "smi-dash"+version = "1.0.0"+edition = "2021"+license = "MIT"+description = "Dashboard, simulator and CLI for a self-mixing laser interferometer read by a Raspberry Pi Pico"++[[bin]]+name = "smi-dash"+path = "src/main.rs"++[features]+default = ["h5"]+h5 = ["dep:hdf5"]++[dependencies]+axum = "0.7"+tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "time", "sync", "signal"] }+tokio-stream = { version = "0.1", features = ["sync"] }+futures = "0.3"+serde = { version = "1", features = ["derive"] }+serde_json = "1"+clap = { version = "4", features = ["derive", "env"] }+serialport = "4"+rustfft = "6"+ureq = { version = "2", default-features = false, features = ["json"] }+rand = { version = "0.8", features = ["small_rng"] }+rand_distr = "0.4"+chrono = { version = "0.4", default-features = false, features = ["clock"] }+hdf5 = { package = "hdf5-metno", version = "0.9", optional = true }++[profile.release]+opt-level = 3+lto = "thin"+codegen-units = 4
software/dashboard/README.mdadded+51@@ -0,0 +1,51 @@+# smi-dash: dashboard, simulator and CLI++One binary. `smi-dash start` runs a small local web server (Rust, axum) that owns all state: the data source (simulator or a Pico over USB serial), the fringe detector, the running displacement, recording and settings. The page in `assets/index.html` is drawn on canvases from a Server-Sent Events stream, and every button calls the same HTTP endpoint a CLI verb calls, so the page, the CLI and an AI always agree.++| File | Role |+|---|---|+| `src/sim.rs` | Lang-Kobayashi self-mixing model, target motions, multimode beat, the board's analog chain and the RP2040 ADC |+| `src/dsp.rs` | Fringe detector (low-pass, envelope, edge detection, direction) and the spectrum |+| `src/proto.rs` | Decoder for the firmware's framed stream, with resync and CRC |+| `src/engine.rs` | Sample rings, displacement history, display frames, acquisition and serial threads |+| `src/record.rs` | CSV (streamed) and HDF5 (written on stop) recording |+| `src/server.rs` | HTTP API, SSE live channel, settings, page console |+| `src/eval.rs` | Offline accuracy suite against the simulator's ground truth |+| `src/main.rs` | CLI |++## Use++```+smi-dash start # background server for this AI thread or user, port reused across restarts+smi-dash show # open it in a Hydrogen webview tab (show --surface pup for the pup browser)+smi-dash status # displacement, velocity, fringe rate, link and recording+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 stop+```++Run `smi-dash --help` or `smi-dash <verb> --help` for every flag. Each answer starts with `OK:` or `ERROR:` and ends with `Hint:` lines naming the next command; add `--json` for `{status, data, hints}`.++## HTTP API++| Method and path | Purpose |+|---|---|+| `GET /events` | SSE: `state`, `frame` (about 30 per second), `toast`, `click`, `reveal`, `cursor`, `reload` |+| `GET /state`, `GET /frame`, `GET /health` | Current state with enums and ranges, one display frame, liveness |+| `POST /sim`, `/detect`, `/view`, `/source` | Partial JSON updates; unknown keys are refused with the valid list |+| `POST /zero`, `/record/start`, `/record/stop` | Displacement zero, recording |+| `GET/POST /settings` | Persisted settings |+| `POST /ui/{toast,click,reveal,cursor,reload}` | Drive the open page |+| `GET/POST /console` | The page's console, readable by the CLI |++Settings persist in `~/.adom/instances/smi-dash/settings.json`; each thread's simulator and view settings are restored from `snapshots/` on the next start. An idle server saves and exits after 24 h (Settings, or `--keep-alive`). `View > keep_awake` (`smi-dash view --keep-awake on`) makes the page hold a screen wake lock for unattended recordings; it is off by default.++## Build++```+cargo build --release # Linux, needs libudev-dev, libhdf5-dev+cargo build --release --target x86_64-pc-windows-gnu --no-default-features # Windows, CSV only+cargo test --release+```
software/dashboard/SKILL.mdadded+44@@ -0,0 +1,44 @@+---+name: smi-dash+description: >-+ Drive the self-mixing interferometer dashboard (smi-dash): live ADC0/ADC1 fringes from the+ Raspberry Pi Pico or the built-in simulator, fringe counting with direction, displacement in+ nm and um, velocity, spectrum, SYNC markers, CSV/HDF5 recording, and an accuracy suite against+ simulated ground truth. Use when asked to show the interferometer, simulate a moving target,+ count fringes, record the photodiode channels, or check the detector's error.+---++# smi-dash++Start one server per AI thread and reuse it:++```+smi-dash ls # what is running+smi-dash --ai-thread "<your thread>" start # reuses a live instance for that thread+smi-dash --ai-thread "<your thread>" show+```++Every verb answers `OK:`/`ERROR:` with `Hint:` lines; follow the hints. Verbs: `status`, `source sim|serial`,+`sim --profile constant|sine|step|hand|hold ...`, `detect --lp-hz --threshold --invert`, `view --window-ms+--history-s --pause --resume --keep-awake`, `zero`, `record start|stop|status`, `ui toast|click|reveal|cursor|reload`,+`settings get|set`, `console`, `eval --suite`, `stop`.++Selectors for `ui click`: `#btn-pause #btn-zero #btn-record #btn-settings #src-sim #src-serial+[data-profile=sine] #mm-toggle #s-close`. A toast you raise with `ui toast` appears on the user's screen.++## Displaying this app (REQUIRED, read before showing anything)++To SHOW this app, use `smi-dash show` (it opens the proper Hydrogen webview tab itself). For+manual display, FIRST load the `webview` skill (adom-workspace-control) and follow it.+- **NEVER open this app in VS Code's "Simple Browser"**: not a webview in the Adom+ ecosystem, no live channel, no console read-back, no AI drivability. Using it is a bug.+- Surfaces: **wv** (Hydrogen webview panel), **pup** (`pup` skill), the user's **real signed-in browser**+ (Adom browser extension), and **hdbw** (Hydrogen's standalone browser window, only under Hydrogen).+ Simple Browser is NEVER one of them.+- `?frame=16x9` letterboxes the page to an exact 16:9 stage for screen recordings.++## Limits to tell the user++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.
software/dashboard/assets/icon.svgadded+1@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="none" stroke="#e6edf3" stroke-width="1.3" stroke-linecap="round"><path d="M1 8h3"/><path d="M4 5.5v5"/><path d="M6 8c1-3 2 3 3 0s2 3 3 0 1 2 2.5 0"/></svg>
software/dashboard/assets/index.htmladded+552@@ -0,0 +1,552 @@+<!doctype html>+<html lang="en" data-scheme="studio">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>Interferometer</title>+<link rel="icon" href="icon.svg">+<style>+:root{+ --bg:#161b22;--surface:#0d1117;--elevated:#1c2128;--overlay:#21262d;--border:#30363d;+ --text:#e6edf3;--text-body:#c9d1d9;--text-2:#c9d1d9;--text-3:#6e7681;+ --accent:#00b8b1;--accent-hover:#00d4cb;--accent-bright:#00e6dc;--on-accent:#05221f;+ --blue:#64abff;--purple:#8c6bf7;--green:#3fb950;--red:#f85149;--yellow:#d29922;+ --f-head:"Familjen Grotesk","Satoshi",system-ui,-apple-system,"Segoe UI",sans-serif;+ --f-body:"Satoshi",system-ui,-apple-system,"Segoe UI",sans-serif;+ --f-mono:"JetBrains Mono",ui-monospace,"Cascadia Mono",Consolas,monospace;+ --away:#00b8b1;--toward:#8c6bf7;--ch2:#64abff;--sync:#d0d7de;+}+*{box-sizing:border-box;margin:0;padding:0}+html,body{height:100%;overflow:hidden;background:var(--bg);color:var(--text-body);font:13px/1.35 var(--f-body)}+*::-webkit-scrollbar{display:none}*{scrollbar-width:none}+button{font:inherit;color:inherit;background:none;border:0;cursor:pointer}+#app{display:grid;grid-template-rows:44px minmax(0,1fr) 24px;height:100vh;overflow:hidden}+/* header */+header{display:flex;align-items:center;gap:12px;padding:0 12px;background:var(--surface);border-bottom:1px solid var(--border)}+.brand{display:flex;align-items:center;gap:8px;font:600 14px var(--f-head);color:var(--accent);white-space:nowrap;cursor:default}+.brand .sub{color:var(--text-2);font-weight:500}+.vsep{width:1px;height:22px;background:var(--border)}+.subject{display:flex;align-items:baseline;gap:10px;min-width:0;flex:1}+.subject b{color:var(--text);font:600 14px var(--f-head);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}+.subject .meta{font:11px var(--f-mono);color:var(--text-3);white-space:nowrap}+@media (max-width:720px){.subject .meta{display:none}}+.actions{display:flex;gap:4px;margin-left:auto}+.ib{width:32px;height:32px;display:grid;place-items:center;border-radius:6px;border:1px solid transparent}+.ib:hover{background:var(--elevated);border-color:var(--border)}+.ib svg{width:16px;height:16px;stroke:var(--text);fill:none;stroke-width:1.6;stroke-linecap:round;stroke-linejoin:round}+.ib.is-on{background:color-mix(in srgb,var(--accent) 22%,transparent);border-color:var(--accent);box-shadow:inset 0 0 0 1px var(--accent)}+.ib.is-on svg{stroke:var(--accent-bright)}+.ib.rec-on{background:color-mix(in srgb,var(--accent) 22%,transparent);border-color:var(--accent)}+.ib.rec-on svg circle{fill:var(--accent-bright);stroke:var(--accent-bright);animation:pulse 1s infinite}+@keyframes pulse{50%{opacity:.35}}+/* body */+main{display:grid;grid-template-columns:minmax(0,1fr) clamp(260px,22vw,330px);gap:8px;padding:8px;min-height:0}+.plots{display:grid;grid-template-rows:1.3fr .85fr 1.1fr .9fr;gap:8px;min-height:0;min-width:0}+.card{background:var(--surface);border:1px solid var(--border);border-radius:8px;min-height:0;min-width:0;display:flex;flex-direction:column;overflow:hidden}+.ct{display:flex;align-items:center;gap:10px;padding:5px 10px 2px;font:600 12px var(--f-head);color:var(--text);white-space:nowrap}+.ct .lg{display:flex;gap:10px;font:500 11px var(--f-body);color:var(--text-2);overflow:hidden}+.ct .lg i{display:inline-block;width:10px;height:3px;border-radius:2px;margin-right:4px;vertical-align:middle}+.ct .r{margin-left:auto;font:11px var(--f-mono);color:var(--text-3)}+.cv{flex:1;min-height:0;position:relative}+.cv canvas{position:absolute;inset:0;width:100%;height:100%}+/* side panel */+aside{display:flex;flex-direction:column;gap:8px;min-height:0;overflow:hidden}+.panel{background:var(--surface);border:1px solid var(--border);border-radius:8px;padding:6px 9px;display:flex;flex-direction:column;gap:5px}+.big{font:600 clamp(22px,2.2vw,32px)/1.05 var(--f-mono);color:var(--text);letter-spacing:-.5px}+.lbl{font:500 11px var(--f-body);color:var(--text-2)}+.sub2{font:12px var(--f-mono);color:var(--text-3)}+.grid2{display:grid;grid-template-columns:1fr 1fr;gap:3px 10px}+.kv .v{font:600 14px var(--f-mono);color:var(--text)}+.dirpill{display:inline-flex;align-items:center;gap:4px;font:600 11px var(--f-body);padding:1px 7px;border-radius:10px;border:1px solid var(--border)}+.dirpill svg{width:11px;height:11px;fill:currentColor}+.seg{display:flex;background:var(--bg);border:1px solid var(--border);border-radius:6px;padding:2px;gap:2px}+.seg button{flex:1;padding:3px 2px;border-radius:4px;font:500 12px var(--f-body);color:var(--text-2);white-space:nowrap}+.seg button:hover{background:var(--elevated);color:var(--text)}+.seg button.is-on{background:color-mix(in srgb,var(--accent) 24%,var(--elevated));color:var(--accent-bright);box-shadow:inset 0 0 0 1px var(--accent)}+.row{display:flex;align-items:center;gap:8px}+.slider{display:grid;grid-template-columns:78px 1fr 80px;align-items:center;gap:6px}+.slider span{font:11px var(--f-body);color:var(--text-2)}+.slider output{font:11px var(--f-mono);color:var(--text);text-align:right}+input[type=range]{-webkit-appearance:none;appearance:none;width:100%;height:4px;background:var(--border);border-radius:2px;outline:none}+input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;width:13px;height:13px;border-radius:50%;background:var(--accent);border:2px solid var(--surface)}+input[type=range]::-moz-range-thumb{width:12px;height:12px;border-radius:50%;background:var(--accent);border:2px solid var(--surface)}+.toggle{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:4px 8px;border-radius:6px;border:1px solid var(--border);background:var(--bg);font:500 12px var(--f-body);color:var(--text-2)}+.toggle .sw{width:30px;height:16px;border-radius:8px;background:var(--border);position:relative;transition:.15s}+.toggle .sw::after{content:"";position:absolute;top:2px;left:2px;width:12px;height:12px;border-radius:50%;background:var(--text-3);transition:.15s}+.toggle.is-on{border-color:var(--accent);color:var(--accent-bright);background:color-mix(in srgb,var(--accent) 12%,var(--bg))}+.toggle.is-on .sw{background:var(--accent)}+.toggle.is-on .sw::after{left:16px;background:var(--on-accent)}+.btn{padding:6px 10px;border-radius:6px;border:1px solid var(--border);background:var(--elevated);font:600 12px var(--f-body);color:var(--text)}+.btn:hover{border-color:var(--accent)}+.btn.primary{background:var(--accent);color:var(--on-accent);border-color:var(--accent)}+.btn.primary:hover{background:var(--accent-hover)}+select{font:12px var(--f-body);background:var(--bg);color:var(--text);border:1px solid var(--border);border-radius:6px;padding:4px 6px}+.hide{display:none!important}+.hint{font:11px var(--f-body);color:var(--text-3)}+/* status bar */+footer{display:flex;align-items:center;gap:14px;padding:0 12px;background:var(--surface);border-top:1px solid var(--border);font:11px var(--f-mono);color:var(--text-3);white-space:nowrap;overflow:hidden}+.led{width:8px;height:8px;border-radius:50%;background:var(--text-3);display:inline-block;margin-right:6px;vertical-align:middle}+.led.ok{background:var(--green)}.led.bad{background:var(--red)}.led.warn{background:var(--yellow)}+/* toasts, tooltips, cursor, modal */+#toasts{position:fixed;left:50%;bottom:36px;transform:translateX(-50%);display:flex;flex-direction:column-reverse;gap:6px;z-index:9000;pointer-events:none}+.toast{pointer-events:auto;min-width:240px;max-width:560px;padding:8px 12px;border-radius:8px;background:var(--overlay);border:1px solid var(--border);border-left:3px solid var(--accent);color:var(--text);font:13px var(--f-body);box-shadow:0 8px 24px rgba(0,0,0,.45);animation:tin .18s ease}+.toast.error{border-left-color:var(--red)}.toast.success{border-left-color:var(--green)}+@keyframes tin{from{opacity:0;transform:translateY(6px)}}+#tt{position:fixed;z-index:99999;max-width:300px;padding:7px 10px;border-radius:6px;background:var(--overlay);border:1px solid var(--border);color:var(--text-body);font:12px/1.4 var(--f-body);text-transform:none;pointer-events:none;opacity:0;transition:opacity .18s ease,transform .18s ease;transform:translateY(3px)}+#tt.show{opacity:1;transform:none}+#cursor{position:fixed;z-index:99998;left:-40px;top:-40px;pointer-events:none;transition:left .3s ease,top .3s ease;display:none}+#cursor svg{width:20px;height:20px;filter:drop-shadow(0 2px 3px rgba(0,0,0,.6))}+#cursor .lab{position:absolute;left:18px;top:16px;background:var(--accent);color:var(--on-accent);font:600 11px var(--f-body);padding:2px 6px;border-radius:4px;white-space:nowrap}+#modal{position:fixed;inset:0;background:rgba(1,4,9,.6);display:none;place-items:center;z-index:9500}+#modal.show{display:grid}+.dlg{width:min(480px,92vw);max-height:90vh;overflow:auto;background:var(--surface);border:1px solid var(--border);border-radius:10px;padding:14px 16px;display:flex;flex-direction:column;gap:10px}+.dlg h2{font:600 16px var(--f-head);color:var(--text)}+.srow{display:grid;grid-template-columns:1fr 170px;align-items:center;gap:10px}+.srow label{font:12px var(--f-body);color:var(--text-body)}+.srow input[type=text],.srow input[type=number]{font:12px var(--f-mono);background:var(--bg);color:var(--text);border:1px solid var(--border);border-radius:6px;padding:4px 6px;width:100%}+.ver{font:11px var(--f-mono);color:var(--text-3)}+@media (max-width:900px){main{grid-template-columns:1fr}aside{display:none}}+@media (max-height:520px){.plots{grid-template-rows:1.3fr .8fr 1fr 0fr}#card-spec{display:none}}+/* ?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)}+</style>+</head>+<body>+<div id="app">+<header>+ <div class="brand" id="brand" data-tip="Self-mixing interferometer dashboard. Reads the Raspberry Pi Pico over USB, or simulates the laser, optics and analog chain.">+ <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"><path d="M1 8h3"/><path d="M4 5.5v5"/><path d="M6 8c1-3 2 3 3 0s2 3 3 0 1 2 2.5 0"/></svg>+ Interferometer <span class="sub">· SMI dashboard</span>+ </div>+ <div class="vsep"></div>+ <div class="subject"><b id="subj">Simulator</b><span class="meta" id="subj-meta">250 ksps per channel · λ 658 nm · 1 fringe = 329 nm</span></div>+ <div class="actions">+ <button class="ib" id="btn-pause" data-tip="Freeze the plots. Acquisition and the displacement count keep running. While frozen, drag a channel plot to look back up to 2 s." aria-pressed="false">+ <svg viewBox="0 0 16 16"><path d="M5 3v10M11 3v10"/></svg></button>+ <button class="ib" id="btn-zero" data-tip="Set the running displacement to zero here. The fringe count restarts; recorded data is not changed.">+ <svg viewBox="0 0 16 16"><circle cx="8" cy="8" r="5"/><path d="M8 1v3M8 12v3M1 8h3M12 8h3"/></svg></button>+ <button class="ib" id="btn-record" data-tip="Record both channels, SYNC, fringes and displacement. Format and folder are in Settings. Click again to stop and save." aria-pressed="false">+ <svg viewBox="0 0 16 16"><circle cx="8" cy="8" r="4.5"/></svg></button>+ <button class="ib" id="btn-settings" data-tip="Settings: frame rate, units, recording format and folder, detector tuning, idle shutdown.">+ <svg viewBox="0 0 16 16"><circle cx="8" cy="8" r="2.2"/><path d="M8 1.5v2M8 12.5v2M1.5 8h2M12.5 8h2M3.4 3.4l1.4 1.4M11.2 11.2l1.4 1.4M3.4 12.6l1.4-1.4M11.2 4.8l1.4-1.4"/></svg></button>+ </div>+</header>+<main>+ <section class="plots">+ <div class="card" id="card-ch1">+ <div class="ct">Channel 1 · laser monitor photodiode (ADC0)+ <span class="lg"><span><i style="background:var(--accent)"></i>ADC</span><span><i style="background:var(--accent-bright)"></i>low-passed</span><span><i style="background:var(--away)"></i>fringe, away</span><span><i style="background:var(--toward)"></i>fringe, towards</span><span><i style="background:var(--sync)"></i>SYNC</span></span>+ <span class="r" id="ch1-r"></span></div>+ <div class="cv" data-tip="Scroll to zoom the time window (0.1 ms to 2 s). Double-click resets to 10 ms. When frozen, drag to look back."><canvas id="cv-ch1"></canvas></div>+ </div>+ <div class="card" id="card-ch2">+ <div class="ct">Channel 2 · external photodiode (ADC1)<span class="r" id="ch2-r"></span></div>+ <div class="cv" data-tip="Same time window as channel 1. Sampled 2 us after channel 1 in each pair."><canvas id="cv-ch2"></canvas></div>+ </div>+ <div class="card" id="card-disp">+ <div class="ct">Displacement+ <span class="lg"><span><i style="background:var(--accent)"></i>counted</span><span id="lg-truth"><i style="background:var(--text-3)"></i>simulator truth</span></span>+ <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-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>+ <span class="r" id="spec-r"></span></div>+ <div class="cv" data-tip="Hann-windowed FFT of the last 8192 samples (33 ms) per channel, dB relative to ADC full scale. The fringe frequency times lambda/2 is the speed."><canvas id="cv-spec"></canvas></div>+ </div>+ </section>+ <aside>+ <div class="panel">+ <div class="lbl">Displacement</div>+ <div class="big" id="ro-disp">0 nm</div>+ <div class="sub2" id="ro-disp2">0.000 µm</div>+ <div class="grid2">+ <div class="kv"><div class="lbl">Velocity</div><div class="v" id="ro-vel">0</div></div>+ <div class="kv"><div class="lbl">Fringe rate</div><div class="v" id="ro-rate">0 Hz</div></div>+ <div class="kv"><div class="lbl">Fringes</div><div class="v" id="ro-count">0</div></div>+ <div class="kv"><div class="lbl">Direction</div><div class="v"><span class="dirpill" id="ro-dir">none</span></div></div>+ </div>+ </div>+ <div class="panel" id="p-truth" data-tip="Only with the simulator: the counted displacement compared with the simulated target's true position. Counting resolves one fringe, 329 nm, so errors up to that size are expected.">+ <div class="grid2">+ <div class="kv"><div class="lbl">Simulator truth</div><div class="v" id="ro-truth">0</div></div>+ <div class="kv"><div class="lbl">Error now</div><div class="v" id="ro-err">0</div></div>+ <div class="kv"><div class="lbl">RMS error (trace)</div><div class="v" id="ro-rms">0</div></div>+ <div class="kv"><div class="lbl">Max error (trace)</div><div class="v" id="ro-max">0</div></div>+ </div>+ </div>+ <div class="panel">+ <div class="lbl">Source</div>+ <div class="seg">+ <button id="src-sim" data-tip="Generate physically modelled signals: self-mixing optics, the board's analog chain and the RP2040 ADC.">Simulator</button>+ <button id="src-serial" data-tip="Read the Raspberry Pi Pico running smi_pico.uf2 over USB serial. Picks the first Pico port found.">Pico (USB)</button>+ </div>+ <div class="slider" data-tip="Low-pass corner of the fringe detector. Keep the fringe rate below about two thirds of it; raise it for fast moves, at the cost of more noise."><span>Detector LP</span><input type="range" id="lp-slider" min="0" max="1000" step="1"><output id="lp-out"></output></div>+ </div>+ <div class="panel" id="p-sim">+ <div class="lbl">Target motion</div>+ <div class="seg" id="profiles">+ <button data-profile="constant" data-tip="Constant speed, reversing at the ends of the travel range.">Constant</button>+ <button data-profile="sine" data-tip="Sinusoidal back-and-forth around the start point.">Sine</button>+ <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>+ </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>+ </aside>+</main>+<footer>+ <span><span class="led" id="led"></span><span id="st-link">connecting</span></span>+ <span id="st-rate"></span><span id="st-frames"></span><span id="st-err"></span><span id="st-fps"></span>+ <span id="rec-hint">Not recording</span>+ <span style="margin-left:auto" id="st-ver"></span>+</footer>+</div>+<div id="toasts"></div>+<div id="tt"></div>+<div id="cursor"><svg viewBox="0 0 20 20"><path d="M2 2l6 15 2.2-6.2L16.5 8.5z" fill="#00e6dc" stroke="#05221f" stroke-width="1.2"/></svg><span class="lab" id="cursor-lab">AI</span></div>+<div id="modal"><div class="dlg">+ <h2>Settings</h2>+ <div class="srow"><label data-tip="Frames per second pushed to this page. Lower it on a slow machine.">Display frame rate</label><input type="number" id="s-fps" min="5" max="60" step="1"></div>+ <div class="srow"><label data-tip="Auto shows nm below 10 um and um above.">Displacement units</label><select id="s-units"><option value="auto">Auto</option><option value="nm">nm</option><option value="um">µm</option></select></div>+ <div class="srow"><label data-tip="CSV streams to disk as it records. HDF5 holds the data in memory and writes on stop, up to 120 s.">Recording format</label><select id="s-format"><option value="csv">CSV</option><option value="h5">HDF5</option></select></div>+ <div class="srow"><label data-tip="Folder for recordings. A leading ~ means your home folder.">Recording folder</label><input type="text" id="s-dir"></div>+ <div class="srow"><label data-tip="A jump counts as a fringe when it is larger than this fraction of the fringe amplitude.">Detector threshold</label><input type="number" id="s-thr" min="0.05" max="0.95" step="0.05"></div>+ <div class="srow"><label data-tip="Flip which way counts as away. Depends on the photodiode jumpers and which way your stage moves.">Invert direction</label><div class="toggle" id="s-invert" role="switch"><span>Inverted</span><span class="sw"></span></div></div>+ <div class="srow"><label data-tip="The server saves its state and exits after this many idle hours. Your settings are kept.">Idle shutdown (hours)</label><input type="number" id="s-ttl" min="0.1" step="1"></div>+ <div class="srow"><label data-tip="Where smi-dash show opens this page.">Default display</label><select id="s-surface"><option value="wv">Hydrogen webview</option><option value="pup">pup browser</option></select></div>+ <div class="row" style="justify-content:space-between"><span class="ver" id="s-ver"></span><button class="btn primary" id="s-close">Done</button></div>+</div></div>+<script>+"use strict";+if(new URLSearchParams(location.search).get("frame")==="16x9") document.documentElement.classList.add("framed");+const $=s=>document.querySelector(s);+const LSB=3.3/4096;+let S=null, F=null, fpsEMA=0, dragging=null, renderPending=false; const frameTimes=[];++// console capture: the AI reads it with `smi-dash console`+(function(){+ for(const lv of ["log","warn","error"]){+ const o=console[lv].bind(console);+ console[lv]=(...a)=>{o(...a);post("console",{level:lv,text:a.map(x=>typeof x==="string"?x:JSON.stringify(x)).join(" "),t:Date.now()},true)};+ }+ window.addEventListener("error",e=>console.error("onerror: "+e.message+" @"+e.lineno));+ window.addEventListener("unhandledrejection",e=>console.error("unhandled: "+(e.reason&&e.reason.message||e.reason)));+})();++function post(path,body,quiet){+ return fetch(path,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(body||{})})+ .then(r=>r.json()).then(j=>{ if(j.status==="error"&&!quiet){toast(j.error+(j.hints&&j.hints.length?". "+j.hints[0]:""),"error")} return j})+ .catch(e=>{ if(!quiet) toast("Server not reachable: "+e.message,"error") });+}+const throttles={};+function postSoon(path,body,ms=90){+ const t=throttles[path]||(throttles[path]={timer:0,body:{}});+ Object.assign(t.body,body); clearTimeout(t.timer);+ t.timer=setTimeout(()=>{const b=t.body;t.body={};post(path,b)},ms);+}++// toasts+function toast(text,kind="info"){+ const d=document.createElement("div"); d.className="toast "+kind; d.textContent=text;+ const box=$("#toasts"); box.appendChild(d); while(box.children.length>4) box.firstChild.remove();+ let left=kind==="error"?12000:4000, t0=Date.now(), paused=false;+ d.onmouseenter=()=>{paused=true;left-=Date.now()-t0}; d.onmouseleave=()=>{paused=false;t0=Date.now();arm()};+ d.onclick=()=>d.remove();+ const arm=()=>setTimeout(()=>{if(!paused)d.remove()},left); arm();+}++// tooltips: body-appended, 600 ms delay, clamped to the viewport on both axes+(function(){+ const tt=$("#tt"); let timer=0, cur=null, mx=0, my=0;+ document.addEventListener("mousemove",e=>{mx=e.clientX;my=e.clientY});+ document.addEventListener("mouseover",e=>{+ const el=e.target.closest("[data-tip]"); if(el===cur) return; cur=el; clearTimeout(timer); tt.classList.remove("show");+ if(!el) return;+ timer=setTimeout(()=>{+ tt.textContent=el.dataset.tip; tt.style.left="0px"; tt.style.top="0px"; tt.classList.add("show");+ const M=8, w=tt.offsetWidth, h=tt.offsetHeight, W=document.documentElement.clientWidth, H=document.documentElement.clientHeight;+ let x=mx+14, y=my+14;+ if(x+w>W-M) x=mx-14-w; if(y+h>H-M) y=my-14-h;+ x=Math.max(M,Math.min(x,W-w-M)); y=Math.max(M,Math.min(y,H-h-M));+ tt.style.left=x+"px"; tt.style.top=y+"px";+ },600);+ });+ document.addEventListener("mousedown",()=>{clearTimeout(timer);tt.classList.remove("show")});+})();++// AI cursor+function aiCursor(sel,label,then){+ const el=document.querySelector(sel); if(!el){console.warn("cursor: no element "+sel);return}+ const r=el.getBoundingClientRect(), c=$("#cursor"); c.style.display="block";+ $("#cursor-lab").textContent=label||"AI";+ c.style.left=(r.left+r.width/2)+"px"; c.style.top=(r.top+r.height/2)+"px";+ setTimeout(()=>{ if(then) then(el); setTimeout(()=>{c.style.display="none"},1500) },380);+}++// formatting+function units(){return S&&S.settings?S.settings.units:"auto"}+function fmtDisp(nm){+ const u=units();+ if(u==="nm"||(u==="auto"&&Math.abs(nm)<10000)) return Math.round(nm).toLocaleString("en-US")+" nm";+ return (nm/1000).toFixed(3)+" µm";+}+function fmtVel(v){ if(!isFinite(v)) return "n/a"; return Math.abs(v)>=1000?(v/1000).toFixed(3)+" mm/s":v.toFixed(1)+" µm/s" }+function fmtHz(f){ return f>=1000?(f/1000).toFixed(2)+" kHz":Math.round(f)+" Hz" }++// canvas helpers+function ctxOf(id){+ const c=document.getElementById(id), r=c.getBoundingClientRect(), dpr=window.devicePixelRatio||1;+ const W=Math.max(1,Math.round(r.width*dpr)), H=Math.max(1,Math.round(r.height*dpr));+ if(c.width!==W||c.height!==H){c.width=W;c.height=H}+ const g=c.getContext("2d"); g.setTransform(dpr,0,0,dpr,0,0); g.clearRect(0,0,r.width,r.height);+ return {g,w:r.width,h:r.height};+}+// Theme colours, read once (getComputedStyle in a draw loop forces a style recalc per call).+const cssCache={};+const css=n=>cssCache[n]||(cssCache[n]=getComputedStyle(document.documentElement).getPropertyValue(n).trim());+function niceStep(range,n){const raw=range/n, p=Math.pow(10,Math.floor(Math.log10(raw))), m=raw/p; return (m<1.5?1:m<3.5?2:m<7.5?5:10)*p}+function axes(g,x0,y0,w,h,ylo,yhi,yfmt,xlo,xhi,xfmt){+ g.strokeStyle=css("--border"); g.lineWidth=1; g.fillStyle=css("--text-3"); g.font="10px "+css("--f-mono");+ const ys=niceStep(yhi-ylo,4);+ g.textAlign="right"; g.textBaseline="middle";+ for(let v=Math.ceil(ylo/ys)*ys; v<=yhi+1e-9; v+=ys){+ const y=y0+h-(v-ylo)/(yhi-ylo)*h; g.globalAlpha=.55; g.beginPath(); g.moveTo(x0,y+.5); g.lineTo(x0+w,y+.5); g.stroke(); g.globalAlpha=1;+ g.fillText(yfmt(v),x0-4,y);+ }+ const xs=niceStep(xhi-xlo,6), dec=Math.max(0,-Math.floor(Math.log10(xs)+1e-9)); g.textBaseline="top";+ for(let v=Math.ceil(xlo/xs)*xs; v<=xhi+1e-9; v+=xs){+ const x=x0+(v-xlo)/(xhi-xlo)*w; g.globalAlpha=.35; g.beginPath(); g.moveTo(x+.5,y0); g.lineTo(x+.5,y0+h); g.stroke(); g.globalAlpha=1;+ g.textAlign=x>x0+w-30?"right":x<x0+30?"left":"center";+ g.fillText(xfmt(Math.abs(v)<xs*1e-6?0:v,dec),x,y0+h+3);+ }+}+const scales={};+function autoscale(key,lo,hi,minSpan){+ const s=scales[key]||(scales[key]={lo,hi});+ const span=Math.max(hi-lo,minSpan), mid=(hi+lo)/2; let tlo=mid-span*0.6, thi=mid+span*0.6;+ // expand at once, shrink slowly+ s.lo=tlo<s.lo?tlo:s.lo+(tlo-s.lo)*0.06; s.hi=thi>s.hi?thi:s.hi+(thi-s.hi)*0.06;+ return s;+}+const PADL=44, PADB=16, PADT=6, PADR=8;++function drawChannel(id,ch,key,color,withMarks){+ const {g,w,h}=ctxOf(id); if(!F) return;+ const x0=PADL,y0=PADT,pw=w-PADL-PADR,ph=h-PADT-PADB, n=F.cols;+ let lo=4095,hi=0; for(let i=0;i<n;i++){ if(ch.mn[i]<lo)lo=ch.mn[i]; if(ch.mx[i]>hi)hi=ch.mx[i] }+ const sc=autoscale(key,lo*LSB,hi*LSB,0.02);+ const winms=F.win_ms;+ axes(g,x0,y0,pw,ph,sc.lo,sc.hi,v=>v.toFixed(sc.hi-sc.lo<0.2?3:2)+"",-winms,0,(v,d)=>v.toFixed(d)+" ms");+ const Y=v=>y0+ph-(v*LSB-sc.lo)/(sc.hi-sc.lo)*ph, X=i=>x0+(i+0.5)/n*pw;+ g.save(); g.beginPath(); g.rect(x0,y0,pw,ph); g.clip();+ // SYNC markers+ g.strokeStyle=css("--sync"); g.setLineDash([4,3]); g.lineWidth=1;+ for(const [c,lv] of F.sy){ const x=x0+c/n*pw; g.globalAlpha=lv?0.9:0.35; g.beginPath(); g.moveTo(x,y0); g.lineTo(x,y0+ph); g.stroke() }+ g.setLineDash([]); g.globalAlpha=1;+ // envelope+ g.strokeStyle=color; g.fillStyle=color; g.lineWidth=1.2;+ if(n<pw*0.9){ g.beginPath(); for(let i=0;i<n;i++){const x=X(i),y=Y((ch.mn[i]+ch.mx[i])/2); i?g.lineTo(x,y):g.moveTo(x,y)} g.stroke() }+ else { g.globalAlpha=.85; g.beginPath(); for(let i=0;i<n;i++){const x=X(i); g.moveTo(x,Y(ch.mx[i])-0.5); g.lineTo(x,Y(ch.mn[i])+0.5)} g.lineWidth=Math.max(1,pw/n); g.stroke(); g.globalAlpha=1 }+ if(withMarks){+ if(ch.f){ g.strokeStyle=css("--accent-bright"); g.lineWidth=1.3; g.globalAlpha=.9; g.beginPath(); for(let i=0;i<n;i++){const x=X(i),y=Y(ch.f[i]); i?g.lineTo(x,y):g.moveTo(x,y)} g.stroke(); g.globalAlpha=1 }+ const few=F.fr.length<=120, cAway=css("--away"), cToward=css("--toward");+ for(const [c,d] of F.fr){+ const x=x0+c/n*pw, col=d>0?cAway:cToward;+ if(few){ g.strokeStyle=col; g.globalAlpha=.28; g.lineWidth=1; g.beginPath(); g.moveTo(x,y0+12); g.lineTo(x,y0+ph); g.stroke(); g.globalAlpha=1 }+ g.fillStyle=col; g.beginPath();+ if(d>0){ g.moveTo(x,y0+1); g.lineTo(x-4,y0+9); g.lineTo(x+4,y0+9) } else { g.moveTo(x,y0+9); g.lineTo(x-4,y0+1); g.lineTo(x+4,y0+1) }+ g.fill();+ }+ }+ g.restore();+}++function drawDisp(){+ const {g,w,h}=ctxOf("cv-disp"); if(!F) return;+ const d=F.disp, m=d.meas, t=d.truth, n=m.length; if(n<2) return;+ let lo=Infinity,hi=-Infinity; for(let i=0;i<n;i++){ lo=Math.min(lo,m[i]); hi=Math.max(hi,m[i]); if(t[i]!=null){lo=Math.min(lo,t[i]);hi=Math.max(hi,t[i])} }+ const um=units()==="um"||(units()==="auto"&&Math.max(Math.abs(lo),Math.abs(hi))>=10000);+ const k=um?1/1000:1, sc=autoscale("disp",lo*k,hi*k,um?1:400);+ const x0=PADL+8,y0=PADT,pw=w-x0-PADR,ph=h-PADT-PADB, span=d.span_s||n*d.dt_s;+ axes(g,x0,y0,pw,ph,sc.lo,sc.hi,v=>um?v.toFixed(Math.abs(sc.hi-sc.lo)<5?2:0)+"µm":Math.round(v)+"nm",-span,0,(v,d)=>v.toFixed(d)+" s");+ const X=i=>x0+i/(n-1)*pw, Y=v=>y0+ph-(v*k-sc.lo)/(sc.hi-sc.lo)*ph;+ g.save(); g.beginPath(); g.rect(x0,y0,pw,ph); g.clip();+ if(t.some(v=>v!=null)){ g.strokeStyle=css("--text-3"); g.lineWidth=1.4; g.setLineDash([5,4]); g.beginPath(); let st=false; for(let i=0;i<n;i++){ if(t[i]==null){st=false;continue} const x=X(i),y=Y(t[i]); st?g.lineTo(x,y):g.moveTo(x,y); st=true } g.stroke(); g.setLineDash([]) }+ g.strokeStyle=css("--accent"); g.lineWidth=1.8; g.beginPath(); for(let i=0;i<n;i++){const x=X(i),y=Y(m[i]); i?g.lineTo(x,y):g.moveTo(x,y)} g.stroke();+ // zero line+ const yz=Y(0); if(yz>y0&&yz<y0+ph){ g.strokeStyle=css("--text-3"); g.globalAlpha=.6; g.beginPath(); g.moveTo(x0,yz+.5); g.lineTo(x0+pw,yz+.5); g.stroke(); g.globalAlpha=1 }+ g.restore();+}++function drawSpec(){+ const {g,w,h}=ctxOf("cv-spec"); if(!F||!F.spec||!F.spec.ch1) return;+ const x0=PADL,y0=PADT,pw=w-PADL-PADR,ph=h-PADT-PADB, fmax=F.spec.f_max/1000;+ const lo=-110, hi=0;+ axes(g,x0,y0,pw,ph,lo,hi,v=>v+"",0,fmax,(v,d)=>v.toFixed(d)+" kHz");+ const draw=(a,col)=>{ const n=a.length; g.strokeStyle=col; g.lineWidth=1.2; g.beginPath(); for(let i=0;i<n;i++){const x=x0+(i+.5)/n*pw, y=y0+ph-(Math.max(lo,Math.min(hi,a[i]))-lo)/(hi-lo)*ph; i?g.lineTo(x,y):g.moveTo(x,y)} g.stroke() };+ g.save(); g.beginPath(); g.rect(x0,y0,pw,ph); g.clip();+ draw(F.spec.ch2,css("--ch2")); draw(F.spec.ch1,css("--accent"));+ const px=x0+F.spec.peak_hz/1000/fmax*pw; g.strokeStyle=css("--text-2"); g.setLineDash([2,3]); g.beginPath(); g.moveTo(px,y0); g.lineTo(px,y0+ph); g.stroke(); g.setLineDash([]);+ g.restore();+}++function render(){+ if(!F) return;+ drawChannel("cv-ch1",F.ch1,"ch1",css("--accent"),true);+ drawChannel("cv-ch2",F.ch2,"ch2",css("--ch2"),false);+ drawDisp(); drawSpec();+ const r=F.readout;+ $("#ro-disp").textContent=fmtDisp(r.disp_nm);+ $("#ro-disp2").textContent=Math.abs(r.disp_nm)<10000?(r.disp_nm/1000).toFixed(3)+" µm":Math.round(r.disp_nm).toLocaleString("en-US")+" nm";+ $("#ro-vel").textContent=fmtVel(r.vel_um_s);+ $("#ro-rate").textContent=fmtHz(r.fringe_rate_hz);+ $("#ro-count").textContent=r.count.toLocaleString("en-US");+ const dp=$("#ro-dir"), moving=Math.abs(r.vel_um_s)>0.4*r.half_wave_nm/1000*10;+ if(!moving){dp.innerHTML="still";dp.style.color="var(--text-2)";dp.style.borderColor="var(--border)"}+ else if(r.vel_um_s>0){dp.innerHTML='<svg viewBox="0 0 10 10"><path d="M5 1l4 7H1z"/></svg>away';dp.style.color="var(--away)";dp.style.borderColor="var(--away)"}+ else {dp.innerHTML='<svg viewBox="0 0 10 10"><path d="M5 9L1 2h8z"/></svg>towards';dp.style.color="var(--toward)";dp.style.borderColor="var(--toward)"}+ const hasT=r.truth_nm!=null; $("#p-truth").classList.toggle("hide",!hasT); $("#lg-truth").classList.toggle("hide",!hasT);+ if(hasT){ $("#ro-truth").textContent=fmtDisp(r.truth_nm); $("#ro-err").textContent=Math.round(r.err_nm)+" nm"; $("#ro-rms").textContent=Math.round(r.rms_err_nm)+" nm"; $("#ro-max").textContent=Math.round(r.max_err_nm)+" nm" }+ $("#ch1-r").textContent=F.win_ms.toFixed(F.win_ms<1?2:F.win_ms<10?1:0)+" ms window"+(F.paused?" · frozen":"");+ $("#ch2-r").textContent=(F.ch2.mx.length?"":"");+ $("#disp-r").textContent=F.disp.span_s.toFixed(1)+" s";+ $("#spec-r").textContent=F.spec&&F.spec.peak_hz?"peak "+fmtHz(F.spec.peak_hz)+" · "+fmtVel(F.spec.peak_hz*r.half_wave_nm/1000):"";+ const L=F.link, led=$("#led");+ const serial=S&&S.source&&S.source.kind==="serial";+ led.className="led "+(L.error?"bad":(L.connected?((L.crc_errors||L.gaps||L.dropped_bufs)?"warn":"ok"):"warn"));+ $("#st-link").textContent=L.error?L.error:(serial?(L.connected?"Pico streaming":"waiting for Pico"):"simulator running");+ $("#st-rate").textContent=(L.rate_sps/1000).toFixed(0)+" ksps total";+ $("#st-frames").textContent=serial?("frames "+L.frames):"";+ $("#st-err").textContent=serial?("crc "+L.crc_errors+" · gaps "+L.gaps+" · dropped "+L.dropped_bufs):"";+ $("#st-fps").textContent=fpsEMA.toFixed(0)+" fps";+ const rec=F.rec, rb=$("#btn-record"); rb.classList.toggle("rec-on",!!rec); rb.setAttribute("aria-pressed",!!rec);+ $("#rec-hint").textContent=rec?("Recording "+rec.seconds.toFixed(1)+" s"+(rec.limit_seconds?" of "+rec.limit_seconds.toFixed(0):"")+" to "+rec.path.split(/[\\/]/).pop()):(F.rec_error?("Recording error: "+F.rec_error):"Not recording");+ const pb=$("#btn-pause"); pb.classList.toggle("is-on",F.paused); pb.setAttribute("aria-pressed",F.paused);+}++// motion sliders per profile+const LOG=(lo,hi)=>({to:v=>Math.log(v/lo)/Math.log(hi/lo)*1000, from:x=>lo*Math.pow(hi/lo,x/1000)});+const MOTION={+ constant:[["speed_um_s","Speed",LOG(10,10000),v=>fmtVel(v),"Target speed. Fringe rate = speed / 329 nm."],["range_um","Travel",LOG(5,5000),v=>v>=1000?(v/1000).toFixed(2)+" mm":v.toFixed(0)+" µm","Travel before each reversal."]],+ sine:[["amp_um","Amplitude",LOG(0.5,200),v=>v.toFixed(v<10?1:0)+" µm","Zero-to-peak amplitude."],["freq_hz","Frequency",LOG(0.1,20),v=>v.toFixed(v<1?2:1)+" Hz","Cycles per second."]],+ 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:[],+};+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 }+ 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>`;+ const inp=d.querySelector("input"), out=d.querySelector("output");+ inp.oninput=()=>{dragging=inp; const v=map.from(+inp.value); out.textContent=fmt(v); postSoon("sim",{[key]:+v.toPrecision(4)})};+ inp.onchange=()=>{dragging=null};+ inp._sync=()=>{ if(dragging===inp||!S) return; const v=S.sim[key]; inp.value=map.to(v); out.textContent=fmt(v) };+ box.appendChild(d);+ }+}+const LPMAP=LOG(2000,80000);+function applyState(){+ if(!S) return;+ const sim=S.sim, serial=S.source.kind==="serial";+ $("#src-sim").classList.toggle("is-on",!serial); $("#src-serial").classList.toggle("is-on",serial);+ $("#p-sim").classList.toggle("hide",serial);+ $("#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":""));+ for(const b of document.querySelectorAll("[data-profile]")) b.classList.toggle("is-on",b.dataset.profile===sim.profile);+ buildMotion(sim.profile);+ for(const i of document.querySelectorAll("#motion-sliders input")) i._sync&&i._sync();+ if(dragging!==$("#c-slider")){ $("#c-slider").value=sim.c; } $("#c-out").textContent=(+sim.c).toFixed(2);+ if(dragging!==$("#noise-slider")){ $("#noise-slider").value=sim.noise; } $("#noise-out").textContent="x"+(+sim.noise).toFixed(1);+ const mm=$("#mm-toggle"); mm.classList.toggle("is-on",sim.multimode); mm.setAttribute("aria-pressed",sim.multimode);+ if(dragging!==$("#lp-slider")) $("#lp-slider").value=LPMAP.to(S.detect.lp_hz); $("#lp-out").textContent=fmtHz(S.detect.lp_hz);+ const st=S.settings; $("#s-fps").value=st.fps; $("#s-units").value=st.units; $("#s-format").value=st.record_format; $("#s-dir").value=st.record_dir;+ $("#s-thr").value=S.detect.threshold; $("#s-ttl").value=st.ttl_hours; $("#s-surface").value=st.surface;+ const inv=$("#s-invert"); inv.classList.toggle("is-on",S.detect.invert); inv.setAttribute("aria-pressed",S.detect.invert);+ $("#s-ver").textContent="smi-dash "+S.version+" · port "+S.port+" · thread "+S.thread;+ $("#st-ver").textContent="smi-dash "+S.version;+ syncWakeLock();+}+// Screen wake lock, only while the server's view.keep_awake is on (unattended recordings).+let wakeLock=null;+async function syncWakeLock(){+ const want=!!(S&&S.view&&S.view.keep_awake)&&document.visibilityState==="visible";+ if(want&&!wakeLock){+ if(!("wakeLock" in navigator)){console.warn("wake lock: not supported here");return}+ try{ wakeLock=await navigator.wakeLock.request("screen"); console.log("wake lock: held");+ wakeLock.addEventListener("release",()=>{console.log("wake lock: released");wakeLock=null}) }+ catch(e){ console.warn("wake lock: refused, "+e.name+": "+e.message) }+ } else if(!want&&wakeLock){ const w=wakeLock; wakeLock=null; await w.release() }+}+document.addEventListener("visibilitychange",syncWakeLock);++// controls+$("#src-sim").onclick=()=>post("source",{kind:"sim"});+$("#src-serial").onclick=()=>post("source",{kind:"serial"}).then(j=>{ if(j&&j.status==="ok") toast("Reading the Pico on "+j.data.port) });+for(const b of document.querySelectorAll("[data-profile]")) b.onclick=()=>post("sim",{profile:b.dataset.profile}).then(()=>post("zero",{},true));+$("#c-slider").oninput=e=>{dragging=e.target; $("#c-out").textContent=(+e.target.value).toFixed(2); postSoon("sim",{c:+e.target.value})};+$("#noise-slider").oninput=e=>{dragging=e.target; $("#noise-out").textContent="x"+(+e.target.value).toFixed(1); postSoon("sim",{noise:+e.target.value})};+$("#lp-slider").oninput=e=>{dragging=e.target; const v=Math.round(LPMAP.from(+e.target.value)/100)*100; $("#lp-out").textContent=fmtHz(v); postSoon("detect",{lp_hz:v})};+for(const id of ["#c-slider","#noise-slider","#lp-slider"]) $(id).onchange=()=>{dragging=null};+$("#mm-toggle").onclick=()=>{ const on=!S.sim.multimode; post("sim",{multimode:on}).then(()=>toast(on?"Second longitudinal mode on: fringes now fade every 1.46 mm":"Single longitudinal mode: steady fringe amplitude")) };+$("#btn-pause").onclick=()=>post("view",{paused:!F.paused});+$("#btn-zero").onclick=()=>post("zero",{});+$("#btn-record").onclick=()=>{ if(F&&F.rec) post("record/stop",{}); else post("record/start",{}) };+$("#btn-settings").onclick=()=>$("#modal").classList.add("show");+$("#s-close").onclick=()=>$("#modal").classList.remove("show");+$("#modal").onclick=e=>{ if(e.target.id==="modal") $("#modal").classList.remove("show") };+const setS=(k,v)=>post("settings",{[k]:v}).then(j=>{ if(j&&j.status==="ok") toast("Saved: "+k.replace("_"," ")) });+$("#s-fps").onchange=e=>setS("fps",+e.target.value);+$("#s-units").onchange=e=>setS("units",e.target.value);+$("#s-format").onchange=e=>setS("record_format",e.target.value);+$("#s-dir").onchange=e=>setS("record_dir",e.target.value);+$("#s-ttl").onchange=e=>setS("ttl_hours",+e.target.value);+$("#s-surface").onchange=e=>setS("surface",e.target.value);+$("#s-thr").onchange=e=>post("detect",{threshold:+e.target.value}).then(()=>toast("Saved: detector threshold"));+$("#s-invert").onclick=()=>post("detect",{invert:!S.detect.invert}).then(()=>toast("Saved: direction "+(S.detect.invert?"normal":"inverted")));++// 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;+const zoomWin=f=>{ const cur=pendingWin||S.view.window_ms; pendingWin=Math.max(0.1,Math.min(2000,cur*f)); postSoon("view",{window_ms:+pendingWin.toPrecision(3)},60); setTimeout(()=>{pendingWin=null},400) };+wheelOn("cv-ch1",zoomWin); wheelOn("cv-ch2",zoomWin);+wheelOn("cv-disp",f=>postSoon("view",{history_s:Math.max(0.5,Math.min(120,S.view.history_s*f))},60));+for(const id of ["cv-ch1","cv-ch2"]){+ const el=document.getElementById(id).parentElement;+ el.addEventListener("dblclick",()=>post("view",{window_ms:10}));+ let drag=null;+ el.addEventListener("mousedown",e=>{ if(F&&F.paused) drag={x:e.clientX,pan:S.view.pan_ms,w:el.clientWidth} });+ window.addEventListener("mousemove",e=>{ if(!drag) return; const ms=(e.clientX-drag.x)/drag.w*F.win_ms; postSoon("view",{pan_ms:Math.max(0,drag.pan+ms)},40) });+ window.addEventListener("mouseup",()=>{drag=null});+}++// live channel+function connect(){+ const es=new EventSource("events");+ es.addEventListener("state",e=>{ S=JSON.parse(e.data); applyState() });+ es.addEventListener("frame",e=>{ F=JSON.parse(e.data); const now=performance.now(); frameTimes.push(now); while(frameTimes.length&&frameTimes[0]<now-1000) frameTimes.shift(); fpsEMA=frameTimes.length; if(!renderPending){renderPending=true; requestAnimationFrame(()=>{renderPending=false; render()})} });+ es.addEventListener("toast",e=>{ const d=JSON.parse(e.data); toast(d.text,d.kind) });+ es.addEventListener("click",e=>{ const d=JSON.parse(e.data); aiCursor(d.selector,d.label||"AI",el=>el.click()) });+ 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.onerror=()=>{ $("#led").className="led bad"; $("#st-link").textContent="server not reachable, retrying" };+}+window.addEventListener("resize",()=>requestAnimationFrame(render));+document.addEventListener("visibilitychange",()=>console.log("visibility "+document.visibilityState));+let rafCount=0; (function tick(){rafCount++; requestAnimationFrame(tick)})();+setInterval(()=>{console.log(`heartbeat: ${fpsEMA} frames/s received, ${rafCount} animation frames in 10 s, visibility ${document.visibilityState}`); rafCount=0},10000);+connect();+</script>+</body>+</html>
software/dashboard/src/dsp.rsadded+262@@ -0,0 +1,262 @@+// SPDX-License-Identifier: MIT+//! Classical fringe detection for self-mixing signals.+//!+//! 1. Low-pass (2nd-order Butterworth, default 10 kHz) to suppress ADC noise.+//! 2. Track the fringe envelope: decaying running max and min give the+//! peak-to-peak amplitude and midline.+//! 3. Edge detection: a D-sample difference y[n] - y[n-D] with D matched to the+//! filter's rise time. The sawtooth's sharp jump gives a large difference;+//! the slow ramp between jumps gives a small one.+//! 4. A jump counts as one fringe (lambda / 2 of travel) when its size exceeds+//! `threshold` x the envelope's peak-to-peak and the envelope is clear of+//! the noise floor. The jump's sign gives the direction.+//!+//! Limits, stated plainly: with weak feedback (C below about 1) the signal is a+//! near-sinusoid with no sharp edge, so this detector stops counting; the+//! fringe rate must stay well below the low-pass corner (about fc / 1.5) or the+//! ramp itself crosses the threshold; and when the envelope fades (multimode+//! beating) fringes are missed.++use crate::sim::Biquad;+use rustfft::{num_complex::Complex, FftPlanner};+use serde::{Deserialize, Serialize};++#[derive(Clone, Debug, Serialize, Deserialize)]+#[serde(default)]+pub struct DetectParams {+ pub lp_hz: f64,+ /// Jump size as a fraction of the envelope's peak-to-peak.+ pub threshold: f64,+ /// Minimum envelope, in ADC codes, before anything is counted.+ pub min_pp_codes: f64,+ /// Flip the sign convention (depends on the photodiode jumpers and TIA polarity).+ pub invert: bool,+ pub wavelength_nm: f64,+}++impl Default for DetectParams {+ fn default() -> Self {+ Self { lp_hz: 10_000.0, threshold: 0.35, min_pp_codes: 24.0, invert: false, wavelength_nm: 658.0 }+ }+}++#[derive(Clone, Copy, Debug, Serialize)]+pub struct Fringe {+ pub pair: u64,+ /// +1 = target moving away from the laser, -1 = towards it.+ pub dir: i8,+}++pub struct Detector {+ pub p: DetectParams,+ fs: f64,+ lp: Biquad,+ hist: Vec<f64>,+ hpos: usize,+ d: usize,+ env_max: f64,+ env_min: f64,+ decay: f64,+ in_edge: bool,+ edge_best: f64,+ edge_pair: u64,+ refractory: u64,+ last_edge: u64,+ primed: u64,+ /// Signed, squared size of recent edge candidates (exponential average).+ /// Jumps are larger than any ramp segment that crosses the threshold, so+ /// its sign is the jump direction.+ pub jump_sign: f64,+ pub count: i64,+ pub filtered_last: f64,+}++impl Detector {+ pub fn new(p: DetectParams, fs: f64) -> Self {+ let mut d = Self {+ lp: Biquad::lowpass(p.lp_hz, std::f64::consts::FRAC_1_SQRT_2, fs),+ p,+ fs,+ hist: vec![],+ hpos: 0,+ d: 1,+ env_max: f64::MIN,+ env_min: f64::MAX,+ decay: 0.0,+ in_edge: false,+ edge_best: 0.0,+ edge_pair: 0,+ refractory: 0,+ last_edge: 0,+ primed: 0,+ jump_sign: 0.0,+ count: 0,+ filtered_last: 0.0,+ };+ d.configure();+ d+ }++ fn configure(&mut self) {+ let fc = self.p.lp_hz.clamp(500.0, 0.45 * self.fs);+ self.lp = Biquad::lowpass(fc, std::f64::consts::FRAC_1_SQRT_2, self.fs);+ // Difference span: about the filter's 10-90 % rise time (0.35 / fc).+ // Never shorter than the board's own anti-alias rise time (about 2 samples).+ self.d = ((0.35 / fc) * self.fs).round().max(2.0) as usize;+ self.hist = vec![0.0; self.d + 1];+ self.hpos = 0;+ self.refractory = (self.d as u64) * 2;+ // Envelope decays toward the midline with a 30 ms time constant.+ self.decay = 1.0 / (0.03 * self.fs);+ self.primed = 0;+ }++ pub fn set_params(&mut self, p: DetectParams) {+ let refilter = p.lp_hz != self.p.lp_hz;+ self.p = p;+ if refilter {+ self.configure();+ }+ }++ pub fn half_wave_nm(&self) -> f64 {+ self.p.wavelength_nm / 2.0+ }++ pub fn displacement_nm(&self) -> f64 {+ self.count as f64 * self.half_wave_nm()+ }++ pub fn zero(&mut self) {+ self.count = 0;+ }++ /// Process one sample (ADC code) at absolute pair index `pair`.+ /// Returns a fringe when an edge completes.+ #[inline]+ pub fn push(&mut self, code: u16, pair: u64) -> Option<Fringe> {+ let x = code as f64;+ if self.primed == 0 {+ self.lp.reset(x);+ for h in self.hist.iter_mut() {+ *h = x;+ }+ self.env_max = x;+ self.env_min = x;+ }+ self.primed += 1;+ let y = self.lp.run(x);+ self.filtered_last = y;+ // Envelope: jump to new extremes, relax toward each other otherwise.+ if y > self.env_max { self.env_max = y } else { self.env_max -= (self.env_max - y) * self.decay }+ if y < self.env_min { self.env_min = y } else { self.env_min += (y - self.env_min) * self.decay }+ let pp = self.env_max - self.env_min;++ let old = self.hist[self.hpos];+ self.hist[self.hpos] = y;+ self.hpos = (self.hpos + 1) % self.hist.len();+ if self.primed < (self.fs * 0.0005) as u64 {+ return None; // let the filter and envelope settle+ }+ let diff = y - old;+ let thr = self.p.threshold * pp;+ let armed = pp >= self.p.min_pp_codes;+ let mut out = None;+ if armed && diff.abs() > thr && (self.in_edge || pair.saturating_sub(self.last_edge) > self.refractory) {+ if !self.in_edge || diff.abs() > self.edge_best.abs() {+ self.edge_best = diff;+ self.edge_pair = pair;+ }+ self.in_edge = true;+ } else if self.in_edge {+ // A run above threshold ended: it is a candidate edge. At high fringe+ // rates the ramp between jumps also crosses the threshold, with the+ // opposite sign and a smaller size, so weigh candidates by size+ // squared and count only those that agree with the running sign.+ self.in_edge = false;+ self.last_edge = self.edge_pair;+ let rel = self.edge_best / pp.max(1.0);+ let w = rel * rel * rel.signum();+ self.jump_sign = if self.jump_sign == 0.0 { w } else { 0.4 * self.jump_sign + 0.6 * w };+ if self.edge_best.signum() == self.jump_sign.signum() {+ // The board's chain is inverting; a rising jump at the ADC means+ // the power fell sharply, which for this geometry is motion away.+ let mut dir: i8 = if self.edge_best < 0.0 { -1 } else { 1 };+ if self.p.invert {+ dir = -dir;+ }+ self.count += dir as i64;+ out = Some(Fringe { pair: self.edge_pair, dir });+ }+ }+ out+ }+}++/// Hann-windowed magnitude spectrum in dBFS, max-pooled into `bins` bins.+pub fn spectrum(samples: &[u16], bins: usize, planner: &mut FftPlanner<f64>) -> Vec<f32> {+ let n = samples.len();+ if n < 64 {+ return vec![];+ }+ let mean = samples.iter().map(|&v| v as f64).sum::<f64>() / n as f64;+ let mut buf: Vec<Complex<f64>> = samples+ .iter()+ .enumerate()+ .map(|(i, &v)| {+ let w = 0.5 - 0.5 * (2.0 * std::f64::consts::PI * i as f64 / (n as f64 - 1.0)).cos();+ Complex::new((v as f64 - mean) * w, 0.0)+ })+ .collect();+ planner.plan_fft_forward(n).process(&mut buf);+ let half = n / 2;+ // Full-scale sine (2048 codes amplitude) with a Hann window peaks at 2048 * n / 4.+ let fs_ref = 2048.0 * n as f64 / 4.0;+ let mut out = vec![-140.0f32; bins];+ for (k, c) in buf.iter().take(half).enumerate().skip(1) {+ let b = k * bins / half;+ let db = 20.0 * (c.norm() / fs_ref + 1e-12).log10();+ if (db as f32) > out[b] {+ out[b] = db as f32;+ }+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::sim::{Profile, SimParams, Simulator};++ fn run(p: SimParams, seconds: f64) -> (f64, f64, usize) {+ let mut sim = Simulator::new(p.clone());+ let mut det = Detector::new(DetectParams::default(), 250_000.0);+ let n = (seconds * 250_000.0) as usize;+ let ch = sim.generate(n);+ let mut events = 0;+ for (i, &c) in ch.ch1.iter().enumerate() {+ if det.push(c, i as u64).is_some() {+ events += 1;+ }+ }+ (det.displacement_nm(), *ch.truth_nm.last().unwrap(), events)+ }++ #[test]+ fn constant_velocity_counts_and_sign() {+ // 1 mm/s away for 0.2 s over a 400 um range: 200 um, ~608 fringes.+ let p = SimParams { profile: Profile::Constant, speed_um_s: 1000.0, range_um: 400.0, ..Default::default() };+ let (meas, truth, ev) = run(p, 0.2);+ assert!(truth > 190_000.0, "truth {truth}");+ let err = (meas - truth).abs();+ assert!(err < 2.0 * 329.0, "meas {meas} truth {truth} events {ev}");+ }++ #[test]+ fn sine_returns_to_zero() {+ let p = SimParams { profile: Profile::Sine, amp_um: 5.0, freq_hz: 2.0, ..Default::default() };+ let (meas, truth, _) = run(p, 1.0);+ assert!((meas - truth).abs() < 2.0 * 329.0, "meas {meas} truth {truth}");+ }+}+
software/dashboard/src/engine.rsadded+599@@ -0,0 +1,599 @@+// SPDX-License-Identifier: MIT+//! Acquisition and processing: one engine owns the sample rings, the detector,+//! the running displacement and the recorder. Sources (simulator or Pico over+//! USB serial) feed it chunks; the server reads display snapshots from it.++use crate::dsp::{spectrum, DetectParams, Detector, Fringe};+use crate::proto::{Decoder, Frame};+use crate::record::{Format, Meta, RecStatus, Recorder};+use crate::sim::{SimParams, Simulator, FS};+use rustfft::FftPlanner;+use serde::{Deserialize, Serialize};+use serde_json::{json, Value};+use std::collections::VecDeque;+use std::io::Read;+use std::sync::mpsc;+use std::sync::{Arc, Mutex};+use std::time::{Duration, Instant};++const RING_BITS: u32 = 19; // 524288 pairs, 2.1 s per channel+const RING: usize = 1 << RING_BITS;+const MASK: u64 = (RING as u64) - 1;+const DISP_STEP: u64 = 250; // one displacement point per millisecond+const DISP_KEEP: usize = 120_000; // two minutes+pub const MAX_COLS: usize = 1200;++#[derive(Clone, Debug, Serialize, Deserialize)]+#[serde(default)]+pub struct View {+ /// Width of the live channel plots, ms.+ pub window_ms: f64,+ pub paused: bool,+ /// When paused, how far back from the pause point the window ends, ms.+ pub pan_ms: f64,+ /// Span of the displacement trace, s.+ pub history_s: f64,+ /// Ask the open page to hold a screen wake lock (for unattended recordings).+ /// Off by default; turn it off afterwards so the display can rest.+ pub keep_awake: bool,+}++impl Default for View {+ fn default() -> Self {+ Self { window_ms: 10.0, paused: false, pan_ms: 0.0, history_s: 4.0, keep_awake: false }+ }+}++#[derive(Clone, Debug, Serialize, PartialEq, Eq)]+#[serde(tag = "kind", rename_all = "lowercase")]+pub enum SourceKind {+ Sim,+ Serial { port: String },+}++#[derive(Default, Serialize, Clone)]+pub struct LinkStats {+ pub connected: bool,+ pub frames: u64,+ pub crc_errors: u64,+ pub gaps: u64,+ pub dropped_bufs: u32,+ pub sync_lost: u32,+ pub info: String,+ pub error: String,+ pub rate_sps: f64,+}++pub struct Engine {+ pub source: SourceKind,+ /// Simulator parameters; the acquisition thread owns the Simulator itself+ /// and picks up changes by revision, so generation never holds this lock.+ pub sim_p: SimParams,+ pub sim_rev: u64,+ pub det: Detector,+ pub view: View,+ ch1: Vec<u16>,+ ch2: Vec<u16>,+ filt: Vec<f32>,+ pub head: u64,+ paused_head: u64,+ fringes: VecDeque<Fringe>,+ syncs: VecDeque<(u64, u8)>,+ sync_level: u8,+ disp: VecDeque<(f32, f32)>,+ disp_head: u64,+ next_disp_pair: u64,+ truth_now: f64,+ truth_zero: f64,+ have_truth: bool,+ pub rec: Option<Recorder>,+ pub last_rec: Option<RecStatus>,+ pub link: LinkStats,+ planner: FftPlanner<f64>,+ spec_cache: Value,+ spec_at: Instant,+ pub generation: u64,+ rate_t0: Instant,+ rate_p0: u64,+ pub rec_error: Option<String>,+}++impl Engine {+ pub fn new(sim: SimParams, det: DetectParams, view: View) -> Self {+ Self {+ source: SourceKind::Sim,+ sim_p: sim,+ sim_rev: 0,+ det: Detector::new(det, FS),+ view,+ ch1: vec![2048; RING],+ ch2: vec![2048; RING],+ filt: vec![2048.0; RING],+ head: 0,+ paused_head: 0,+ fringes: VecDeque::new(),+ syncs: VecDeque::new(),+ sync_level: 0,+ disp: VecDeque::new(),+ disp_head: 0,+ next_disp_pair: DISP_STEP,+ truth_now: 0.0,+ truth_zero: 0.0,+ have_truth: false,+ rec: None,+ last_rec: None,+ link: LinkStats::default(),+ planner: FftPlanner::new(),+ spec_cache: Value::Null,+ spec_at: Instant::now() - Duration::from_secs(10),+ generation: 0,+ rate_t0: Instant::now(),+ rate_p0: 0,+ rec_error: None,+ }+ }++ /// Forget all buffered data (used when the source changes).+ pub fn reset_stream(&mut self) {+ self.head = 0;+ self.paused_head = 0;+ self.fringes.clear();+ self.syncs.clear();+ self.disp.clear();+ self.disp_head = 0;+ self.next_disp_pair = DISP_STEP;+ self.det = Detector::new(self.det.p.clone(), FS);+ self.truth_zero = 0.0;+ self.truth_now = 0.0;+ self.link = LinkStats::default();+ self.generation += 1;+ for v in self.ch1.iter_mut().chain(self.ch2.iter_mut()) {+ *v = 2048;+ }+ }++ pub fn zero(&mut self) {+ self.det.zero();+ self.truth_zero = self.truth_now;+ self.disp.clear();+ self.disp_head = 0;+ }++ pub fn set_paused(&mut self, p: bool) {+ if p && !self.view.paused {+ self.paused_head = self.head;+ }+ if !p {+ self.view.pan_ms = 0.0;+ }+ self.view.paused = p;+ }++ /// Feed a contiguous chunk of pairs that starts at absolute pair `first`.+ pub fn ingest(&mut self, first: u64, ch1: &[u16], ch2: &[u16], truth_nm: Option<&[f64]>, sync: &[(u64, u8)]) {+ // A gap (dropped USB buffers) is filled with the last value so pair+ // indices stay aligned with the Pico's clock.+ if first > self.head && self.head > 0 {+ let fill = (first - self.head).min(RING as u64);+ let (l1, l2) = (self.ch1[((self.head - 1) & MASK) as usize], self.ch2[((self.head - 1) & MASK) as usize]);+ for k in 0..fill {+ let i = ((first - fill + k) & MASK) as usize;+ self.ch1[i] = l1;+ self.ch2[i] = l2;+ }+ }+ let level_at_start = self.sync_level;+ for &s in sync {+ self.syncs.push_back(s);+ self.sync_level = s.1;+ }+ let mut new_fr: Vec<(u64, i8)> = vec![];+ let rec_on = self.rec.is_some();+ let mut disp_col: Vec<f32> = if rec_on { Vec::with_capacity(ch1.len()) } else { vec![] };+ let half = self.det.half_wave_nm();+ for i in 0..ch1.len() {+ let p = first + i as u64;+ let idx = (p & MASK) as usize;+ self.ch1[idx] = ch1[i];+ self.ch2[idx] = ch2[i];+ if let Some(f) = self.det.push(ch1[i], p) {+ self.fringes.push_back(f);+ new_fr.push((f.pair, f.dir));+ }+ self.filt[idx] = self.det.filtered_last as f32;+ if let Some(t) = truth_nm {+ self.truth_now = t[i];+ self.have_truth = true;+ }+ if rec_on {+ disp_col.push((self.det.count as f64 * half) as f32);+ }+ if p + 1 >= self.next_disp_pair {+ let truth = if self.have_truth && truth_nm.is_some() { (self.truth_now - self.truth_zero) as f32 } else { f32::NAN };+ self.disp.push_back((self.det.displacement_nm() as f32, truth));+ self.disp_head += 1;+ if self.disp.len() > DISP_KEEP {+ self.disp.pop_front();+ }+ self.next_disp_pair += DISP_STEP;+ }+ }+ if truth_nm.is_none() {+ self.have_truth = false;+ }+ self.head = first + ch1.len() as u64;+ let oldest = self.head.saturating_sub(RING as u64);+ while self.fringes.front().is_some_and(|f| f.pair < oldest) {+ self.fringes.pop_front();+ }+ while self.syncs.front().is_some_and(|s| s.0 < oldest) {+ self.syncs.pop_front();+ }+ if let Some(r) = self.rec.as_mut() {+ // Truth is recorded relative to the same zero as the counted displacement.+ let tz = self.truth_zero;+ let truth_rel: Option<Vec<f64>> = truth_nm.map(|t| t.iter().map(|v| v - tz).collect());+ if let Err(e) = r.write(first, ch1, ch2, &disp_col, truth_rel.as_deref(), sync, &new_fr, level_at_start) {+ self.rec_error = Some(e.to_string());+ }+ if r.done() {+ let r = self.rec.take().unwrap();+ match r.finish() {+ Ok(st) => self.last_rec = Some(st),+ Err(e) => self.rec_error = Some(e),+ }+ }+ }+ let el = self.rate_t0.elapsed().as_secs_f64();+ if el > 1.0 {+ self.link.rate_sps = (self.head.saturating_sub(self.rate_p0)) as f64 * 2.0 / el;+ self.rate_t0 = Instant::now();+ self.rate_p0 = self.head;+ }+ }++ pub fn start_record(&mut self, dir: &std::path::Path, format: Format, seconds: Option<f64>) -> Result<String, String> {+ if self.rec.is_some() {+ return Err("already recording".into());+ }+ let meta = Meta {+ source: match &self.source {+ SourceKind::Sim => format!("simulator {}", serde_json::to_string(&self.sim_p).unwrap_or_default()),+ SourceKind::Serial { port } => format!("pico on {port}"),+ },+ wavelength_nm: self.det.p.wavelength_nm,+ lp_hz: self.det.p.lp_hz,+ threshold: self.det.p.threshold,+ };+ let r = Recorder::start(dir, format, seconds, self.head, meta).map_err(|e| e.to_string())?;+ let p = r.path.display().to_string();+ self.rec = Some(r);+ self.rec_error = None;+ Ok(p)+ }++ pub fn stop_record(&mut self) -> Result<RecStatus, String> {+ let r = self.rec.take().ok_or("not recording")?;+ let st = r.finish()?;+ self.last_rec = Some(st.clone());+ Ok(st)+ }++ fn velocity_um_s(&self, field: usize) -> f64 {+ // Least-squares slope over the last 40 ms of the 1 kHz displacement trace.+ let n = self.disp.len().min(40);+ if n < 5 {+ return 0.0;+ }+ let pts = self.disp.iter().skip(self.disp.len() - n);+ let (mut sx, mut sy, mut sxx, mut sxy) = (0.0, 0.0, 0.0, 0.0);+ for (i, d) in pts.enumerate() {+ let x = i as f64 * 1e-3;+ let y = if field == 0 { d.0 } else { d.1 } as f64;+ if y.is_nan() {+ return f64::NAN;+ }+ sx += x;+ sy += y;+ sxx += x * x;+ sxy += x * y;+ }+ let nf = n as f64;+ let slope = (nf * sxy - sx * sy) / (nf * sxx - sx * sx); // nm/s+ slope / 1000.0+ }++ pub fn readout(&self) -> Value {+ let disp = self.det.displacement_nm();+ let v = self.velocity_um_s(0);+ let half = self.det.half_wave_nm();+ let mut r = json!({+ "disp_nm": disp,+ "disp_um": disp / 1000.0,+ "vel_um_s": v,+ "count": self.det.count,+ "fringe_rate_hz": (v * 1000.0 / half).abs(),+ "dir": self.fringes.back().map(|f| f.dir).unwrap_or(0),+ "half_wave_nm": half,+ "seconds": self.head as f64 / FS,+ });+ if self.have_truth {+ let truth = self.truth_now - self.truth_zero;+ // RMS over the displacement history currently shown.+ let n = ((self.view.history_s * 1000.0) as usize).min(self.disp.len());+ let mut se = 0.0;+ let mut mx: f64 = 0.0;+ for d in self.disp.iter().skip(self.disp.len() - n) {+ let e = (d.0 - d.1) as f64;+ se += e * e;+ mx = mx.max(e.abs());+ }+ r["truth_nm"] = json!(truth);+ r["err_nm"] = json!(disp - truth);+ r["rms_err_nm"] = json!(if n > 0 { (se / n as f64).sqrt() } else { 0.0 });+ r["max_err_nm"] = json!(mx);+ r["truth_vel_um_s"] = json!(self.velocity_um_s(1));+ }+ r+ }++ /// Build one display frame.+ pub fn snapshot(&mut self, want_spec: bool) -> Value {+ let end_head = if self.view.paused { self.paused_head } else { self.head };+ let pan = if self.view.paused { (self.view.pan_ms * 250.0) as u64 } else { 0 };+ let max_w = (RING as u64) - 1000;+ let w = ((self.view.window_ms * 250.0) as u64).clamp(25, max_w);+ let end = end_head.saturating_sub(pan).max(w.min(end_head));+ let oldest = self.head.saturating_sub(max_w);+ let end = end.max(oldest + w).min(self.head);+ let start = end.saturating_sub(w);+ let cols = (w as usize).min(MAX_COLS);+ let mut mn1 = Vec::with_capacity(cols);+ let mut mx1 = Vec::with_capacity(cols);+ let mut mn2 = Vec::with_capacity(cols);+ let mut mx2 = Vec::with_capacity(cols);+ let mut f1 = Vec::with_capacity(cols);+ for c in 0..cols {+ let a = start + (c as u64) * w / cols as u64;+ let b = (start + ((c as u64) + 1) * w / cols as u64).max(a + 1);+ let (mut l1, mut h1, mut l2, mut h2, mut fs) = (u16::MAX, 0u16, u16::MAX, 0u16, 0f32);+ for p in a..b {+ let i = (p & MASK) as usize;+ l1 = l1.min(self.ch1[i]);+ h1 = h1.max(self.ch1[i]);+ l2 = l2.min(self.ch2[i]);+ h2 = h2.max(self.ch2[i]);+ fs += self.filt[i];+ }+ mn1.push(l1);+ mx1.push(h1);+ mn2.push(l2);+ mx2.push(h2);+ f1.push((fs / (b - a) as f32 * 10.0).round() / 10.0);+ }+ let scale = cols as f64 / w as f64;+ let fr: Vec<(f64, i8)> = self+ .fringes+ .iter()+ .filter(|f| f.pair >= start && f.pair < end)+ .map(|f| (((f.pair - start) as f64 * scale * 10.0).round() / 10.0, f.dir))+ .collect();+ let sy: Vec<(f64, u8)> = self+ .syncs+ .iter()+ .filter(|s| s.0 >= start && s.0 < end)+ .map(|s| (((s.0 - start) as f64 * scale * 10.0).round() / 10.0, s.1))+ .collect();+ // Displacement trace, decimated to at most 1000 points.+ let hist_n = ((self.view.history_s * 1000.0) as usize).min(self.disp.len());+ let skip = self.disp.len() - hist_n;+ let stride = hist_n.div_ceil(1000).max(1);+ let mut dm = vec![];+ let mut dt = vec![];+ for (k, d) in self.disp.iter().skip(skip).enumerate() {+ if k % stride == 0 || k + 1 == hist_n {+ dm.push((d.0 * 10.0).round() / 10.0);+ dt.push(if d.1.is_nan() { Value::Null } else { json!((d.1 * 10.0).round() / 10.0) });+ }+ }+ if want_spec || self.spec_at.elapsed() > Duration::from_millis(250) {+ self.spec_at = Instant::now();+ let n = 8192usize;+ if self.head >= n as u64 {+ let s = end - (n as u64).min(end);+ let a: Vec<u16> = (s..s + n as u64).map(|p| self.ch1[(p & MASK) as usize]).collect();+ let b: Vec<u16> = (s..s + n as u64).map(|p| self.ch2[(p & MASK) as usize]).collect();+ let sa = spectrum(&a, 512, &mut self.planner);+ let sb = spectrum(&b, 512, &mut self.planner);+ let lo = 512 * 300 / 125_000; // ignore below 300 Hz+ let (pk, _) = sa.iter().enumerate().skip(lo.max(1)).fold((0, -200.0f32), |acc, (i, &v)| if v > acc.1 { (i, v) } else { acc });+ let round = |v: &Vec<f32>| v.iter().map(|x| (x * 10.0).round() / 10.0).collect::<Vec<f32>>();+ self.spec_cache = json!({+ "f_max": FS / 2.0, "ch1": round(&sa), "ch2": round(&sb),+ "peak_hz": (pk as f64 + 0.5) * FS / 2.0 / 512.0,+ });+ }+ }+ json!({+ "head": self.head,+ "start": start,+ "win_ms": w as f64 / 250.0,+ "cols": cols,+ "paused": self.view.paused,+ "ch1": {"mn": mn1, "mx": mx1, "f": f1},+ "ch2": {"mn": mn2, "mx": mx2},+ "fr": fr,+ "sy": sy,+ "disp": {"dt_s": stride as f64 * 1e-3, "meas": dm, "truth": dt, "span_s": hist_n as f64 * 1e-3},+ "spec": self.spec_cache,+ "readout": self.readout(),+ "link": self.link,+ "rec": self.rec.as_ref().map(|r| serde_json::to_value(r.status()).unwrap()),+ "last_rec": self.last_rec.as_ref().map(|r| serde_json::to_value(r).unwrap()),+ "rec_error": self.rec_error,+ "sync_level": self.sync_level,+ })+ }+}++/// Run the acquisition loop forever on its own thread.+pub fn run_acquisition(engine: Arc<Mutex<Engine>>) {+ std::thread::Builder::new()+ .name("acquisition".into())+ .spawn(move || {+ let mut serial: Option<(String, mpsc::Receiver<SerialMsg>, Arc<std::sync::atomic::AtomicBool>)> = None;+ let mut gen = u64::MAX;+ let mut t0 = Instant::now();+ let mut sim_pairs: u64 = 0;+ let (p0, mut rev) = {+ let e = engine.lock().unwrap();+ (e.sim_p.clone(), e.sim_rev)+ };+ let mut sim = Simulator::new(p0);+ loop {+ let (kind, g, new_p) = {+ let e = engine.lock().unwrap();+ let np = if e.sim_rev != rev { rev = e.sim_rev; Some(e.sim_p.clone()) } else { None };+ (e.source.clone(), e.generation, np)+ };+ if let Some(p) = new_p {+ sim.set_params(p);+ }+ if g != gen {+ gen = g;+ t0 = Instant::now();+ sim_pairs = 0;+ if let Some((_, _, stop)) = serial.take() {+ stop.store(true, std::sync::atomic::Ordering::SeqCst);+ }+ if let SourceKind::Serial { port } = &kind {+ serial = Some(spawn_serial(port.clone()));+ }+ }+ match kind {+ SourceKind::Sim => {+ // Generate in real time, in chunks of at most 10 ms, outside the lock.+ let due = (t0.elapsed().as_secs_f64() * FS) as u64;+ if due < sim_pairs + 1000 {+ std::thread::sleep(Duration::from_millis(2));+ continue;+ }+ if due - sim_pairs > 50_000 {+ // More than 0.2 s behind (slow machine, sleep): run slower than+ // real time rather than locking everyone out to catch up.+ t0 = Instant::now();+ sim_pairs = 0;+ continue;+ }+ let n = ((due - sim_pairs) as usize).min(2_500);+ let ch = sim.generate(n);+ let base = sim.tick / 2 - n as u64;+ let mut e = engine.lock().unwrap();+ let first = e.head;+ 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;+ drop(e);+ sim_pairs += n as u64;+ }+ SourceKind::Serial { .. } => {+ let Some((_, rx, _)) = serial.as_ref() else {+ std::thread::sleep(Duration::from_millis(50));+ continue;+ };+ match rx.recv_timeout(Duration::from_millis(100)) {+ Ok(SerialMsg::Frames(frames, stats)) => {+ let mut e = engine.lock().unwrap();+ e.link.connected = true;+ e.link.frames = stats.frames;+ e.link.crc_errors = stats.crc_errors;+ e.link.gaps = stats.gaps;+ e.link.error.clear();+ let mut pending_sync = vec![];+ for f in frames {+ match f {+ Frame::Data { first_pair, ch1, ch2, .. } => {+ let sync: Vec<(u64, u8)> = std::mem::take(&mut pending_sync);+ e.ingest(first_pair, &ch1, &ch2, None, &sync);+ }+ Frame::Sync { pair, level, .. } => pending_sync.push((pair, level)),+ Frame::Status { dropped_bufs, sync_lost, .. } => {+ e.link.dropped_bufs = dropped_bufs;+ e.link.sync_lost = sync_lost;+ }+ Frame::Info { text, .. } => e.link.info = text,+ }+ }+ if !pending_sync.is_empty() {+ let h = e.head;+ e.ingest(h, &[], &[], None, &pending_sync);+ }+ }+ Ok(SerialMsg::Error(msg)) => {+ let mut e = engine.lock().unwrap();+ e.link.connected = false;+ e.link.error = msg;+ }+ Err(_) => {}+ }+ }+ }+ }+ })+ .expect("spawn acquisition thread");+}++pub enum SerialMsg {+ Frames(Vec<Frame>, crate::proto::DecodeStats),+ Error(String),+}++fn spawn_serial(port: String) -> (String, mpsc::Receiver<SerialMsg>, Arc<std::sync::atomic::AtomicBool>) {+ let (tx, rx) = mpsc::channel();+ let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));+ let stop2 = stop.clone();+ let p2 = port.clone();+ std::thread::spawn(move || {+ while !stop2.load(std::sync::atomic::Ordering::SeqCst) {+ let opened = serialport::new(&p2, 115_200).timeout(Duration::from_millis(200)).open();+ let mut sp = match opened {+ Ok(s) => s,+ Err(e) => {+ let _ = tx.send(SerialMsg::Error(format!("cannot open {p2}: {e}")));+ std::thread::sleep(Duration::from_secs(1));+ continue;+ }+ };+ // DTR starts the stream on the Pico.+ let _ = sp.write_data_terminal_ready(true);+ let _ = sp.write_all(b"start\n");+ let mut dec = Decoder::default();+ let mut buf = vec![0u8; 65536];+ let mut frames = vec![];+ let mut last_send = Instant::now();+ loop {+ if stop2.load(std::sync::atomic::Ordering::SeqCst) {+ let _ = sp.write_data_terminal_ready(false);+ return;+ }+ match sp.read(&mut buf) {+ Ok(0) => {}+ Ok(n) => dec.push(&buf[..n], &mut frames),+ Err(e) if e.kind() == std::io::ErrorKind::TimedOut => {}+ Err(e) => {+ let _ = tx.send(SerialMsg::Error(format!("read error on {p2}: {e}")));+ break;+ }+ }+ if !frames.is_empty() && last_send.elapsed() > Duration::from_millis(4) {+ let _ = tx.send(SerialMsg::Frames(std::mem::take(&mut frames), dec.stats.clone()));+ last_send = Instant::now();+ }+ }+ std::thread::sleep(Duration::from_millis(500));+ }+ });+ (port, rx, stop)+}++use std::io::Write as _;
software/dashboard/src/eval.rsadded+134@@ -0,0 +1,134 @@+// SPDX-License-Identifier: MIT+//! Offline accuracy evaluation: run the simulator and the detector together and+//! compare the counted displacement with the simulator's ground truth.++use crate::dsp::{DetectParams, Detector};+use crate::sim::{Profile, SimParams, Simulator, FS};+use serde::Serialize;++#[derive(Serialize, Clone)]+pub struct EvalRow {+ pub case: String,+ pub seconds: f64,+ pub c: f64,+ pub speed_note: String,+ pub lp_hz: f64,+ pub multimode: bool,+ pub noise: f64,+ /// Fringe boundaries the target actually crossed (sum of |d floor(L / (lambda/2))|).+ pub true_fringes: u64,+ pub detected: u64,+ /// Detected fringes whose direction disagreed with the true velocity.+ pub dir_errors: u64,+ pub final_err_nm: f64,+ pub rms_err_nm: f64,+ pub max_err_nm: f64,+ pub travel_um: f64,+}++pub fn run_case(name: &str, p: SimParams, d: DetectParams, seconds: f64) -> EvalRow {+ let half = p.wavelength_nm / 2.0;+ let mut sim = Simulator::new(p.clone());+ let mut det = Detector::new(DetectParams { wavelength_nm: p.wavelength_nm, ..d.clone() }, FS);+ let total = (seconds * FS) as usize;+ let chunk = 25_000;+ let mut done = 0usize;+ let mut truth: Vec<f64> = Vec::with_capacity(total);+ let mut events: Vec<(u64, i8)> = vec![];+ let (mut se, mut mx, mut ns) = (0.0f64, 0.0f64, 0u64);+ while done < total {+ let n = chunk.min(total - done);+ let ch = sim.generate(n);+ for i in 0..n {+ let pair = (done + i) as u64;+ if let Some(f) = det.push(ch.ch1[i], pair) {+ events.push((f.pair, f.dir));+ }+ if pair % 250 == 0 {+ let e = det.displacement_nm() - ch.truth_nm[i];+ se += e * e;+ mx = mx.max(e.abs());+ ns += 1;+ }+ }+ truth.extend_from_slice(&ch.truth_nm);+ done += n;+ }+ let mut true_fr = 0u64;+ let mut travel = 0.0;+ for w in truth.windows(2) {+ let a = (w[0] / half).floor() as i64;+ let b = (w[1] / half).floor() as i64;+ true_fr += (b - a).unsigned_abs();+ travel += (w[1] - w[0]).abs();+ }+ // Direction check against the true velocity over +-0.5 ms around each event.+ let mut dir_err = 0u64;+ for &(pair, dir) in &events {+ let i = pair as usize;+ let a = i.saturating_sub(125);+ let b = (i + 125).min(truth.len() - 1);+ let dv = truth[b] - truth[a];+ if dv.abs() > half * 0.25 && (dv > 0.0) != (dir > 0) {+ dir_err += 1;+ }+ }+ let speed_note = match p.profile {+ Profile::Constant => format!("{} um/s", p.speed_um_s),+ Profile::Sine => format!("{} um at {} Hz", p.amp_um, p.freq_hz),+ Profile::Step => format!("{} um steps", p.step_um),+ Profile::Hand => format!("{} um wander", p.jitter_um),+ Profile::Hold => "still".into(),+ };+ EvalRow {+ case: name.into(),+ seconds,+ c: p.c,+ speed_note,+ lp_hz: d.lp_hz,+ multimode: p.multimode,+ noise: p.noise,+ true_fringes: true_fr,+ detected: events.len() as u64,+ dir_errors: dir_err,+ final_err_nm: det.displacement_nm() - truth.last().copied().unwrap_or(0.0),+ rms_err_nm: if ns > 0 { (se / ns as f64).sqrt() } else { 0.0 },+ max_err_nm: mx,+ travel_um: travel / 1000.0,+ }+}++pub fn suite() -> Vec<EvalRow> {+ let base = SimParams::default();+ let d = DetectParams::default();+ let fast = DetectParams { lp_hz: 60_000.0, ..d.clone() };+ let cases: Vec<(&str, SimParams, DetectParams)> = vec![+ ("constant 1 mm/s", SimParams { profile: Profile::Constant, speed_um_s: 1000.0, range_um: 400.0, ..base.clone() }, d.clone()),+ ("constant 5 mm/s, 10 kHz LP", SimParams { profile: Profile::Constant, speed_um_s: 5000.0, range_um: 2000.0, ..base.clone() }, d.clone()),+ ("constant 5 mm/s, 60 kHz LP", SimParams { profile: Profile::Constant, speed_um_s: 5000.0, range_um: 2000.0, ..base.clone() }, fast.clone()),+ ("constant 10 mm/s, 60 kHz LP", SimParams { profile: Profile::Constant, speed_um_s: 10_000.0, range_um: 4000.0, ..base.clone() }, fast.clone()),+ ("sine 5 um, 2 Hz", SimParams { profile: Profile::Sine, amp_um: 5.0, freq_hz: 2.0, ..base.clone() }, d.clone()),+ ("sine 50 um, 5 Hz", SimParams { profile: Profile::Sine, amp_um: 50.0, freq_hz: 5.0, ..base.clone() }, d.clone()),+ ("step 10 um and return", SimParams { profile: Profile::Step, step_um: 10.0, ..base.clone() }, d.clone()),+ ("hand jitter", SimParams { profile: Profile::Hand, ..base.clone() }, d.clone()),+ ("very weak feedback C 0.1", SimParams { profile: Profile::Constant, c: 0.1, ..base.clone() }, d.clone()),+ ("weak feedback C 0.5", SimParams { profile: Profile::Constant, c: 0.5, ..base.clone() }, d.clone()),+ ("C 1.2", SimParams { profile: Profile::Constant, c: 1.2, ..base.clone() }, d.clone()),+ ("C 6", SimParams { profile: Profile::Constant, c: 6.0, ..base.clone() }, d.clone()),+ ("noise x10", SimParams { profile: Profile::Constant, noise: 10.0, ..base.clone() }, d.clone()),+ ("single mode, 2 mm/s over 3 mm", SimParams { profile: Profile::Constant, speed_um_s: 2000.0, range_um: 3000.0, ..base.clone() }, d.clone()),+ ("multimode, 2 mm/s over 3 mm", SimParams { profile: Profile::Constant, speed_um_s: 2000.0, range_um: 3000.0, multimode: true, ..base.clone() }, d.clone()),+ ];+ cases.into_iter().map(|(n, p, d)| run_case(n, p, d, 1.5)).collect()+}++pub fn markdown(rows: &[EvalRow]) -> String {+ let mut s = String::from("| Case | C | Motion | LP | True fringes | Detected | Direction errors | Final error | RMS error | Max error |\n|---|---|---|---|---|---|---|---|---|---|\n");+ for r in rows {+ s += &format!(+ "| {} | {} | {} | {:.0} kHz | {} | {} | {} | {:.0} nm | {:.0} nm | {:.0} nm |\n",+ r.case, r.c, r.speed_note, r.lp_hz / 1000.0, r.true_fringes, r.detected, r.dir_errors, r.final_err_nm, r.rms_err_nm, r.max_err_nm+ );+ }+ s+}
software/dashboard/src/main.rsadded+636@@ -0,0 +1,636 @@+// SPDX-License-Identifier: MIT+//! smi-dash: dashboard, simulator and CLI for a self-mixing laser interferometer.+//!+//! Every verb prints `OK:` or `ERROR:` first, then `Hint:` lines; `--json` gives+//! `{status, data, hints}`. The CLI talks to the running server over the same+//! HTTP endpoints the page uses, so anything the page can do, a command can do.++mod dsp;+mod engine;+mod eval;+mod proto;+mod record;+mod server;+mod sim;+mod util;++use clap::{Parser, Subcommand};+use serde_json::{json, Value};+use std::io::IsTerminal;+use std::sync::{Arc, Mutex};+use std::time::Instant;++#[derive(Parser)]+#[command(name = "smi-dash", version, about = "Self-mixing interferometer dashboard, simulator and CLI")]+struct Cli {+ /// Machine-readable output: {status, data, hints}.+ #[arg(long, global = true)]+ json: bool,+ /// Your AI thread's name (also ADOM_AI_THREAD). Each thread gets its own server.+ #[arg(long = "ai-thread", global = true, env = "ADOM_AI_THREAD")]+ ai_thread: Option<String>,+ /// Talk to the server on this port instead of looking it up.+ #[arg(long, global = true)]+ port: Option<u16>,+ #[command(subcommand)]+ cmd: Cmd,+}++#[derive(Subcommand)]+enum Cmd {+ /// Run the server in the foreground (`start` runs it in the background).+ Serve {+ /// Port number or "auto".+ #[arg(long = "listen", default_value = "auto")]+ listen: String,+ #[arg(long)]+ keep_alive: bool,+ #[arg(long)]+ ttl: Option<f64>,+ /// Start reading this serial port instead of the simulator.+ #[arg(long)]+ serial: Option<String>,+ },+ /// Start the server in the background, or reuse this thread's live one.+ Start {+ #[arg(long)]+ serial: Option<String>,+ },+ /// Open the dashboard in a Hydrogen webview tab.+ Show {+ /// wv (Hydrogen webview) or pup; default from settings.+ #[arg(long)]+ surface: Option<String>,+ },+ /// List running instances.+ Ls,+ /// Check the server answers.+ Health,+ /// Live readouts: displacement, velocity, fringes, link, recording.+ Status,+ /// Stop this thread's server.+ Stop,+ /// List serial ports; a Pico shows is_pico=true.+ Ports,+ /// Choose the data source: sim, or serial [--serial-port P].+ Source {+ kind: String,+ #[arg(long = "serial-port")]+ serial_port: Option<String>,+ },+ /// Change simulator parameters (only the ones given).+ Sim {+ /// constant | sine | step | hand | hold+ #[arg(long)]+ profile: Option<String>,+ #[arg(long = "speed-um-s")]+ speed_um_s: Option<f64>,+ #[arg(long = "range-um")]+ range_um: Option<f64>,+ #[arg(long = "amp-um")]+ amp_um: Option<f64>,+ #[arg(long = "freq-hz")]+ freq_hz: Option<f64>,+ #[arg(long = "step-um")]+ step_um: Option<f64>,+ #[arg(long = "jitter-um")]+ jitter_um: Option<f64>,+ /// Optical feedback parameter C (below 1 sine-like, above 1 sawtooth).+ #[arg(long)]+ c: Option<f64>,+ #[arg(long)]+ alpha: Option<f64>,+ /// Modulation depth of the laser power.+ #[arg(long)]+ m: Option<f64>,+ #[arg(long)]+ noise: Option<f64>,+ /// on | off: second longitudinal mode, beat nulls every 1.46 mm.+ #[arg(long)]+ multimode: Option<String>,+ #[arg(long = "wavelength-nm")]+ wavelength_nm: Option<f64>,+ },+ /// Fringe detector parameters.+ Detect {+ #[arg(long = "lp-hz")]+ lp_hz: Option<f64>,+ #[arg(long)]+ threshold: Option<f64>,+ /// on | off+ #[arg(long)]+ invert: Option<String>,+ },+ /// Display: window width, pause, pan, displacement history.+ View {+ #[arg(long = "window-ms")]+ window_ms: Option<f64>,+ #[arg(long)]+ pause: bool,+ #[arg(long)]+ resume: bool,+ #[arg(long = "pan-ms")]+ pan_ms: Option<f64>,+ #[arg(long = "history-s")]+ history_s: Option<f64>,+ /// on | off: the page holds a screen wake lock (for unattended recordings).+ #[arg(long = "keep-awake")]+ keep_awake: Option<String>,+ },+ /// Set the running displacement to zero.+ Zero,+ /// Record to CSV or HDF5: record start|stop|status.+ Record {+ action: String,+ #[arg(long)]+ format: Option<String>,+ #[arg(long)]+ seconds: Option<f64>,+ #[arg(long)]+ dir: Option<String>,+ },+ /// Drive the open page: ui toast TEXT | ui click SEL | ui reveal SEL | ui cursor SEL | ui reload.+ ///+ /// Selectors: #btn-pause #btn-zero #btn-record #btn-settings #src-sim #src-serial+ /// [data-profile=constant|sine|step|hand|hold] #mm-toggle #c-slider #speed-slider+ Ui {+ verb: String,+ arg: Option<String>,+ #[arg(long, default_value = "info")]+ kind: String,+ },+ /// Settings: `settings get` or `settings set key=value ...`.+ Settings {+ action: String,+ pairs: Vec<String>,+ },+ /// The page's console buffer.+ Console,+ /// Offline accuracy check against the simulator's ground truth (no server needed).+ Eval {+ /// Run the standard suite used for the published error table.+ #[arg(long)]+ suite: bool,+ #[arg(long, default_value = "constant")]+ profile: String,+ #[arg(long, default_value_t = 2.0)]+ seconds: f64,+ #[arg(long)]+ c: Option<f64>,+ #[arg(long = "speed-um-s")]+ speed_um_s: Option<f64>,+ #[arg(long)]+ multimode: bool,+ #[arg(long)]+ noise: Option<f64>,+ #[arg(long = "lp-hz")]+ lp_hz: Option<f64>,+ },+}++struct Out {+ json: bool,+ color: bool,+}++impl Out {+ fn ok(&self, msg: &str, data: Value, hints: &[String]) {+ if self.json {+ println!("{}", json!({"status": "ok", "message": msg, "data": data, "hints": hints}));+ } else {+ let tag = if self.color { "\x1b[32mOK:\x1b[0m" } else { "OK:" };+ println!("{tag} {msg}");+ for h in hints {+ println!("Hint: {h}");+ }+ }+ }+ fn err(&self, msg: &str, hints: &[String]) -> ! {+ if self.json {+ println!("{}", json!({"status": "error", "message": msg, "hints": hints}));+ } else {+ let tag = if self.color { "\x1b[31mERROR:\x1b[0m" } else { "ERROR:" };+ println!("{tag} {msg}");+ for h in hints {+ println!("Hint: {h}");+ }+ }+ std::process::exit(1)+ }+}++fn thread_name(cli: &Cli) -> String {+ cli.ai_thread.clone().unwrap_or_else(|| "default".into())+}++fn find_port(cli: &Cli, out: &Out) -> u16 {+ if let Some(p) = cli.port {+ return p;+ }+ let me = util::slug(&thread_name(cli));+ let live = util::instances();+ if let Some(v) = live.iter().find(|v| util::slug(v["thread"].as_str().unwrap_or("")) == me) {+ return v["port"].as_u64().unwrap_or(0) as u16;+ }+ if live.len() == 1 {+ return live[0]["port"].as_u64().unwrap_or(0) as u16;+ }+ if live.is_empty() {+ out.err("no smi-dash server is running", &["Start one with `smi-dash start`, then `smi-dash show`".into()]);+ }+ out.err(+ "several smi-dash servers are running and none belongs to this thread",+ &["Pick one with `--port <PORT>` (see `smi-dash ls`) or pass `--ai-thread <name>`".into()],+ )+}++fn call(out: &Out, port: u16, method: &str, path: &str, body: Option<Value>) -> Value {+ let url = format!("http://127.0.0.1:{port}{path}");+ let ua = format!("smi-dash-cli/{}", env!("CARGO_PKG_VERSION"));+ let req = ureq::request(method, &url).set("User-Agent", &ua).timeout(std::time::Duration::from_secs(10));+ let res = match body {+ Some(b) => req.send_json(b),+ None => req.call(),+ };+ match res {+ Ok(r) => r.into_json::<Value>().unwrap_or(Value::Null),+ Err(ureq::Error::Status(_, r)) => {+ let v: Value = r.into_json().unwrap_or(Value::Null);+ let hints: Vec<String> = v["hints"].as_array().map(|a| a.iter().filter_map(|h| h.as_str().map(String::from)).collect()).unwrap_or_default();+ out.err(v["error"].as_str().unwrap_or("request refused"), &hints)+ }+ Err(e) => out.err(&format!("cannot reach the server on port {port}: {e}"), &["Start it with `smi-dash start`; list instances with `smi-dash ls`".into()]),+ }+}++fn hints_of(v: &Value) -> Vec<String> {+ v["hints"].as_array().map(|a| a.iter().filter_map(|h| h.as_str().map(String::from)).collect()).unwrap_or_default()+}++fn onoff(s: &str, out: &Out) -> bool {+ match s {+ "on" | "true" | "1" | "yes" => true,+ "off" | "false" | "0" | "no" => false,+ _ => out.err(&format!("expected on or off, got '{s}'"), &["Use `on` or `off`, e.g. `--multimode on`".into()]),+ }+}++fn fmt_disp(nm: f64) -> String {+ if nm.abs() >= 10_000.0 { format!("{:.3} um", nm / 1000.0) } else { format!("{nm:.0} nm") }+}++fn main() {+ let cli = Cli::parse();+ let out = Out { json: cli.json, color: std::io::stdout().is_terminal() };+ match &cli.cmd {+ Cmd::Serve { listen, keep_alive, ttl, serial } => serve(&cli, &out, listen, *keep_alive, *ttl, serial.clone()),+ Cmd::Start { serial } => start(&cli, &out, serial.clone()),+ Cmd::Show { surface } => show(&cli, &out, surface.clone()),+ Cmd::Ls => {+ let live = util::instances();+ let mut lines = vec![];+ for v in &live {+ let ver = v["version"].as_str().unwrap_or("?");+ let drift = if ver != env!("CARGO_PKG_VERSION") { format!(" (WARN: runs {ver}, this binary is {}; restart it)", env!("CARGO_PKG_VERSION")) } else { String::new() };+ lines.push(format!("port {} thread '{}' pid {} since {}{}", v["port"], v["thread"].as_str().unwrap_or(""), v["pid"], v["startedAt"].as_str().unwrap_or(""), drift));+ }+ let msg = if live.is_empty() { "no instances running".to_string() } else { format!("{} instance(s)\n{}", live.len(), lines.join("\n")) };+ let hints: Vec<String> = if live.is_empty() { vec!["Start one with `smi-dash start`".into()] } else { vec![] };+ out.ok(&msg, json!(live), &hints);+ }+ Cmd::Health => {+ let port = find_port(&cli, &out);+ let v = call(&out, port, "GET", "/health", None);+ out.ok(&format!("smi-dash {} on port {port}, source {}", v["data"]["version"].as_str().unwrap_or("?"), v["data"]["source"]["kind"].as_str().unwrap_or("?")), v["data"].clone(), &[]);+ }+ Cmd::Status => {+ let port = find_port(&cli, &out);+ let v = call(&out, port, "GET", "/frame", None);+ let d = &v["data"];+ let r = &d["readout"];+ let mut msg = format!(+ "displacement {} ({} fringes), velocity {:.1} um/s, fringe rate {:.0} Hz, {:.1} s acquired",+ fmt_disp(r["disp_nm"].as_f64().unwrap_or(0.0)),+ r["count"],+ r["vel_um_s"].as_f64().unwrap_or(0.0),+ r["fringe_rate_hz"].as_f64().unwrap_or(0.0),+ r["seconds"].as_f64().unwrap_or(0.0)+ );+ if let Some(t) = r["truth_nm"].as_f64() {+ msg += &format!("; simulator truth {}, error {:.0} nm, rms error {:.0} nm over the trace", fmt_disp(t), r["err_nm"].as_f64().unwrap_or(0.0), r["rms_err_nm"].as_f64().unwrap_or(0.0));+ }+ if d["rec"].is_object() {+ msg += &format!("; recording {:.1} s to {}", d["rec"]["seconds"].as_f64().unwrap_or(0.0), d["rec"]["path"].as_str().unwrap_or(""));+ }+ let l = &d["link"];+ if !l["error"].as_str().unwrap_or("").is_empty() {+ msg += &format!("; link error: {}", l["error"].as_str().unwrap_or(""));+ }+ let mut d2 = d.clone();+ if let Some(o) = d2.as_object_mut() {+ for k in ["ch1", "ch2", "disp", "spec"] {+ o.remove(k);+ }+ }+ out.ok(&msg, d2, &[]);+ }+ Cmd::Stop => {+ let port = find_port(&cli, &out);+ call(&out, port, "POST", "/shutdown", Some(json!({})));+ out.ok(&format!("stopped the server on port {port}"), json!({}), &[]);+ }+ Cmd::Ports => {+ let p = util::list_ports();+ let msg = if p.is_empty() { "no serial ports found".to_string() } else { p.iter().map(|x| format!("{}{}", x["port"].as_str().unwrap_or(""), if x["is_pico"].as_bool() == Some(true) { " (Raspberry Pi Pico)" } else { "" })).collect::<Vec<_>>().join(", ") };+ let hints: Vec<String> = if p.iter().any(|x| x["is_pico"].as_bool() == Some(true)) {+ vec!["Use it with `smi-dash source serial --serial-port <PORT>`".into()]+ } else {+ vec![if cfg!(windows) {+ "No Pico seen. Flash smi_pico.uf2 (hold BOOTSEL, plug in, copy the file) and plug it in; it appears as a COM port".into()+ } else {+ "No Pico seen. Under WSL, attach it from Windows with `usbipd attach --wsl --busid <BUSID>`, or run the Windows build".into()+ }]+ };+ out.ok(&msg, json!(p), &hints);+ }+ Cmd::Source { kind, serial_port } => {+ let port = find_port(&cli, &out);+ let mut b = json!({"kind": kind});+ if let Some(sp) = serial_port {+ b["port"] = json!(sp);+ }+ let v = call(&out, port, "POST", "/source", Some(b));+ out.ok(&format!("source is now {}", kind), v["data"].clone(), &hints_of(&v));+ }+ Cmd::Sim { profile, speed_um_s, range_um, amp_um, freq_hz, step_um, jitter_um, c, alpha, m, noise, multimode, wavelength_nm } => {+ let port = find_port(&cli, &out);+ let mut b = json!({});+ if let Some(p) = profile {+ if sim::Profile::parse(p).is_none() {+ out.err(&format!("unknown profile '{p}'"), &[format!("Valid profiles: {}", sim::Profile::ALL.join(", "))]);+ }+ b["profile"] = json!(p);+ }+ for (k, v) in [("speed_um_s", speed_um_s), ("range_um", range_um), ("amp_um", amp_um), ("freq_hz", freq_hz), ("step_um", step_um), ("jitter_um", jitter_um), ("c", c), ("alpha", alpha), ("m", m), ("noise", noise), ("wavelength_nm", wavelength_nm)] {+ if let Some(x) = v {+ b[k] = json!(x);+ }+ }+ if let Some(mm) = multimode {+ b["multimode"] = json!(onoff(mm, &out));+ }+ let v = call(&out, port, "POST", "/sim", Some(b));+ let d = &v["data"];+ out.ok(&format!("simulator: profile {}, C {}, multimode {}", d["profile"].as_str().unwrap_or("?"), d["c"], d["multimode"]), d.clone(), &[]);+ }+ Cmd::Detect { lp_hz, threshold, invert } => {+ let port = find_port(&cli, &out);+ let mut b = json!({});+ if let Some(x) = lp_hz { b["lp_hz"] = json!(x) }+ if let Some(x) = threshold { b["threshold"] = json!(x) }+ if let Some(x) = invert { b["invert"] = json!(onoff(x, &out)) }+ let v = call(&out, port, "POST", "/detect", Some(b));+ out.ok("detector updated", v["data"].clone(), &[]);+ }+ Cmd::View { window_ms, pause, resume, pan_ms, history_s, keep_awake } => {+ let port = find_port(&cli, &out);+ let mut b = json!({});+ if let Some(x) = window_ms { b["window_ms"] = json!(x) }+ if let Some(x) = pan_ms { b["pan_ms"] = json!(x) }+ if let Some(x) = history_s { b["history_s"] = json!(x) }+ if *pause { b["paused"] = json!(true) }+ if *resume { b["paused"] = json!(false) }+ if let Some(k) = keep_awake { b["keep_awake"] = json!(onoff(k, &out)) }+ let v = call(&out, port, "POST", "/view", Some(b));+ out.ok("view updated", v["data"].clone(), &[]);+ }+ Cmd::Zero => {+ let port = find_port(&cli, &out);+ call(&out, port, "POST", "/zero", Some(json!({})));+ out.ok("displacement set to zero", json!({}), &[]);+ }+ Cmd::Record { action, format, seconds, dir } => {+ let port = find_port(&cli, &out);+ match action.as_str() {+ "start" => {+ let mut b = json!({});+ if let Some(f) = format { b["format"] = json!(f) }+ if let Some(s) = seconds { b["seconds"] = json!(s) }+ if let Some(d) = dir { b["dir"] = json!(d) }+ let v = call(&out, port, "POST", "/record/start", Some(b));+ let mut h = hints_of(&v);+ if let Some(s) = seconds {+ h.insert(0, format!("It stops by itself after {s} s; the file is complete when `smi-dash status` no longer shows recording"));+ }+ out.ok(&format!("recording to {}", v["data"]["path"].as_str().unwrap_or("")), v["data"].clone(), &h);+ }+ "stop" => {+ let v = call(&out, port, "POST", "/record/stop", Some(json!({})));+ out.ok(&format!("saved {:.2} s to {}", v["data"]["seconds"].as_f64().unwrap_or(0.0), v["data"]["path"].as_str().unwrap_or("")), v["data"].clone(), &[]);+ }+ "status" => {+ let v = call(&out, port, "GET", "/frame", None);+ let d = &v["data"];+ if d["rec"].is_object() {+ out.ok(&format!("recording {:.1} s to {}", d["rec"]["seconds"].as_f64().unwrap_or(0.0), d["rec"]["path"].as_str().unwrap_or("")), d["rec"].clone(), &[]);+ } else {+ out.ok("not recording", d["last_rec"].clone(), &["Start with `smi-dash record start --format csv --seconds 5`".into()]);+ }+ }+ _ => out.err(&format!("unknown record action '{action}'"), &["Use `smi-dash record start|stop|status`".into()]),+ }+ }+ Cmd::Ui { verb, arg, kind } => {+ let port = find_port(&cli, &out);+ let body = match verb.as_str() {+ "toast" => json!({"text": arg.clone().unwrap_or_default(), "kind": kind}),+ "reload" => json!({}),+ _ => match arg {+ Some(sel) => json!({"selector": sel}),+ None => out.err(&format!("ui {verb} needs a selector"), &[format!("e.g. `smi-dash ui {verb} '#btn-zero'`")]),+ },+ };+ let v = call(&out, port, "POST", &format!("/ui/{verb}"), Some(body));+ out.ok(&format!("ui {verb} sent to {} page(s)", v["data"]["delivered_to"]), v["data"].clone(), &hints_of(&v));+ }+ Cmd::Settings { action, pairs } => {+ let port = find_port(&cli, &out);+ match action.as_str() {+ "get" => {+ let v = call(&out, port, "GET", "/settings", None);+ out.ok(&serde_json::to_string_pretty(&v["data"]["settings"]).unwrap(), v["data"].clone(), &[]);+ }+ "set" => {+ let mut b = json!({});+ for kv in pairs {+ let Some((k, val)) = kv.split_once('=') else {+ out.err(&format!("expected key=value, got '{kv}'"), &["e.g. `smi-dash settings set fps=30 record_format=h5`".into()]);+ };+ b[k] = serde_json::from_str(val).unwrap_or(json!(val));+ }+ let v = call(&out, port, "POST", "/settings", Some(b));+ out.ok("settings saved", v["data"].clone(), &[]);+ }+ _ => out.err(&format!("unknown settings action '{action}'"), &["Use `smi-dash settings get` or `smi-dash settings set key=value`".into()]),+ }+ }+ Cmd::Console => {+ let port = find_port(&cli, &out);+ let v = call(&out, port, "GET", "/console", None);+ let lines: Vec<String> = v["data"].as_array().map(|a| a.iter().map(|e| format!("[{}] {}", e["level"].as_str().unwrap_or(""), e["text"].as_str().unwrap_or(""))).collect()).unwrap_or_default();+ out.ok(&format!("{} console lines\n{}", lines.len(), lines.join("\n")), v["data"].clone(), &[]);+ }+ Cmd::Eval { suite, profile, seconds, c, speed_um_s, multimode, noise, lp_hz } => {+ if *suite {+ let t = Instant::now();+ let rows = eval::suite();+ let table = eval::markdown(&rows);+ out.ok(&format!("suite of {} cases in {:.1} s\n{}", rows.len(), t.elapsed().as_secs_f64(), table), json!(rows), &[]);+ } else {+ let Some(pr) = sim::Profile::parse(profile) else {+ out.err(&format!("unknown profile '{profile}'"), &[format!("Valid profiles: {}", sim::Profile::ALL.join(", "))]);+ };+ let mut p = sim::SimParams { profile: pr, multimode: *multimode, ..Default::default() };+ if let Some(x) = c { p.c = *x }+ if let Some(x) = speed_um_s { p.speed_um_s = *x }+ if let Some(x) = noise { p.noise = *x }+ let mut d = dsp::DetectParams::default();+ if let Some(x) = lp_hz { d.lp_hz = *x }+ let r = eval::run_case("custom", p, d, *seconds);+ out.ok(&eval::markdown(std::slice::from_ref(&r)), json!(r), &[]);+ }+ }+ }+}++fn serve(cli: &Cli, out: &Out, listen: &str, keep_alive: bool, ttl: Option<f64>, serial: Option<String>) {+ let thread = thread_name(cli);+ let mut settings = util::load_settings();+ if keep_alive {+ settings.keep_alive = true;+ }+ if let Some(t) = ttl {+ settings.ttl_hours = t;+ }+ // Restore this thread's snapshot (simulator, view, source) if any.+ let snap = util::read_json(&util::snapshot_path(&thread));+ let simp: sim::SimParams = snap.as_ref().and_then(|s| serde_json::from_value(s["sim"].clone()).ok()).unwrap_or_default();+ let view: engine::View = snap.as_ref().and_then(|s| serde_json::from_value(s["view"].clone()).ok()).unwrap_or_default();+ let mut view = view;+ view.paused = false;+ let mut eng = engine::Engine::new(simp, settings.detect.clone(), view);+ if let Some(sp) = serial {+ eng.source = engine::SourceKind::Serial { port: sp };+ }+ let rt = tokio::runtime::Builder::new_multi_thread().enable_all().build().unwrap();+ rt.block_on(async move {+ // auto: reuse this thread's last port when free, so open tabs keep working.+ let last = util::read_json(&util::base_dir().join("ports").join(format!("{}.json", util::slug(&thread)))).and_then(|v| v["port"].as_u64());+ let mut addr = if listen == "auto" { "127.0.0.1:0".to_string() } else { format!("127.0.0.1:{listen}") };+ if listen == "auto" {+ if let Some(p) = last {+ if std::net::TcpListener::bind(("127.0.0.1", p as u16)).is_ok() {+ addr = format!("127.0.0.1:{p}");+ }+ }+ }+ let listener = match tokio::net::TcpListener::bind(&addr).await {+ Ok(l) => l,+ Err(e) => out.err(&format!("cannot listen on {addr}: {e}"), &["Use `--listen auto` to pick a free port".into()]),+ };+ let port = listener.local_addr().unwrap().port();+ util::register(&thread, port);+ let _ = util::write_json(&util::base_dir().join("ports").join(format!("{}.json", util::slug(&thread))), &json!({"port": port}));+ let (tx, _) = tokio::sync::broadcast::channel(256);+ let app = Arc::new(server::App {+ engine: Arc::new(Mutex::new(eng)),+ settings: Mutex::new(settings),+ tx,+ console: Mutex::new(Default::default()),+ last_activity: Mutex::new(Instant::now()),+ thread: thread.clone(),+ port,+ started: chrono::Local::now(),+ });+ out.ok(+ &format!("serving on http://127.0.0.1:{port}/ (thread '{thread}'{})", if snap.is_some() { ", restored snapshot" } else { "" }),+ json!({"port": port, "thread": thread}),+ &["Open it with `smi-dash show`".into()],+ );+ let t2 = thread.clone();+ tokio::spawn(async move {+ let _ = tokio::signal::ctrl_c().await;+ util::deregister(&t2);+ std::process::exit(0);+ });+ server::serve(app, listener).await;+ });+}++fn start(cli: &Cli, out: &Out, serial: Option<String>) {+ let thread = thread_name(cli);+ let me = util::slug(&thread);+ if let Some(v) = util::instances().into_iter().find(|v| util::slug(v["thread"].as_str().unwrap_or("")) == me) {+ out.ok(+ &format!("already running on port {} (thread '{}', since {}). Use that instance.", v["port"], thread, v["startedAt"].as_str().unwrap_or("")),+ v.clone(),+ &["Open it with `smi-dash show`".into()],+ );+ return;+ }+ let exe = std::env::current_exe().unwrap();+ let log = util::base_dir().join("logs").join(format!("{me}.log"));+ let _ = std::fs::create_dir_all(log.parent().unwrap());+ let logf = std::fs::File::create(&log).unwrap();+ let mut cmd = std::process::Command::new(exe);+ cmd.arg("serve").arg("--ai-thread").arg(&thread);+ if let Some(s) = serial {+ cmd.arg("--serial").arg(s);+ }+ cmd.stdout(logf.try_clone().unwrap()).stderr(logf).stdin(std::process::Stdio::null());+ #[cfg(unix)]+ {+ use std::os::unix::process::CommandExt;+ cmd.process_group(0);+ }+ if let Err(e) = cmd.spawn() {+ out.err(&format!("cannot start the server: {e}"), &["Run it in the foreground to see why: `smi-dash serve`".into()]);+ }+ let t = Instant::now();+ while t.elapsed().as_secs_f64() < 8.0 {+ std::thread::sleep(std::time::Duration::from_millis(150));+ if let Some(v) = util::instances().into_iter().find(|v| util::slug(v["thread"].as_str().unwrap_or("")) == me) {+ out.ok(&format!("started on http://127.0.0.1:{}/ (thread '{}')", v["port"], thread), v.clone(), &["Open it with `smi-dash show`".into(), format!("Server log: {}", log.display())]);+ return;+ }+ }+ out.err("the server did not come up within 8 s", &[format!("Read its log: {}", log.display())]);+}++fn show(cli: &Cli, out: &Out, surface: Option<String>) {+ let port = find_port(cli, out);+ let v = call(out, port, "GET", "/settings", None);+ let surface = surface.unwrap_or_else(|| v["data"]["settings"]["surface"].as_str().unwrap_or("wv").to_string());+ let url = format!("http://localhost:{port}/");+ match surface.as_str() {+ "wv" => {+ let thread = thread_name(cli);+ let r = std::process::Command::new("adom-cli")+ .args(["hydrogen", "webview", "open-or-refresh", "--name", "Interferometer", "--url", &url, "--ai-thread", &thread, "--reason", "SMI dashboard"])+ .output();+ match r {+ Ok(o) if o.status.success() => out.ok(&format!("opened {url} in the Hydrogen webview tab 'Interferometer'"), json!({"url": url}), &["Drive it with `smi-dash ui toast \"hello\"`; read its console with `smi-dash console`".into()]),+ Ok(o) => out.err(&format!("adom-cli refused: {}", String::from_utf8_lossy(&o.stdout).trim()), &["Open it on pup instead: `smi-dash show --surface pup`".into()]),+ Err(e) => out.err(&format!("adom-cli not found ({e})"), &[format!("Open {url} in a browser, or install the Adom CLI")]),+ }+ }+ "pup" => {+ let r = std::process::Command::new("adom-bridge").args(["pup_open_tab", &json!({"url": url}).to_string()]).output();+ match r {+ Ok(o) if o.status.success() => out.ok(&format!("opened {url} in pup"), json!({"url": url}), &[]),+ _ => out.err("adom-bridge could not open pup", &["Use the Hydrogen webview: `smi-dash show --surface wv`".into()]),+ }+ }+ s => out.err(&format!("unknown surface '{s}'"), &["Valid surfaces: wv, pup".into()]),+ }+}
software/dashboard/src/proto.rsadded+235@@ -0,0 +1,235 @@+// SPDX-License-Identifier: MIT+//! Decoder for the Pico firmware's framed stream (see firmware/src/smi_frame.h).++pub const T_DATA: u8 = 1;+pub const T_SYNC: u8 = 2;+pub const T_STATUS: u8 = 3;+pub const T_INFO: u8 = 4;+const HDR: usize = 8;+const BLOCK: usize = 64;++pub fn crc16(p: &[u8]) -> u16 {+ let mut crc: u16 = 0xFFFF;+ for &b in p {+ crc ^= (b as u16) << 8;+ for _ in 0..8 {+ crc = if crc & 0x8000 != 0 { (crc << 1) ^ 0x1021 } else { crc << 1 };+ }+ }+ crc+}++#[derive(Debug, Clone, PartialEq)]+pub enum Frame {+ Data { seq: u16, first_pair: u64, t_us: u32, ch1: Vec<u16>, ch2: Vec<u16> },+ Sync { seq: u16, pair: u64, t_us: u32, level: u8 },+ Status { seq: u16, pairs: u64, dropped_bufs: u32, sync_lost: u32, total_sps: u32, t_us: u32 },+ Info { seq: u16, text: String },+}++fn u16le(b: &[u8]) -> u16 {+ u16::from_le_bytes([b[0], b[1]])+}+fn u32le(b: &[u8]) -> u32 {+ u32::from_le_bytes([b[0], b[1], b[2], b[3]])+}+fn u64le(b: &[u8]) -> u64 {+ let mut a = [0u8; 8];+ a.copy_from_slice(&b[..8]);+ u64::from_le_bytes(a)+}++/// Unpack one 64-sample block. Returns bytes consumed.+pub fn unpack_block(src: &[u8], out: &mut [u16; BLOCK]) -> Option<usize> {+ if src.len() < 2 {+ return None;+ }+ let head = u16le(src);+ let code = (head >> 12) as usize;+ out[0] = head & 0x0FFF;+ if code > 12 && code != 15 {+ return None;+ }+ let w = if code == 15 { 12 } else { code };+ let need = 2 + (63 * w + 7) / 8;+ if src.len() < need {+ return None;+ }+ let mut acc: u32 = 0;+ let mut nb = 0usize;+ let mut o = 2usize;+ let mut prev = out[0] as i32;+ for i in 1..BLOCK {+ let mut z = 0u32;+ if w > 0 {+ while nb < w {+ acc |= (src[o] as u32) << nb;+ o += 1;+ nb += 8;+ }+ z = acc & ((1u32 << w) - 1);+ acc >>= w;+ nb -= w;+ }+ if code == 15 {+ out[i] = z as u16;+ } else {+ prev += ((z >> 1) as i32) ^ -((z & 1) as i32);+ if !(0..=4095).contains(&prev) {+ return None;+ }+ out[i] = prev as u16;+ }+ }+ Some(need)+}++#[derive(Default, Debug, Clone)]+pub struct DecodeStats {+ pub frames: u64,+ pub crc_errors: u64,+ pub resync_bytes: u64,+ pub gaps: u64,+}++/// Incremental decoder: feed bytes, get frames. Resynchronises on the 0xA5 0x5A+/// sync word and drops any frame whose CRC fails.+#[derive(Default)]+pub struct Decoder {+ buf: Vec<u8>,+ pub stats: DecodeStats,+ next_pair: Option<u64>,+}++impl Decoder {+ pub fn push(&mut self, bytes: &[u8], out: &mut Vec<Frame>) {+ self.buf.extend_from_slice(bytes);+ let mut i = 0usize;+ loop {+ // Find the sync word.+ while i + 1 < self.buf.len() && !(self.buf[i] == 0xA5 && self.buf[i + 1] == 0x5A) {+ i += 1;+ self.stats.resync_bytes += 1;+ }+ if i + HDR > self.buf.len() {+ break;+ }+ let len = u16le(&self.buf[i + 4..]) as usize;+ if len > 8192 {+ i += 1;+ self.stats.resync_bytes += 1;+ continue;+ }+ let total = HDR + len + 2;+ if i + total > self.buf.len() {+ break;+ }+ let f = &self.buf[i..i + total];+ let crc = u16le(&f[HDR + len..]);+ if crc16(&f[2..HDR + len]) != crc {+ self.stats.crc_errors += 1;+ i += 1;+ continue;+ }+ if let Some(fr) = parse(f[2], u16le(&f[6..]), &f[HDR..HDR + len]) {+ if let Frame::Data { first_pair, ch1, .. } = &fr {+ if let Some(np) = self.next_pair {+ if *first_pair != np {+ self.stats.gaps += 1;+ }+ }+ self.next_pair = Some(first_pair + ch1.len() as u64);+ }+ self.stats.frames += 1;+ out.push(fr);+ } else {+ self.stats.crc_errors += 1;+ }+ i += total;+ }+ self.buf.drain(..i);+ }+}++fn parse(ty: u8, seq: u16, p: &[u8]) -> Option<Frame> {+ match ty {+ T_DATA => {+ if p.len() < 13 {+ return None;+ }+ let first_pair = u64le(p);+ let t_us = u32le(&p[8..]);+ let groups = p[12] as usize;+ let mut ch1 = Vec::with_capacity(groups * BLOCK);+ let mut ch2 = Vec::with_capacity(groups * BLOCK);+ let mut o = 13;+ let mut blk = [0u16; BLOCK];+ for _ in 0..groups {+ o += unpack_block(&p[o..], &mut blk)?;+ ch1.extend_from_slice(&blk);+ o += unpack_block(&p[o..], &mut blk)?;+ ch2.extend_from_slice(&blk);+ }+ Some(Frame::Data { seq, first_pair, t_us, ch1, ch2 })+ }+ T_SYNC if p.len() >= 13 => Some(Frame::Sync { seq, pair: u64le(p), t_us: u32le(&p[8..]), level: p[12] }),+ T_STATUS if p.len() >= 24 => Some(Frame::Status {+ seq,+ pairs: u64le(p),+ dropped_bufs: u32le(&p[8..]),+ sync_lost: u32le(&p[12..]),+ total_sps: u32le(&p[16..]),+ t_us: u32le(&p[20..]),+ }),+ T_INFO => Some(Frame::Info { seq, text: String::from_utf8_lossy(p).into_owned() }),+ _ => None,+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn crc_check_value() {+ assert_eq!(crc16(b"123456789"), 0x29B1);+ }++ /// vectors.bin is written by the firmware's own C packer (firmware/test/test_pack.c).+ #[test]+ fn decodes_firmware_vectors() {+ let bytes = include_bytes!("../../firmware/test/vectors.bin");+ let mut d = Decoder::default();+ let mut out = vec![];+ // Feed in awkward slices, with garbage in front, to exercise resync.+ let mut junk = vec![0x5A, 0xA5, 0x00, 0x13];+ junk.extend_from_slice(bytes);+ for ch in junk.chunks(37) {+ d.push(ch, &mut out);+ }+ assert_eq!(out.len(), 4);+ assert_eq!(d.stats.crc_errors, 0);+ for (fr, f) in out.iter().enumerate() {+ let Frame::Data { first_pair, ch1, ch2, .. } = f else { panic!("not data") };+ assert_eq!(*first_pair, fr as u64 * 1024);+ for i in 0..1024 {+ let n = fr as f64 * 1024.0 + i as f64;+ assert_eq!(ch1[i], (2048.0 + 1200.0 * (n * 0.05).sin()) as u16);+ assert_eq!(ch2[i] as u64, ((fr * 1024 + i) as u64 * 7) % 4096);+ }+ }+ }++ #[test]+ fn corrupt_frame_is_dropped() {+ let mut bytes = include_bytes!("../../firmware/test/vectors.bin").to_vec();+ let first_len = 8 + u16le(&bytes[4..]) as usize + 2;+ bytes[first_len + 100] ^= 0x40; // corrupt the second frame+ let mut d = Decoder::default();+ let mut out = vec![];+ d.push(&bytes, &mut out);+ assert_eq!(out.len(), 3);+ assert!(d.stats.crc_errors >= 1);+ assert_eq!(d.stats.gaps, 1);+ }+}
software/dashboard/src/record.rsadded+243@@ -0,0 +1,243 @@+// SPDX-License-Identifier: MIT+//! Recording to CSV (streamed) or HDF5 (buffered, written on stop).++use serde::Serialize;+use std::fs::File;+use std::io::{BufWriter, Write};+use std::path::PathBuf;++#[derive(Clone, Copy, Debug, Serialize, PartialEq, Eq)]+#[serde(rename_all = "lowercase")]+pub enum Format {+ Csv,+ H5,+}++impl Format {+ pub fn parse(s: &str) -> Option<Self> {+ match s {+ "csv" => Some(Self::Csv),+ "h5" | "hdf5" => Some(Self::H5),+ _ => None,+ }+ }+}++/// HDF5 recordings are held in memory until stop; cap them.+pub const H5_MAX_SECONDS: f64 = 120.0;++pub struct Meta {+ pub source: String,+ pub wavelength_nm: f64,+ pub lp_hz: f64,+ pub threshold: f64,+}++pub struct Recorder {+ pub format: Format,+ pub path: PathBuf,+ pub start_pair: u64,+ pub pairs: u64,+ pub limit_pairs: Option<u64>,+ pub fringes: u64,+ pub syncs: u64,+ csv: Option<BufWriter<File>>,+ ch1: Vec<u16>,+ ch2: Vec<u16>,+ disp: Vec<f32>,+ truth: Vec<f32>,+ fr: Vec<(u64, i8)>,+ sy: Vec<(u64, u8)>,+ meta: Meta,+ pub started: chrono::DateTime<chrono::Local>,+}++#[derive(Serialize, Clone)]+pub struct RecStatus {+ pub active: bool,+ pub format: Format,+ pub path: String,+ pub seconds: f64,+ pub limit_seconds: Option<f64>,+ pub fringes: u64,+ pub syncs: u64,+}++impl Recorder {+ pub fn start(dir: &std::path::Path, format: Format, seconds: Option<f64>, start_pair: u64, meta: Meta) -> std::io::Result<Self> {+ std::fs::create_dir_all(dir)?;+ let started = chrono::Local::now();+ let ext = match format {+ Format::Csv => "csv",+ Format::H5 => "h5",+ };+ let path = dir.join(format!("smi-{}.{}", started.format("%Y%m%d-%H%M%S"), ext));+ let mut limit = seconds.map(|s| (s * 250_000.0) as u64);+ if format == Format::H5 {+ let cap = (H5_MAX_SECONDS * 250_000.0) as u64;+ limit = Some(limit.map_or(cap, |l| l.min(cap)));+ }+ let csv = if format == Format::Csv {+ let mut w = BufWriter::with_capacity(1 << 20, File::create(&path)?);+ writeln!(w, "# smi-dash recording, {}", started.to_rfc3339())?;+ writeln!(w, "# source: {}", meta.source)?;+ writeln!(w, "# per-channel rate 250000 Hz; ch2 is sampled 2 us after ch1 in each pair; 12-bit codes, 3.3 V full scale")?;+ writeln!(w, "# wavelength_nm {}; one fringe = {} nm; detector lp_hz {}; threshold {}", meta.wavelength_nm, meta.wavelength_nm / 2.0, meta.lp_hz, meta.threshold)?;+ writeln!(w, "# fringe: +1 away, -1 towards, at the pair where the edge was steepest; disp_nm: running fringe count x lambda/2")?;+ writeln!(w, "pair,t_s,ch1,ch2,ch1_v,ch2_v,sync,fringe,disp_nm,truth_nm")?;+ Some(w)+ } else {+ None+ };+ Ok(Self {+ format,+ path,+ start_pair,+ pairs: 0,+ limit_pairs: limit,+ fringes: 0,+ syncs: 0,+ csv,+ ch1: vec![],+ ch2: vec![],+ disp: vec![],+ truth: vec![],+ fr: vec![],+ sy: vec![],+ meta,+ started,+ })+ }++ pub fn done(&self) -> bool {+ self.limit_pairs.is_some_and(|l| self.pairs >= l)+ }++ /// Append a contiguous chunk starting at absolute pair `first`.+ #[allow(clippy::too_many_arguments)]+ pub fn write(+ &mut self,+ first: u64,+ ch1: &[u16],+ ch2: &[u16],+ disp_nm: &[f32],+ truth_nm: Option<&[f64]>,+ sync: &[(u64, u8)],+ fringes: &[(u64, i8)],+ sync_level_at_start: u8,+ ) -> std::io::Result<()> {+ let mut n = ch1.len();+ if let Some(l) = self.limit_pairs {+ n = n.min((l - self.pairs) as usize);+ }+ if n == 0 {+ return Ok(());+ }+ let last = first + n as u64;+ let fr: Vec<(u64, i8)> = fringes.iter().copied().filter(|f| f.0 < last).map(|(p, d)| (p.max(first), d)).collect();+ let sy: Vec<(u64, u8)> = sync.iter().copied().filter(|s| s.0 >= first && s.0 < last).collect();+ self.fringes += fr.len() as u64;+ self.syncs += sy.len() as u64;+ let lsb = 3.3 / 4096.0;+ if let Some(w) = self.csv.as_mut() {+ let mut level = sync_level_at_start;+ let (mut fi, mut si) = (0usize, 0usize);+ for i in 0..n {+ let p = first + i as u64;+ while si < sy.len() && sy[si].0 <= p {+ level = sy[si].1;+ si += 1;+ }+ let mut f = 0i8;+ while fi < fr.len() && fr[fi].0 <= p {+ f = fr[fi].1;+ fi += 1;+ }+ let t = (p - self.start_pair) as f64 / 250_000.0;+ match truth_nm {+ Some(tr) => writeln!(w, "{},{:.6},{},{},{:.4},{:.4},{},{},{:.1},{:.1}", p, t, ch1[i], ch2[i], ch1[i] as f64 * lsb, ch2[i] as f64 * lsb, level, f, disp_nm[i], tr[i])?,+ None => writeln!(w, "{},{:.6},{},{},{:.4},{:.4},{},{},{:.1},", p, t, ch1[i], ch2[i], ch1[i] as f64 * lsb, ch2[i] as f64 * lsb, level, f, disp_nm[i])?,+ }+ }+ } else {+ self.ch1.extend_from_slice(&ch1[..n]);+ self.ch2.extend_from_slice(&ch2[..n]);+ self.disp.extend_from_slice(&disp_nm[..n]);+ if let Some(tr) = truth_nm {+ self.truth.extend(tr[..n].iter().map(|&v| v as f32));+ }+ self.fr.extend(fr);+ self.sy.extend(sy);+ }+ self.pairs += n as u64;+ Ok(())+ }++ pub fn status(&self) -> RecStatus {+ RecStatus {+ active: true,+ format: self.format,+ path: self.path.display().to_string(),+ seconds: self.pairs as f64 / 250_000.0,+ limit_seconds: self.limit_pairs.map(|l| l as f64 / 250_000.0),+ fringes: self.fringes,+ syncs: self.syncs,+ }+ }++ pub fn finish(mut self) -> Result<RecStatus, String> {+ let st = self.status();+ match self.format {+ Format::Csv => {+ if let Some(mut w) = self.csv.take() {+ w.flush().map_err(|e| e.to_string())?;+ }+ }+ Format::H5 => self.write_h5()?,+ }+ Ok(RecStatus { active: false, ..st })+ }++ #[cfg(feature = "h5")]+ fn write_h5(&self) -> Result<(), String> {+ use hdf5::types::VarLenUnicode;+ let e = |x: hdf5::Error| x.to_string();+ let f = hdf5::File::create(&self.path).map_err(e)?;+ f.new_dataset_builder().deflate(4).with_data(&self.ch1).create("ch1").map_err(e)?;+ f.new_dataset_builder().deflate(4).with_data(&self.ch2).create("ch2").map_err(e)?;+ f.new_dataset_builder().deflate(4).with_data(&self.disp).create("disp_nm").map_err(e)?;+ if !self.truth.is_empty() {+ f.new_dataset_builder().deflate(4).with_data(&self.truth).create("truth_nm").map_err(e)?;+ }+ let fp: Vec<u64> = self.fr.iter().map(|x| x.0).collect();+ let fd: Vec<i8> = self.fr.iter().map(|x| x.1).collect();+ let sp: Vec<u64> = self.sy.iter().map(|x| x.0).collect();+ let sl: Vec<u8> = self.sy.iter().map(|x| x.1).collect();+ let g = f.create_group("fringes").map_err(e)?;+ g.new_dataset_builder().with_data(&fp).create("pair").map_err(e)?;+ g.new_dataset_builder().with_data(&fd).create("dir").map_err(e)?;+ let g = f.create_group("sync").map_err(e)?;+ g.new_dataset_builder().with_data(&sp).create("pair").map_err(e)?;+ g.new_dataset_builder().with_data(&sl).create("level").map_err(e)?;+ let attr_f = |name: &str, v: f64| -> Result<(), String> {+ f.new_attr::<f64>().create(name).map_err(e)?.write_scalar(&v).map_err(e)+ };+ attr_f("sample_rate_hz", 250_000.0)?;+ attr_f("ch2_delay_s", 2e-6)?;+ attr_f("lsb_volts", 3.3 / 4096.0)?;+ attr_f("wavelength_nm", self.meta.wavelength_nm)?;+ attr_f("detector_lp_hz", self.meta.lp_hz)?;+ attr_f("detector_threshold", self.meta.threshold)?;+ f.new_attr::<u64>().create("start_pair").map_err(e)?.write_scalar(&self.start_pair).map_err(e)?;+ let s: VarLenUnicode = self.meta.source.parse().map_err(|_| "bad source string".to_string())?;+ f.new_attr::<VarLenUnicode>().create("source").map_err(e)?.write_scalar(&s).map_err(e)?;+ let s: VarLenUnicode = self.started.to_rfc3339().parse().map_err(|_| "bad time".to_string())?;+ f.new_attr::<VarLenUnicode>().create("created").map_err(e)?.write_scalar(&s).map_err(e)?;+ Ok(())+ }++ #[cfg(not(feature = "h5"))]+ fn write_h5(&self) -> Result<(), String> {+ Err("this build has no HDF5 support; record with --format csv".into())+ }+}
software/dashboard/src/server.rsadded+448@@ -0,0 +1,448 @@+// SPDX-License-Identifier: MIT+//! HTTP server: the page, the SSE live channel and the JSON endpoints that both+//! the page and the CLI use.++use crate::dsp::DetectParams;+use crate::engine::{run_acquisition, Engine, SourceKind, View};+use crate::record::Format;+use crate::sim::{Profile, SimParams};+use crate::util::{self, Settings};+use axum::extract::State;+use axum::http::{header, StatusCode};+use axum::response::sse::{Event, KeepAlive, Sse};+use axum::response::{Html, IntoResponse, Response};+use axum::routing::{get, post};+use axum::{Json, Router};+use futures::stream::Stream;+use serde_json::{json, Value};+use std::collections::VecDeque;+use std::convert::Infallible;+use std::sync::{Arc, Mutex};+use std::time::{Duration, Instant};+use tokio::sync::broadcast;++const INDEX: &str = include_str!("../assets/index.html");+const ICON: &str = include_str!("../assets/icon.svg");++pub struct App {+ pub engine: Arc<Mutex<Engine>>,+ pub settings: Mutex<Settings>,+ pub tx: broadcast::Sender<(String, String)>,+ pub console: Mutex<VecDeque<Value>>,+ pub last_activity: Mutex<Instant>,+ pub thread: String,+ pub port: u16,+ pub started: chrono::DateTime<chrono::Local>,+}++type S = State<Arc<App>>;++fn ok(data: Value, hints: &[&str]) -> Response {+ Json(json!({"status": "ok", "data": data, "hints": hints})).into_response()+}++fn refuse(code: StatusCode, msg: &str, hints: &[String]) -> Response {+ (code, Json(json!({"status": "error", "error": msg, "hints": hints}))).into_response()+}++impl App {+ fn touch(&self) {+ *self.last_activity.lock().unwrap() = Instant::now();+ }+ pub fn broadcast(&self, event: &str, data: Value) {+ let _ = self.tx.send((event.to_string(), data.to_string()));+ }+ pub fn state(&self) -> Value {+ let e = self.engine.lock().unwrap();+ let s = self.settings.lock().unwrap();+ json!({+ "app": "smi-dash",+ "version": env!("CARGO_PKG_VERSION"),+ "thread": self.thread,+ "port": self.port,+ "source": e.source,+ "sim": e.sim_p,+ "detect": e.det.p,+ "view": e.view,+ "settings": *s,+ "recording": e.rec.as_ref().map(|r| serde_json::to_value(r.status()).unwrap()),+ "enums": {+ "sim.profile": Profile::ALL,+ "source.kind": ["sim", "serial"],+ "record.format": ["csv", "h5"],+ "settings.surface": ["wv", "pup"],+ "settings.units": ["auto", "nm", "um"],+ },+ "ranges": {+ "sim.c": [0.0, 10.0], "sim.m": [0.0, 0.5], "sim.noise": [0.0, 50.0],+ "sim.speed_um_s": [0.0, 20000.0], "sim.amp_um": [0.0, 500.0], "sim.freq_hz": [0.05, 50.0],+ "detect.lp_hz": [500.0, 100000.0], "detect.threshold": [0.05, 0.95],+ "view.window_ms": [0.1, 2000.0], "view.history_s": [0.5, 120.0],+ },+ })+ }+ fn push_state(&self) {+ let st = self.state();+ self.broadcast("state", st);+ self.save_snapshot();+ }+ fn save_snapshot(&self) {+ let e = self.engine.lock().unwrap();+ let snap = json!({"sim": e.sim_p, "view": e.view, "source": e.source});+ drop(e);+ let _ = util::write_json(&util::snapshot_path(&self.thread), &snap);+ }+}++/// Merge a partial JSON object into a serialisable value, refusing unknown keys.+fn merge<T: serde::Serialize + serde::de::DeserializeOwned>(cur: &T, patch: &Value, what: &str) -> Result<T, (String, Vec<String>)> {+ let mut v = serde_json::to_value(cur).unwrap();+ let Some(obj) = patch.as_object() else {+ return Err((format!("{what} expects a JSON object"), vec![format!("Send e.g. {{\"{}\": ...}}", v.as_object().unwrap().keys().next().unwrap())]));+ };+ let keys: Vec<String> = v.as_object().unwrap().keys().cloned().collect();+ for (k, val) in obj {+ if !keys.contains(k) {+ return Err((format!("unknown {what} key '{k}'"), vec![format!("Valid keys: {}", keys.join(", "))]));+ }+ v[k] = val.clone();+ }+ serde_json::from_value(v).map_err(|e| (format!("invalid {what}: {e}"), vec![format!("GET /state lists every {what} value and its type")]))+}++pub async fn serve(app: Arc<App>, listener: tokio::net::TcpListener) {+ run_acquisition(app.engine.clone());+ // Display frames at the configured rate.+ let a2 = app.clone();+ tokio::spawn(async move {+ let mut frame_no = 0u64;+ loop {+ let fps = a2.settings.lock().unwrap().fps.clamp(5.0, 60.0);+ tokio::time::sleep(Duration::from_secs_f64(1.0 / fps)).await;+ if a2.tx.receiver_count() == 0 {+ continue;+ }+ frame_no += 1;+ let snap = a2.engine.lock().unwrap().snapshot(false);+ a2.broadcast("frame", snap);+ // Recording finished on its own (duration reached): tell the page once.+ let fin = a2.engine.lock().unwrap().last_rec.take();+ if let Some(r) = fin {+ a2.broadcast("toast", json!({"text": format!("Saved {:.1} s to {}", r.seconds, r.path), "kind": "info"}));+ a2.engine.lock().unwrap().last_rec = Some(r);+ a2.push_state();+ }+ let _ = frame_no;+ }+ });+ // Idle reaper.+ let a3 = app.clone();+ tokio::spawn(async move {+ loop {+ tokio::time::sleep(Duration::from_secs(60)).await;+ let s = a3.settings.lock().unwrap().clone();+ if s.keep_alive {+ continue;+ }+ let idle = a3.last_activity.lock().unwrap().elapsed();+ if idle > Duration::from_secs_f64(s.ttl_hours * 3600.0) {+ a3.save_snapshot();+ util::deregister(&a3.thread);+ std::process::exit(0);+ }+ }+ });++ let r = Router::new()+ .route("/", get(index))+ .route("/icon.svg", get(|| async { ([(header::CONTENT_TYPE, "image/svg+xml")], ICON) }))+ .route("/events", get(events))+ .route("/state", get(state))+ .route("/health", get(health))+ .route("/frame", get(frame))+ .route("/sim", post(set_sim))+ .route("/detect", post(set_detect))+ .route("/view", post(set_view))+ .route("/source", post(set_source))+ .route("/ports", get(ports))+ .route("/zero", post(zero))+ .route("/record/start", post(rec_start))+ .route("/record/stop", post(rec_stop))+ .route("/settings", get(get_settings).post(set_settings))+ .route("/ui/:verb", post(ui))+ .route("/console", get(get_console).post(post_console))+ .route("/shutdown", post(shutdown))+ .with_state(app);+ axum::serve(listener, r).await.unwrap();+}++async fn index(State(a): S) -> Html<&'static str> {+ a.touch();+ Html(INDEX)+}++async fn events(State(a): S) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {+ a.touch();+ let mut rx = a.tx.subscribe();+ let first = a.state().to_string();+ let (tx, out) = tokio::sync::mpsc::channel::<Result<Event, Infallible>>(64);+ let a2 = a.clone();+ tokio::spawn(async move {+ // 2 KB comment so buffering proxies flush, then replay state on connect.+ if tx.send(Ok(Event::default().comment(" ".repeat(2048)))).await.is_err() {+ return;+ }+ if tx.send(Ok(Event::default().event("state").data(first))).await.is_err() {+ return;+ }+ loop {+ match rx.recv().await {+ Ok((ev, data)) => {+ if ev != "frame" {+ a2.touch();+ }+ if tx.send(Ok(Event::default().event(ev).data(data))).await.is_err() {+ break;+ }+ }+ Err(broadcast::error::RecvError::Lagged(_)) => continue,+ Err(_) => break,+ }+ }+ });+ Sse::new(tokio_stream::wrappers::ReceiverStream::new(out)).keep_alive(KeepAlive::new().interval(Duration::from_secs(15)).text("hb"))+}++async fn state(State(a): S) -> Response {+ a.touch();+ ok(a.state(), &[])+}++async fn health(State(a): S) -> Response {+ let e = a.engine.lock().unwrap();+ let data = json!({+ "version": env!("CARGO_PKG_VERSION"), "thread": a.thread, "port": a.port, "pid": std::process::id(),+ "source": e.source, "link": e.link, "seconds": e.head as f64 / 250_000.0,+ "started": a.started.to_rfc3339(), "sse_clients": a.tx.receiver_count(),+ });+ drop(e);+ ok(data, &[])+}++async fn frame(State(a): S) -> Response {+ a.touch();+ let s = a.engine.lock().unwrap().snapshot(true);+ ok(s, &[])+}++async fn set_sim(State(a): S, Json(p): Json<Value>) -> Response {+ a.touch();+ let mut e = a.engine.lock().unwrap();+ match merge::<SimParams>(&e.sim_p, &p, "sim") {+ Ok(mut np) => {+ np.c = np.c.clamp(0.0, 10.0);+ np.m = np.m.clamp(0.0, 0.5);+ np.noise = np.noise.clamp(0.0, 50.0);+ e.sim_p = np.clone();+ e.sim_rev += 1;+ e.det.p.wavelength_nm = np.wavelength_nm;+ drop(e);+ a.push_state();+ ok(serde_json::to_value(np).unwrap(), &[])+ }+ Err((m, h)) => refuse(StatusCode::BAD_REQUEST, &m, &h),+ }+}++async fn set_detect(State(a): S, Json(p): Json<Value>) -> Response {+ a.touch();+ let mut e = a.engine.lock().unwrap();+ match merge::<DetectParams>(&e.det.p, &p, "detect") {+ Ok(mut np) => {+ np.lp_hz = np.lp_hz.clamp(500.0, 100_000.0);+ np.threshold = np.threshold.clamp(0.05, 0.95);+ e.det.set_params(np.clone());+ drop(e);+ {+ let mut s = a.settings.lock().unwrap();+ s.detect = np.clone();+ let _ = util::write_json(&util::settings_path(), &*s);+ }+ a.push_state();+ ok(serde_json::to_value(np).unwrap(), &[])+ }+ Err((m, h)) => refuse(StatusCode::BAD_REQUEST, &m, &h),+ }+}++async fn set_view(State(a): S, Json(p): Json<Value>) -> Response {+ a.touch();+ let mut e = a.engine.lock().unwrap();+ match merge::<View>(&e.view, &p, "view") {+ Ok(mut nv) => {+ nv.window_ms = nv.window_ms.clamp(0.1, 2000.0);+ nv.history_s = nv.history_s.clamp(0.5, 120.0);+ nv.pan_ms = nv.pan_ms.clamp(0.0, 2000.0);+ let paused = nv.paused;+ nv.paused = e.view.paused;+ e.view = nv;+ e.set_paused(paused);+ let v = serde_json::to_value(&e.view).unwrap();+ drop(e);+ a.push_state();+ ok(v, &[])+ }+ Err((m, h)) => refuse(StatusCode::BAD_REQUEST, &m, &h),+ }+}++async fn set_source(State(a): S, Json(p): Json<Value>) -> Response {+ a.touch();+ let kind = p.get("kind").and_then(|v| v.as_str()).unwrap_or("");+ let src = match kind {+ "sim" => SourceKind::Sim,+ "serial" => {+ let port = p.get("port").and_then(|v| v.as_str()).map(String::from).or_else(|| util::guess_pico_port());+ match port {+ Some(port) => SourceKind::Serial { port },+ None => {+ return refuse(+ StatusCode::BAD_REQUEST,+ "no Pico serial port found",+ &["List ports with `smi-dash ports`, then `smi-dash source serial --port <PORT>`".into(), "Under WSL, attach the Pico first: `usbipd attach --wsl --busid <BUSID>` in Windows, or run the Windows build of smi-dash".into()],+ )+ }+ }+ }+ _ => return refuse(StatusCode::BAD_REQUEST, &format!("unknown source kind '{kind}'"), &["Valid kinds: sim, serial".into()]),+ };+ let mut e = a.engine.lock().unwrap();+ if e.rec.is_some() {+ return refuse(StatusCode::CONFLICT, "a recording is running", &["Stop it first: `smi-dash record stop`".into()]);+ }+ e.source = src.clone();+ e.reset_stream();+ drop(e);+ a.push_state();+ ok(serde_json::to_value(src).unwrap(), &["Check the link with `smi-dash status`"])+}++async fn ports(State(a): S) -> Response {+ a.touch();+ ok(json!(util::list_ports()), &[])+}++async fn zero(State(a): S) -> Response {+ a.touch();+ a.engine.lock().unwrap().zero();+ a.broadcast("toast", json!({"text": "Displacement set to zero", "kind": "info"}));+ ok(json!({}), &[])+}++async fn rec_start(State(a): S, Json(p): Json<Value>) -> Response {+ a.touch();+ let s = a.settings.lock().unwrap().clone();+ let fmt_s = p.get("format").and_then(|v| v.as_str()).unwrap_or(&s.record_format).to_string();+ let Some(fmt) = Format::parse(&fmt_s) else {+ return refuse(StatusCode::BAD_REQUEST, &format!("unknown format '{fmt_s}'"), &["Valid formats: csv, h5".into()]);+ };+ if fmt == Format::H5 && !cfg!(feature = "h5") {+ return refuse(StatusCode::BAD_REQUEST, "this build has no HDF5 support", &["Record CSV instead: `smi-dash record start --format csv`".into()]);+ }+ let secs = p.get("seconds").and_then(|v| v.as_f64()).filter(|s| *s > 0.0);+ let dir = p.get("dir").and_then(|v| v.as_str()).map(std::path::PathBuf::from).unwrap_or_else(|| util::expand(&s.record_dir));+ let res = a.engine.lock().unwrap().start_record(&dir, fmt, secs);+ match res {+ Ok(path) => {+ a.broadcast("toast", json!({"text": format!("Recording to {path}"), "kind": "info"}));+ a.push_state();+ ok(json!({"path": path, "format": fmt, "seconds": secs}), &["Stop with `smi-dash record stop`; progress in `smi-dash status`"])+ }+ Err(m) => refuse(StatusCode::CONFLICT, &m, &["Stop the current recording with `smi-dash record stop`".into()]),+ }+}++async fn rec_stop(State(a): S) -> Response {+ a.touch();+ let res = a.engine.lock().unwrap().stop_record();+ match res {+ Ok(st) => {+ a.broadcast("toast", json!({"text": format!("Saved {:.1} s to {}", st.seconds, st.path), "kind": "info"}));+ a.push_state();+ ok(serde_json::to_value(st).unwrap(), &[])+ }+ Err(m) => refuse(StatusCode::CONFLICT, &m, &["Start one with `smi-dash record start --format csv --seconds 5`".into()]),+ }+}++async fn get_settings(State(a): S) -> Response {+ a.touch();+ let s = a.settings.lock().unwrap().clone();+ ok(json!({"settings": s, "enums": {"surface": ["wv", "pup"], "record_format": ["csv", "h5"], "units": ["auto", "nm", "um"]}}), &[])+}++async fn set_settings(State(a): S, Json(p): Json<Value>) -> Response {+ a.touch();+ let cur = a.settings.lock().unwrap().clone();+ match merge::<Settings>(&cur, &p, "settings") {+ Ok(mut ns) => {+ if !["wv", "pup"].contains(&ns.surface.as_str()) {+ return refuse(StatusCode::BAD_REQUEST, &format!("invalid surface '{}'", ns.surface), &["Valid surfaces: wv, pup".into()]);+ }+ if Format::parse(&ns.record_format).is_none() {+ return refuse(StatusCode::BAD_REQUEST, &format!("invalid record_format '{}'", ns.record_format), &["Valid formats: csv, h5".into()]);+ }+ if !["auto", "nm", "um"].contains(&ns.units.as_str()) {+ return refuse(StatusCode::BAD_REQUEST, &format!("invalid units '{}'", ns.units), &["Valid units: auto, nm, um".into()]);+ }+ ns.fps = ns.fps.clamp(5.0, 60.0);+ ns.ttl_hours = ns.ttl_hours.clamp(0.1, 24.0 * 30.0);+ a.engine.lock().unwrap().det.set_params(ns.detect.clone());+ *a.settings.lock().unwrap() = ns.clone();+ let _ = util::write_json(&util::settings_path(), &ns);+ a.push_state();+ ok(serde_json::to_value(ns).unwrap(), &[])+ }+ Err((m, h)) => refuse(StatusCode::BAD_REQUEST, &m, &h),+ }+}++async fn ui(State(a): S, axum::extract::Path(verb): axum::extract::Path<String>, Json(p): Json<Value>) -> Response {+ a.touch();+ let valid = ["toast", "click", "reveal", "cursor", "reload"];+ if !valid.contains(&verb.as_str()) {+ return refuse(StatusCode::NOT_FOUND, &format!("unknown ui verb '{verb}'"), &[format!("Valid verbs: {}", valid.join(", "))]);+ }+ if verb != "toast" && verb != "reload" && p.get("selector").and_then(|v| v.as_str()).is_none() {+ return refuse(StatusCode::BAD_REQUEST, "missing selector", &[format!("Send {{\"selector\": \"#btn-zero\"}}; selectors are listed by `smi-dash ui {verb} --help`")]);+ }+ let n = a.tx.receiver_count();+ a.broadcast(&verb, p.clone());+ let hint = if n == 0 { vec!["No page is connected; open it with `smi-dash show`"] } else { vec![] };+ ok(json!({"delivered_to": n}), &hint)+}++async fn get_console(State(a): S) -> Response {+ let c: Vec<Value> = a.console.lock().unwrap().iter().cloned().collect();+ ok(json!(c), &[])+}++async fn post_console(State(a): S, Json(p): Json<Value>) -> Response {+ let mut c = a.console.lock().unwrap();+ c.push_back(p);+ while c.len() > 300 {+ c.pop_front();+ }+ ok(json!({}), &[])+}++async fn shutdown(State(a): S) -> Response {+ a.save_snapshot();+ let thread = a.thread.clone();+ tokio::spawn(async move {+ tokio::time::sleep(Duration::from_millis(200)).await;+ util::deregister(&thread);+ std::process::exit(0);+ });+ ok(json!({"stopping": true}), &[])+}
software/dashboard/src/sim.rsadded+557@@ -0,0 +1,557 @@+// SPDX-License-Identifier: MIT+//! Physical simulator of the self-mixing interferometer and the board's analog chain.+//!+//! Optics: the Lang-Kobayashi steady-state excess-phase equation+//! phi_F = phi_0 - C sin(phi_F + atan(alpha)), phi_0 = 4 pi L / lambda+//! solved on its stable branch with hysteresis, so C < 1 gives a near-sinusoid,+//! C > 1 gives the leaning sawtooth whose lean follows the direction of motion.+//! Power P = P0 (1 + m cos phi_F). An optional second longitudinal mode, spaced so+//! the two fringe patterns beat with nulls every 1.46 mm of travel, shows the+//! fading problem a single-longitudinal-mode laser removes.+//!+//! Electronics, per channel, from the board netlist: photodiode current into a+//! TIA (Rf), a 1:2 divider, an inverting x20 summing amplifier with the offset+//! trim (net gain -10), a 3.9 k / 1 n pole (40.8 kHz), a Sallen-Key stage+//! (44.4 kHz, Q 0.98), then the RP2040 ADC: 12-bit, 3.3 V reference, about+//! 1.3 LSB rms noise and the wide codes at 512, 1536, 2560 and 3584.+//!+//! The ADC alternates ADC0/ADC1 every 2 us (500 ksps total), so the simulator+//! runs at 500 kHz and samples ch1 on even ticks and ch2 on odd ticks, exactly+//! as the firmware's round robin does.++use rand::rngs::SmallRng;+use rand::SeedableRng;+use rand_distr::{Distribution, Normal};+use serde::{Deserialize, Serialize};+use std::f64::consts::PI;++pub const TICK_HZ: f64 = 500_000.0;+pub const FS: f64 = 250_000.0;+pub const VREF: f64 = 3.3;+/// Two equal modes beat with nulls every `BEAT_MM` of target travel when+/// their spacing is lambda^2 / (2 * BEAT_MM).+pub const BEAT_MM: f64 = 1.46;++#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "lowercase")]+pub enum Profile {+ Constant,+ Sine,+ Step,+ Hand,+ Hold,+}++impl Profile {+ pub fn parse(s: &str) -> Option<Self> {+ Some(match s {+ "constant" => Self::Constant,+ "sine" => Self::Sine,+ "step" => Self::Step,+ "hand" => Self::Hand,+ "hold" => Self::Hold,+ _ => return None,+ })+ }+ pub const ALL: [&'static str; 5] = ["constant", "sine", "step", "hand", "hold"];+}++#[derive(Clone, Debug, Serialize, Deserialize)]+#[serde(default)]+pub struct SimParams {+ pub profile: Profile,+ /// Constant profile: speed in um/s; travel then reverses every `range_um`.+ pub speed_um_s: f64,+ pub range_um: f64,+ /// Sine profile: amplitude (um, zero to peak) and frequency.+ pub amp_um: f64,+ pub freq_hz: f64,+ /// Step profile: step size (um), move time (s) and dwell time (s).+ pub step_um: f64,+ pub move_s: f64,+ pub dwell_s: f64,+ /// Hand jitter: rms wander (um) and tremor amplitude (um).+ pub jitter_um: f64,+ pub tremor_um: f64,+ /// Optical feedback parameter C and linewidth enhancement factor alpha.+ pub c: f64,+ pub alpha: f64,+ /// Modulation depth of the laser power by the returning light.+ pub m: f64,+ pub wavelength_nm: f64,+ pub multimode: bool,+ /// Excess intensity noise multiplier (1 = clean bench, 10 = vibration, speckle).+ pub noise: f64,+ /// Offset trim error at the ADC, volts.+ pub offset_v: f64,+ /// Monitor TIA feedback resistor (1000 or 4700 on the board).+ pub rf1_ohm: f64,+ pub idc1_ua: f64,+ /// External photodiode TIA feedback resistor (47 k or 150 k) and DC current.+ pub rf2_ohm: f64,+ pub idc2_ua: f64,+ pub seed: u64,+}++impl Default for SimParams {+ fn default() -> Self {+ Self {+ profile: Profile::Constant,+ speed_um_s: 1000.0,+ range_um: 400.0,+ amp_um: 5.0,+ freq_hz: 1.0,+ step_um: 10.0,+ move_s: 0.15,+ dwell_s: 0.6,+ jitter_um: 1.5,+ tremor_um: 0.3,+ c: 3.0,+ alpha: 4.0,+ m: 0.12,+ wavelength_nm: 658.0,+ multimode: false,+ noise: 1.0,+ offset_v: 0.02,+ rf1_ohm: 4700.0,+ idc1_ua: 35.0,+ rf2_ohm: 47000.0,+ idc2_ua: 8.0,+ seed: 1,+ }+ }+}++/// Bilinear-transform first-order low-pass.+#[derive(Clone, Default)]+struct Pole1 {+ b: f64,+ a: f64,+ x1: f64,+ y1: f64,+}+impl Pole1 {+ fn new(fc: f64, fs: f64) -> Self {+ let k = (PI * fc / fs).tan();+ Self { b: k / (1.0 + k), a: (k - 1.0) / (k + 1.0), x1: 0.0, y1: 0.0 }+ }+ fn reset(&mut self, v: f64) {+ self.x1 = v;+ self.y1 = v;+ }+ fn run(&mut self, x: f64) -> f64 {+ let y = self.b * (x + self.x1) - self.a * self.y1;+ self.x1 = x;+ self.y1 = y;+ y+ }+}++/// Bilinear-transform second-order low-pass (Direct Form I), prewarped at fc.+#[derive(Clone, Default)]+pub struct Biquad {+ b0: f64,+ b1: f64,+ b2: f64,+ a1: f64,+ a2: f64,+ x1: f64,+ x2: f64,+ y1: f64,+ y2: f64,+}+impl Biquad {+ pub fn lowpass(fc: f64, q: f64, fs: f64) -> Self {+ let k = (PI * fc / fs).tan();+ let n = 1.0 / (1.0 + k / q + k * k);+ let b0 = k * k * n;+ Self {+ b0,+ b1: 2.0 * b0,+ b2: b0,+ a1: 2.0 * (k * k - 1.0) * n,+ a2: (1.0 - k / q + k * k) * n,+ ..Default::default()+ }+ }+ pub fn reset(&mut self, v: f64) {+ self.x1 = v;+ self.x2 = v;+ self.y1 = v;+ self.y2 = v;+ }+ #[inline]+ pub fn run(&mut self, x: f64) -> f64 {+ let y = self.b0 * x + self.b1 * self.x1 + self.b2 * self.x2 - self.a1 * self.y1 - self.a2 * self.y2;+ self.x2 = self.x1;+ self.x1 = x;+ self.y2 = self.y1;+ self.y1 = y;+ y+ }+}++/// One longitudinal mode's self-mixing phase, tracked on its stable branch.+#[derive(Clone)]+struct Mode {+ /// 2 pi / lambda for this mode, rad per metre (round trip is 2x).+ k: f64,+ weight: f64,+ phi_f: f64,+ phi0_prev: f64,+ init: bool,+}++impl Mode {+ fn new(lambda_m: f64, weight: f64) -> Self {+ Self { k: 2.0 * PI / lambda_m, weight, phi_f: 0.0, phi0_prev: 0.0, init: false }+ }++ /// Solve x - phi0 + C sin(x + th) = 0 on the branch continuing from the last+ /// solution. When the branch folds (C > 1) the scan carries the solution to+ /// the next stable branch: that jump is the sawtooth's sharp edge.+ fn step(&mut self, l_m: f64, c: f64, th: f64) -> f64 {+ let phi0 = 2.0 * self.k * l_m;+ if !self.init || c <= 0.0 {+ self.init = true;+ self.phi0_prev = phi0;+ self.phi_f = if c <= 0.0 { phi0 } else { solve_scan(phi0 - 3.0 * PI, phi0, c, th, 1.0) };+ return self.phi_f.cos();+ }+ let d = phi0 - self.phi0_prev;+ self.phi0_prev = phi0;+ // Fast path: Newton from the predicted point on the current branch. Valid+ // while the branch's slope 1 + C cos(x + th) stays well positive; near+ // the fold (the sawtooth edge) fall back to the bracketed scan.+ let x0 = self.phi_f;+ let s0 = 1.0 + c * (x0 + th).cos();+ if s0 > 0.2 {+ let mut x = x0 + d / s0;+ let mut ok = false;+ for _ in 0..4 {+ let (sn, cs) = (x + th).sin_cos();+ let fx = x - phi0 + c * sn;+ let dfx = 1.0 + c * cs;+ if dfx < 0.1 {+ break;+ }+ let dx = fx / dfx;+ x -= dx;+ if dx.abs() < 1e-10 {+ ok = 1.0 + c * (x + th).cos() > 0.1 && (x - x0).abs() < 0.3;+ break;+ }+ }+ if ok {+ self.phi_f = x;+ return x.cos();+ }+ }+ let dir = if d >= 0.0 { 1.0 } else { -1.0 };+ self.phi_f = solve_scan(self.phi_f, phi0, c, th, dir);+ self.phi_f.cos()+ }+}++#[inline]+fn f_eval(x: f64, phi0: f64, c: f64, th: f64) -> f64 {+ x - phi0 + c * (x + th).sin()+}++/// Scan from `x` in direction `dir` until f changes sign the way a stable root+/// does (upward along the scan), then refine by bisection plus Newton.+fn solve_scan(x: f64, phi0: f64, c: f64, th: f64, dir: f64) -> f64 {+ let f0 = f_eval(x, phi0, c, th);+ if f0 == 0.0 {+ return x;+ }+ // If f has the "wrong" sign for the scan direction the root lies behind us+ // (tiny reversal inside one sample); scan the other way.+ let dir = if dir * f0 > 0.0 { -dir } else { dir };+ let step = 0.05 * dir;+ let mut a = x;+ let mut fa = f0;+ let mut b = x;+ let mut fb;+ let mut found = false;+ for _ in 0..800 {+ b = a + step;+ fb = f_eval(b, phi0, c, th);+ if fa.signum() != fb.signum() {+ found = true;+ break;+ }+ a = b;+ fa = fb;+ }+ if !found {+ return phi0;+ }+ let (mut lo, mut hi) = if fa < 0.0 { (a, b) } else { (b, a) };+ let mut r = 0.5 * (lo + hi);+ for _ in 0..40 {+ let fr = f_eval(r, phi0, c, th);+ if fr.abs() < 1e-12 {+ break;+ }+ if fr < 0.0 { lo = r } else { hi = r }+ let dfr = 1.0 + c * (r + th).cos();+ let nr = r - fr / dfr;+ let (mn, mx) = if lo < hi { (lo, hi) } else { (hi, lo) };+ r = if dfr > 1e-9 && nr > mn && nr < mx { nr } else { 0.5 * (lo + hi) };+ if (hi - lo).abs() < 1e-13 {+ break;+ }+ }+ r+}++/// Everything the simulator produces for one chunk.+#[derive(Default)]+pub struct Chunk {+ pub ch1: Vec<u16>,+ pub ch2: Vec<u16>,+ /// Ground-truth target displacement from the start, nm, one per pair.+ pub truth_nm: Vec<f64>,+ /// SYNC edges: (pair index, level).+ pub sync: Vec<(u64, u8)>,+}++pub struct Simulator {+ pub p: SimParams,+ rng: SmallRng,+ modes: Vec<Mode>,+ aa1: [Pole1; 2],+ aa2: [Biquad; 2],+ pub tick: u64,+ t: f64,+ /// Target position relative to its starting point, metres.+ pos: f64,+ /// Hand-jitter state.+ ou: f64,+ drift: f64,+ tremor_phase: f64,+ seg_prev: i64,+ sync_high_until: Option<u64>,+ base_l: f64,+ rebuild: bool,+ t_profile_origin: f64,+ pos_origin: f64,+}++impl Simulator {+ pub fn new(p: SimParams) -> Self {+ let rng = SmallRng::seed_from_u64(p.seed);+ let mut s = Self {+ p,+ rng,+ modes: vec![],+ aa1: [Pole1::new(40_809.0, TICK_HZ), Pole1::new(40_809.0, TICK_HZ)],+ aa2: [Biquad::lowpass(44_368.0, 0.978, TICK_HZ), Biquad::lowpass(44_368.0, 0.978, TICK_HZ)],+ tick: 0,+ t: 0.0,+ pos: 0.0,+ ou: 0.0,+ drift: 0.0,+ tremor_phase: 0.0,+ seg_prev: -1,+ sync_high_until: None,+ // Target 100 mm from the laser, placed 0.18 mm before a beat+ // maximum so multimode runs start bright and fade as they travel.+ base_l: (0.1 / (BEAT_MM * 1e-3)).round() * BEAT_MM * 1e-3 - 0.18e-3,+ rebuild: true,+ t_profile_origin: 0.0,+ pos_origin: 0.0,+ };+ s.build_modes();+ for i in 0..2 {+ s.aa1[i].reset(1.65);+ s.aa2[i].reset(1.65);+ }+ s+ }++ fn build_modes(&mut self) {+ let lam = self.p.wavelength_nm * 1e-9;+ self.modes = if self.p.multimode {+ let dl = lam * lam / (2.0 * BEAT_MM * 1e-3);+ vec![Mode::new(lam - dl / 2.0, 0.5), Mode::new(lam + dl / 2.0, 0.5)]+ } else {+ vec![Mode::new(lam, 1.0)]+ };+ self.rebuild = false;+ }++ /// Apply new parameters. Changing the wavelength or mode count re-seeds the+ /// optical phase; the motion state carries on.+ pub fn set_params(&mut self, p: SimParams) {+ let rebuild = p.multimode != self.p.multimode || p.wavelength_nm != self.p.wavelength_nm;+ // Any change to the motion restarts it from where the target is now, so+ // the target never jumps (a jump would be an instant multi-fringe move).+ let motion = |q: &SimParams| (q.profile, q.speed_um_s, q.range_um, q.amp_um, q.freq_hz, q.step_um, q.move_s, q.dwell_s);+ let profile_changed = motion(&p) != motion(&self.p);+ self.p = p;+ if rebuild {+ self.build_modes();+ }+ if profile_changed {+ // Start the new motion from where the target is now.+ self.seg_prev = -1;+ self.t_profile_origin = self.t;+ self.pos_origin = self.pos;+ self.ou = 0.0;+ self.drift = 0.0;+ }+ }+}++impl Simulator {+ /// Advance the motion by one tick. Returns a SYNC edge if a segment starts.+ fn motion(&mut self, dt: f64) -> Option<u8> {+ let tp = self.t - self.t_profile_origin;+ let p = &self.p;+ let um = 1e-6;+ let (target, seg): (f64, i64) = match p.profile {+ Profile::Hold => (self.pos_origin, 0),+ Profile::Constant => {+ let range = p.range_um.max(1.0) * um;+ let v = p.speed_um_s.abs().max(0.0) * um;+ if v <= 0.0 {+ (self.pos, 0)+ } else {+ let period = 2.0 * range / v;+ let ph = (tp / period).fract() * period * v; // 0..2*range+ let rel = if ph < range { ph } else { 2.0 * range - ph };+ let seg = (tp / (period / 2.0)).floor() as i64;+ (self.pos_origin + rel, seg)+ }+ }+ Profile::Sine => {+ let w = 2.0 * PI * p.freq_hz;+ let seg = (tp * p.freq_hz).floor() as i64;+ (self.pos_origin + p.amp_um * um * (w * tp).sin(), seg)+ }+ Profile::Step => {+ // Move out, dwell, move back, dwell. Raised-cosine moves.+ let mv = p.move_s.max(0.005);+ let dw = p.dwell_s.max(0.0);+ let period = 2.0 * (mv + dw);+ let ph = tp % period;+ let seg = (tp / (mv + dw)).floor() as i64;+ let s = p.step_um * um;+ let shape = |x: f64| 0.5 - 0.5 * (PI * x.clamp(0.0, 1.0)).cos();+ let rel = if ph < mv {+ s * shape(ph / mv)+ } else if ph < mv + dw {+ s+ } else if ph < 2.0 * mv + dw {+ s * (1.0 - shape((ph - mv - dw) / mv))+ } else {+ 0.0+ };+ (self.pos_origin + rel, seg)+ }+ Profile::Hand => {+ // A hand-held target: smooth wander (velocity is an+ // Ornstein-Uhlenbeck process, position mean-reverts over 1 s)+ // plus a 9 Hz physiological tremor with drifting phase.+ let tau_v: f64 = 0.08;+ let tau_x: f64 = 1.0;+ let sigma_x = p.jitter_um * um;+ let sigma_v = sigma_x / (tau_v * tau_x).sqrt();+ let n: f64 = Normal::new(0.0, 1.0).unwrap().sample(&mut self.rng);+ self.drift += -self.drift / tau_v * dt + sigma_v * (2.0 * dt / tau_v).sqrt() * n;+ self.ou += (self.drift - self.ou / tau_x) * dt;+ let n2: f64 = Normal::new(0.0, 1.0).unwrap().sample(&mut self.rng);+ self.tremor_phase += 2.0 * PI * 9.0 * dt + 0.6 * dt.sqrt() * n2;+ (self.pos_origin + self.ou + p.tremor_um * um * self.tremor_phase.sin(), 0)+ }+ };+ self.pos = target;+ if seg != self.seg_prev {+ let first = self.seg_prev == -1;+ self.seg_prev = seg;+ if !first {+ return Some(1);+ }+ }+ None+ }++ /// Generate `pairs` ADC sample pairs.+ pub fn generate(&mut self, pairs: usize) -> Chunk {+ let mut out = Chunk {+ ch1: Vec::with_capacity(pairs),+ ch2: Vec::with_capacity(pairs),+ truth_nm: Vec::with_capacity(pairs),+ sync: vec![],+ };+ if self.rebuild {+ self.build_modes();+ }+ let dt = 1.0 / TICK_HZ;+ let th = self.p.alpha.atan();+ let normal = Normal::new(0.0, 1.0).unwrap();+ let rin = 4e-5 * self.p.noise; // relative intensity noise per tick+ let lsb = VREF / 4096.0;+ let g = 10.0; // divider 1:2 then inverting x20+ let a1 = self.p.rf1_ohm * self.p.idc1_ua * 1e-6 * g;+ let a2 = self.p.rf2_ohm * self.p.idc2_ua * 1e-6 * g;+ // Mechanical noise term: sub-nm white displacement jitter scaled by noise.+ let mech = 0.3e-9 * self.p.noise;+ for _ in 0..pairs {+ let mut pair = [0u16; 2];+ for sub in 0..2 {+ if sub == 0 {+ if let Some(lv) = self.motion(dt * 2.0) {+ let pair_idx = self.tick / 2;+ out.sync.push((pair_idx, lv));+ self.sync_high_until = Some(pair_idx + 250); // 1 ms pulse+ }+ if let Some(until) = self.sync_high_until {+ if self.tick / 2 >= until {+ out.sync.push((self.tick / 2, 0));+ self.sync_high_until = None;+ }+ }+ }+ let l = self.base_l + self.pos + mech * normal.sample(&mut self.rng);+ let mut fr = 0.0;+ for m in self.modes.iter_mut() {+ fr += m.weight * m.step(l, self.p.c, th);+ }+ let pw = 1.0 + self.p.m * fr + rin * normal.sample(&mut self.rng);+ // Both channels see the same optical power fluctuation (rear monitor+ // and front pickoff), each through its own TIA and the inverting chain.+ let v1 = 1.65 + self.p.offset_v - a1 * (pw - 1.0);+ let v2 = 1.65 - 0.6 * self.p.offset_v - a2 * (pw - 1.0) + 0.002 * (2.0 * PI * 100.0 * self.t).sin();+ let y1 = self.aa2[0].run(self.aa1[0].run(v1));+ let y2 = self.aa2[1].run(self.aa1[1].run(v2));+ let y = if sub == 0 { y1 } else { y2 };+ let code = adc_code(y + 1.3 * lsb * normal.sample(&mut self.rng), lsb);+ pair[sub] = code;+ self.t += dt;+ self.tick += 1;+ }+ out.ch1.push(pair[0]);+ out.ch2.push(pair[1]);+ out.truth_nm.push(self.pos * 1e9);+ }+ out+ }+}++/// RP2040 ADC transfer: 12-bit, clipped to the rails, with the documented wide+/// codes (differential non-linearity) at 512, 1536, 2560 and 3584.+fn adc_code(v: f64, lsb: f64) -> u16 {+ let x = (v / lsb).clamp(0.0, 4095.0);+ let mut c = x.floor() as i32;+ let r = c % 1024;+ if (508..512).contains(&r) {+ c = c - r + 512;+ } else if (512..516).contains(&r) {+ c = c - r + 512;+ }+ c.clamp(0, 4095) as u16+}+
software/dashboard/src/util.rsadded+150@@ -0,0 +1,150 @@+// SPDX-License-Identifier: MIT+//! Settings, instance registry, snapshots and serial port discovery.++use crate::dsp::DetectParams;+use serde::{Deserialize, Serialize};+use serde_json::{json, Value};+use std::path::{Path, PathBuf};++#[derive(Clone, Debug, Serialize, Deserialize)]+#[serde(default)]+pub struct Settings {+ /// Idle hours before the server saves its state and exits.+ pub ttl_hours: f64,+ pub keep_alive: bool,+ /// Where `smi-dash show` opens the page: wv (Hydrogen webview) or pup.+ pub surface: String,+ /// Display frames per second pushed to the page.+ pub fps: f64,+ pub record_dir: String,+ pub record_format: String,+ /// Displacement units: auto switches from nm to um above 10 um.+ pub units: String,+ pub detect: DetectParams,+}++impl Default for Settings {+ fn default() -> Self {+ Self {+ ttl_hours: 24.0,+ keep_alive: false,+ surface: "wv".into(),+ fps: 30.0,+ record_dir: "~/smi-recordings".into(),+ record_format: "csv".into(),+ units: "auto".into(),+ detect: DetectParams::default(),+ }+ }+}++pub fn home() -> PathBuf {+ std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from).unwrap_or_else(|| PathBuf::from("."))+}++pub fn expand(p: &str) -> PathBuf {+ if let Some(rest) = p.strip_prefix("~/") {+ home().join(rest)+ } else {+ PathBuf::from(p)+ }+}++pub fn base_dir() -> PathBuf {+ home().join(".adom").join("instances").join("smi-dash")+}++pub fn settings_path() -> PathBuf {+ base_dir().join("settings.json")+}++pub fn slug(thread: &str) -> String {+ let s: String = thread.chars().map(|c| if c.is_ascii_alphanumeric() { c.to_ascii_lowercase() } else { '-' }).collect();+ let s = s.trim_matches('-').to_string();+ if s.is_empty() { "default".into() } else { s }+}++pub fn snapshot_path(thread: &str) -> PathBuf {+ base_dir().join("snapshots").join(format!("{}.json", slug(thread)))+}++pub fn registry_path(thread: &str) -> PathBuf {+ base_dir().join("registry").join(format!("{}.json", slug(thread)))+}++pub fn write_json<T: Serialize>(p: &Path, v: &T) -> std::io::Result<()> {+ if let Some(d) = p.parent() {+ std::fs::create_dir_all(d)?;+ }+ let tmp = p.with_extension("tmp");+ std::fs::write(&tmp, serde_json::to_vec_pretty(v)?)?;+ std::fs::rename(tmp, p)+}++pub fn read_json(p: &Path) -> Option<Value> {+ serde_json::from_slice(&std::fs::read(p).ok()?).ok()+}++pub fn load_settings() -> Settings {+ read_json(&settings_path()).and_then(|v| serde_json::from_value(v).ok()).unwrap_or_default()+}++pub fn register(thread: &str, port: u16) {+ let v = json!({+ "pid": std::process::id(), "port": port, "thread": thread,+ "version": env!("CARGO_PKG_VERSION"), "startedAt": chrono::Local::now().to_rfc3339(),+ });+ let _ = write_json(®istry_path(thread), &v);+}++pub fn deregister(thread: &str) {+ let _ = std::fs::remove_file(registry_path(thread));+}++/// Live registry entries (dead ones are pruned by checking /health).+pub fn instances() -> Vec<Value> {+ let mut out = vec![];+ let Ok(rd) = std::fs::read_dir(base_dir().join("registry")) else { return out };+ for e in rd.flatten() {+ let p = e.path();+ if p.extension().and_then(|x| x.to_str()) != Some("json") {+ continue;+ }+ let Some(v) = read_json(&p) else { continue };+ let port = v["port"].as_u64().unwrap_or(0);+ // Prune only when nothing listens on the port any more. A slow reply+ // (a busy machine) is not death.+ let alive = match ureq::get(&format!("http://127.0.0.1:{port}/health")).timeout(std::time::Duration::from_millis(3000)).call() {+ Ok(_) | Err(ureq::Error::Status(..)) => true,+ Err(ureq::Error::Transport(t)) => t.kind() != ureq::ErrorKind::ConnectionFailed,+ };+ if alive {+ out.push(v);+ } else {+ let _ = std::fs::remove_file(&p);+ }+ }+ out+}++pub fn list_ports() -> Vec<Value> {+ let mut out = vec![];+ if let Ok(ports) = serialport::available_ports() {+ for p in ports {+ let (vid, pid, product, serial) = match &p.port_type {+ serialport::SerialPortType::UsbPort(u) => (Some(u.vid), Some(u.pid), u.product.clone(), u.serial_number.clone()),+ _ => (None, None, None, None),+ };+ out.push(json!({+ "port": p.port_name, "vid": vid.map(|v| format!("{v:04x}")), "pid": pid.map(|v| format!("{v:04x}")),+ "product": product, "serial": serial,+ "is_pico": vid == Some(0x2E8A),+ }));+ }+ }+ out+}++pub fn guess_pico_port() -> Option<String> {+ list_ports().into_iter().find(|p| p["is_pico"].as_bool() == Some(true)).and_then(|p| p["port"].as_str().map(String::from))+}
software/dist/SHA256SUMSadded+3@@ -0,0 +1,3 @@+3bd07d3d729ac9d1150e9a04079392ffdb51f313b6a0fc219624fd94877b4654 smi_pico.uf2+5d193be1b4148ad967e45339a13a5059bddbb33f7304ec1b8b2491d3d7166fb0 smi-dash-linux-x64+155a0c999610397694fcc3e369c6798ac6062aa332e2b47aa32b65e7b7eb8ab6 smi-dash-windows-x64.exe
software/dist/smi-dash-linux-x64added⋯ 1 unchanged line ⋯
software/dist/smi-dash-windows-x64.exeadded⋯ 1 unchanged line ⋯
software/dist/smi_pico.uf2added⋯ 1 unchanged line ⋯
software/firmware/CMakeLists.txtadded+27@@ -0,0 +1,27 @@+# SPDX-License-Identifier: MIT+cmake_minimum_required(VERSION 3.13)+set(PICO_BOARD pico CACHE STRING "Board type")+include(pico_sdk_import.cmake)+project(smi_pico C CXX ASM)+set(CMAKE_C_STANDARD 11)+pico_sdk_init()++add_executable(smi_pico+ src/main.c+ src/smi_frame.c+ src/usb_descriptors.c+)+target_include_directories(smi_pico PRIVATE ${CMAKE_CURRENT_LIST_DIR}/src)+target_compile_options(smi_pico PRIVATE -Wall -Wextra -O2)+target_link_libraries(smi_pico PRIVATE+ pico_stdlib+ pico_unique_id+ hardware_adc+ hardware_dma+ hardware_irq+ tinyusb_device+ tinyusb_board+)+pico_enable_stdio_usb(smi_pico 0)+pico_enable_stdio_uart(smi_pico 0)+pico_add_extra_outputs(smi_pico)
software/firmware/README.mdadded+63@@ -0,0 +1,63 @@+# Pico firmware: smi_pico++Turns a Raspberry Pi Pico (RP2040, SC0915) into the interferometer's two-channel digitizer.++| Pin | Use |+|---|---|+| GPIO26 / ADC0, pin 31 | Channel 1, laser monitor photodiode after the analog chain |+| GPIO27 / ADC1, pin 32 | Channel 2, external photodiode |+| GPIO15, pin 20 | SYNC from the motion stage (the board's SN74LVC1G17 buffer, non-inverting; internal pulls off) |+| ADC_VREF, pin 35 | Filtered on the board (C150), not driven by the firmware |+| USB | CDC serial, the data stream |++## Flashing++1. Hold the BOOTSEL button and plug the Pico into USB. A drive called `RPI-RP2` appears.+2. Copy `smi_pico.uf2` (from `software/dist/`, or your own build) onto it. The Pico reboots and enumerates as a USB serial device, "SMI Interferometer Digitizer", serial number = the board's flash ID.+3. With `picotool` instead: `picotool load -x smi_pico.uf2` while the Pico is in BOOTSEL mode.++## What it does++- The ADC runs free at 48 MHz / 96 = 500 ksps in round robin over ADC0 and ADC1, so each channel gets 250 ksps and channel 2 is sampled 2 us after channel 1. Even samples are always ADC0 because acquisition restarts at input 0.+- Two DMA channels, chained ping-pong, fill a ring of 16 buffers of 1024 pairs (4.1 ms each, 65 ms of slack for USB stalls). If the ring overruns, the buffer is counted as dropped and the host sees the gap in the sample index.+- A GPIO interrupt on both edges of GPIO15 reads the live DMA position, so every SYNC edge carries the index of the sample pair it landed on (resolution one pair, 4 us, plus interrupt latency) and a `time_us_32` timestamp.+- The main loop packs each finished buffer into one DATA frame and writes it to USB CDC. A STATUS frame every 0.5 s reports the pair count, dropped buffers and lost SYNC events.+- Streaming starts when the host opens the port (DTR) and stops when it closes it. Text commands, one per line: `start`, `stop`, `info`.++## Stream format++All fields little-endian. Every frame:++| Bytes | Field |+|---|---|+| 2 | sync word `A5 5A` |+| 1 | type: 1 DATA, 2 SYNC, 3 STATUS, 4 INFO |+| 1 | flags, 0 |+| 2 | payload length |+| 2 | sequence number, wraps |+| n | payload |+| 2 | CRC-16/CCITT-FALSE (poly 0x1021, init 0xFFFF) over type through the end of the payload |++DATA payload: `u64 first_pair`, `u32 t_us` (time the DMA buffer completed), `u8 groups` (16), then for each group of 64 pairs a channel 1 block and a channel 2 block. A block is `u16 head` (bits 0 to 11 the first sample, bits 12 to 15 a width code `w`) followed by 63 values packed LSB first and padded to a byte: for `w` from 0 to 12 they are zigzag-encoded deltas of `w` bits, for `w` = 15 they are raw 12-bit samples (used when the deltas would need 13 bits).++SYNC payload: `u64 pair`, `u32 t_us`, `u8 level`. STATUS payload: `u64 pairs`, `u32 dropped_buffers`, `u32 sync_lost`, `u32 total_sps`, `u32 t_us`. INFO payload: ASCII text with the version and rates.++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.++## Building++```+export PICO_SDK_PATH=/path/to/pico-sdk # tested with 2.1.1 and its lib/tinyusb submodule+cmake -S . -B build -DCMAKE_BUILD_TYPE=Release+cmake --build build -j # build/smi_pico.uf2+```++Toolchain used for the published file: arm-none-eabi-gcc 13.2 on Ubuntu 24.04. The first configure downloads and builds picotool, which the SDK uses to make the .uf2.++## Tests++`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.++```+gcc -O2 -Isrc -o test_pack test/test_pack.c src/smi_frame.c -lm && ./test_pack test/vectors.bin+```
software/firmware/pico_sdk_import.cmakeadded+121@@ -0,0 +1,121 @@+# This is a copy of <PICO_SDK_PATH>/external/pico_sdk_import.cmake++# This can be dropped into an external project to help locate this SDK+# It should be include()ed prior to project()++# Copyright 2020 (c) 2020 Raspberry Pi (Trading) Ltd.+#+# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the+# following conditions are met:+#+# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following+# disclaimer.+#+# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following+# disclaimer in the documentation and/or other materials provided with the distribution.+#+# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products+# derived from this software without specific prior written permission.+#+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,+# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE+# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR+# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,+# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF+# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.++if (DEFINED ENV{PICO_SDK_PATH} AND (NOT PICO_SDK_PATH))+ set(PICO_SDK_PATH $ENV{PICO_SDK_PATH})+ message("Using PICO_SDK_PATH from environment ('${PICO_SDK_PATH}')")+endif ()++if (DEFINED ENV{PICO_SDK_FETCH_FROM_GIT} AND (NOT PICO_SDK_FETCH_FROM_GIT))+ set(PICO_SDK_FETCH_FROM_GIT $ENV{PICO_SDK_FETCH_FROM_GIT})+ message("Using PICO_SDK_FETCH_FROM_GIT from environment ('${PICO_SDK_FETCH_FROM_GIT}')")+endif ()++if (DEFINED ENV{PICO_SDK_FETCH_FROM_GIT_PATH} AND (NOT PICO_SDK_FETCH_FROM_GIT_PATH))+ set(PICO_SDK_FETCH_FROM_GIT_PATH $ENV{PICO_SDK_FETCH_FROM_GIT_PATH})+ message("Using PICO_SDK_FETCH_FROM_GIT_PATH from environment ('${PICO_SDK_FETCH_FROM_GIT_PATH}')")+endif ()++if (DEFINED ENV{PICO_SDK_FETCH_FROM_GIT_TAG} AND (NOT PICO_SDK_FETCH_FROM_GIT_TAG))+ set(PICO_SDK_FETCH_FROM_GIT_TAG $ENV{PICO_SDK_FETCH_FROM_GIT_TAG})+ message("Using PICO_SDK_FETCH_FROM_GIT_TAG from environment ('${PICO_SDK_FETCH_FROM_GIT_TAG}')")+endif ()++if (PICO_SDK_FETCH_FROM_GIT AND NOT PICO_SDK_FETCH_FROM_GIT_TAG)+ set(PICO_SDK_FETCH_FROM_GIT_TAG "master")+ message("Using master as default value for PICO_SDK_FETCH_FROM_GIT_TAG")+endif()++set(PICO_SDK_PATH "${PICO_SDK_PATH}" CACHE PATH "Path to the Raspberry Pi Pico SDK")+set(PICO_SDK_FETCH_FROM_GIT "${PICO_SDK_FETCH_FROM_GIT}" CACHE BOOL "Set to ON to fetch copy of SDK from git if not otherwise locatable")+set(PICO_SDK_FETCH_FROM_GIT_PATH "${PICO_SDK_FETCH_FROM_GIT_PATH}" CACHE FILEPATH "location to download SDK")+set(PICO_SDK_FETCH_FROM_GIT_TAG "${PICO_SDK_FETCH_FROM_GIT_TAG}" CACHE FILEPATH "release tag for SDK")++if (NOT PICO_SDK_PATH)+ if (PICO_SDK_FETCH_FROM_GIT)+ include(FetchContent)+ set(FETCHCONTENT_BASE_DIR_SAVE ${FETCHCONTENT_BASE_DIR})+ if (PICO_SDK_FETCH_FROM_GIT_PATH)+ get_filename_component(FETCHCONTENT_BASE_DIR "${PICO_SDK_FETCH_FROM_GIT_PATH}" REALPATH BASE_DIR "${CMAKE_SOURCE_DIR}")+ endif ()+ FetchContent_Declare(+ pico_sdk+ GIT_REPOSITORY https://github.com/raspberrypi/pico-sdk+ GIT_TAG ${PICO_SDK_FETCH_FROM_GIT_TAG}+ )++ if (NOT pico_sdk)+ message("Downloading Raspberry Pi Pico SDK")+ # GIT_SUBMODULES_RECURSE was added in 3.17+ if (${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.17.0")+ FetchContent_Populate(+ pico_sdk+ QUIET+ GIT_REPOSITORY https://github.com/raspberrypi/pico-sdk+ GIT_TAG ${PICO_SDK_FETCH_FROM_GIT_TAG}+ GIT_SUBMODULES_RECURSE FALSE++ SOURCE_DIR ${FETCHCONTENT_BASE_DIR}/pico_sdk-src+ BINARY_DIR ${FETCHCONTENT_BASE_DIR}/pico_sdk-build+ SUBBUILD_DIR ${FETCHCONTENT_BASE_DIR}/pico_sdk-subbuild+ )+ else ()+ FetchContent_Populate(+ pico_sdk+ QUIET+ GIT_REPOSITORY https://github.com/raspberrypi/pico-sdk+ GIT_TAG ${PICO_SDK_FETCH_FROM_GIT_TAG}++ SOURCE_DIR ${FETCHCONTENT_BASE_DIR}/pico_sdk-src+ BINARY_DIR ${FETCHCONTENT_BASE_DIR}/pico_sdk-build+ SUBBUILD_DIR ${FETCHCONTENT_BASE_DIR}/pico_sdk-subbuild+ )+ endif ()++ set(PICO_SDK_PATH ${pico_sdk_SOURCE_DIR})+ endif ()+ set(FETCHCONTENT_BASE_DIR ${FETCHCONTENT_BASE_DIR_SAVE})+ else ()+ message(FATAL_ERROR+ "SDK location was not specified. Please set PICO_SDK_PATH or set PICO_SDK_FETCH_FROM_GIT to on to fetch from git."+ )+ endif ()+endif ()++get_filename_component(PICO_SDK_PATH "${PICO_SDK_PATH}" REALPATH BASE_DIR "${CMAKE_BINARY_DIR}")+if (NOT EXISTS ${PICO_SDK_PATH})+ message(FATAL_ERROR "Directory '${PICO_SDK_PATH}' not found")+endif ()++set(PICO_SDK_INIT_CMAKE_FILE ${PICO_SDK_PATH}/pico_sdk_init.cmake)+if (NOT EXISTS ${PICO_SDK_INIT_CMAKE_FILE})+ message(FATAL_ERROR "Directory '${PICO_SDK_PATH}' does not appear to contain the Raspberry Pi Pico SDK")+endif ()++set(PICO_SDK_PATH ${PICO_SDK_PATH} CACHE PATH "Path to the Raspberry Pi Pico SDK" FORCE)++include(${PICO_SDK_INIT_CMAKE_FILE})
software/firmware/src/main.cadded+281@@ -0,0 +1,281 @@+// SPDX-License-Identifier: MIT+// Self-mixing interferometer digitizer for the Raspberry Pi Pico (RP2040).+//+// ADC0 (GPIO26) = channel 1, laser monitor photodiode after the analog chain.+// ADC1 (GPIO27) = channel 2, external photodiode.+// GPIO15 = SYNC from the motion stage (SN74LVC1G17 buffer, non-inverting).+//+// The ADC free-runs in round-robin over inputs 0 and 1 at 48 MHz / 96 = 500 ksps+// total (250 ksps per channel). DMA moves samples into a ring of buffers+// (two channels chained ping-pong). The main loop packs each finished buffer+// into a DATA frame (delta-encoded 64-sample blocks with a per-block bit width,+// CRC-16) and writes it to USB CDC. SYNC edges are captured by a GPIO interrupt+// that reads the live DMA position, so each edge carries the sample-pair index+// it landed on.+//+// Streaming starts when the host asserts DTR (opens the port) and stops when it+// drops. Text commands, one per line: "start", "stop", "info".++#include <stdio.h>+#include <string.h>+#include "pico/stdlib.h"+#include "hardware/adc.h"+#include "hardware/dma.h"+#include "hardware/gpio.h"+#include "hardware/irq.h"+#include "hardware/sync.h"+#include "tusb.h"+#include "smi_frame.h"++#define FW_VERSION "1.0.0"+#define SYNC_GPIO 15+#define PAIRS_PER_BUF 1024+#define SAMPLES_PER_BUF (PAIRS_PER_BUF * 2)+#define NBUF 16+#define TOTAL_SPS 500000u+#define SYNC_QUEUE 64++static uint16_t bufs[NBUF][SAMPLES_PER_BUF] __attribute__((aligned(4)));+static int dma_a, dma_b;++// Written by the DMA IRQ, read by the main loop.+static volatile uint32_t bufs_done; // buffers completed since start+static volatile uint32_t buf_done_us[NBUF];+static volatile uint32_t dropped_bufs;+static volatile uint32_t bufs_sent; // buffers handed to USB (main loop only)+static volatile bool running;++typedef struct { uint64_t pair; uint32_t t_us; uint8_t level; } sync_evt_t;+static sync_evt_t sync_q[SYNC_QUEUE];+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 void dma_irq(void) {+ uint32_t mask = dma_hw->ints0;+ // Handle in completion order: the even buffer channel (A) finishes before B.+ for (int k = 0; k < 2; k++) {+ int ch = ((bufs_done & 1) == 0) ? dma_a : dma_b;+ if (!(mask & (1u << ch))) break;+ dma_hw->ints0 = 1u << ch;+ mask &= ~(1u << ch);+ uint32_t idx = bufs_done % NBUF;+ buf_done_us[idx] = time_us_32();+ bufs_done++;+ // This channel's next target is two buffers ahead. If the main loop has+ // not packed that buffer yet it is overwritten and counted as dropped.+ uint32_t next = bufs_done + 1;+ if (next - bufs_sent >= NBUF) dropped_bufs++;+ dma_channel_set_write_addr(ch, bufs[next % NBUF], false);+ dma_channel_set_trans_count(ch, SAMPLES_PER_BUF, false);+ }+ if (mask) dma_hw->ints0 = mask;+}++static void sync_irq(uint gpio, uint32_t events) {+ (void)gpio;+ uint32_t now = time_us_32();+ // Locate the DMA write position: the busy channel holds buffer bufs_done,+ // unless a completion is pending, in which case it holds bufs_done + 1.+ uint32_t done = bufs_done;+ int expect = (done & 1) == 0 ? dma_a : dma_b;+ int other = expect == dma_a ? dma_b : dma_a;+ uint32_t base, remaining;+ if (dma_channel_is_busy(expect)) {+ base = done; remaining = dma_hw->ch[expect].transfer_count;+ } else {+ base = done + 1; remaining = dma_hw->ch[other].transfer_count;+ }+ uint64_t sample = (uint64_t)base * SAMPLES_PER_BUF + (SAMPLES_PER_BUF - remaining);+ if (sync_count >= SYNC_QUEUE) { sync_lost++; return; }+ sync_evt_t *e = &sync_q[sync_head];+ e->pair = sample / 2;+ e->t_us = now;+ e->level = (events & GPIO_IRQ_EDGE_RISE) ? 1 : 0;+ sync_head = (sync_head + 1) % SYNC_QUEUE;+ sync_count++;+}++static void dma_setup(void) {+ dma_a = dma_claim_unused_channel(true);+ dma_b = dma_claim_unused_channel(true);+ int chans[2] = {dma_a, dma_b};+ for (int i = 0; i < 2; i++) {+ dma_channel_config c = dma_channel_get_default_config(chans[i]);+ channel_config_set_transfer_data_size(&c, DMA_SIZE_16);+ channel_config_set_read_increment(&c, false);+ channel_config_set_write_increment(&c, true);+ channel_config_set_dreq(&c, DREQ_ADC);+ channel_config_set_chain_to(&c, chans[1 - i]);+ dma_channel_configure(chans[i], &c, bufs[i], &adc_hw->fifo, SAMPLES_PER_BUF, false);+ }+ dma_channel_set_irq0_enabled(dma_a, true);+ dma_channel_set_irq0_enabled(dma_b, true);+ irq_set_exclusive_handler(DMA_IRQ_0, dma_irq);+ irq_set_priority(DMA_IRQ_0, 0x40);+ irq_set_enabled(DMA_IRQ_0, true);+}++static void acq_start(void) {+ if (running) return;+ adc_run(false);+ dma_channel_abort(dma_a);+ dma_channel_abort(dma_b);+ adc_fifo_drain();+ bufs_done = 0; bufs_sent = 0; dropped_bufs = 0;+ sync_head = sync_tail = sync_count = 0;+ dma_channel_set_write_addr(dma_a, bufs[0], false);+ dma_channel_set_trans_count(dma_a, SAMPLES_PER_BUF, false);+ dma_channel_set_write_addr(dma_b, bufs[1], false);+ dma_channel_set_trans_count(dma_b, SAMPLES_PER_BUF, false);+ adc_select_input(0); // round robin begins at ADC0, so even samples are ch0+ adc_set_round_robin(0x3);+ dma_channel_start(dma_a);+ running = true;+ adc_run(true);+}++static void acq_stop(void) {+ adc_run(false);+ running = false;+ dma_channel_abort(dma_a);+ dma_channel_abort(dma_b);+ adc_fifo_drain();+}++// Blocking-with-service write of a whole frame to CDC.+static bool cdc_write_all(const uint8_t *p, size_t n) {+ while (n) {+ if (!tud_cdc_connected()) return false;+ uint32_t avail = tud_cdc_write_available();+ if (avail == 0) { tud_task(); continue; }+ uint32_t k = n < avail ? (uint32_t)n : avail;+ k = tud_cdc_write(p, k);+ p += k; n -= k;+ tud_cdc_write_flush();+ tud_task();+ }+ return true;+}++static void send_data(uint32_t b) {+ const uint16_t *s = bufs[b % NBUF];+ uint8_t *pl = frame + SMI_HDR_LEN;+ smi_put_u64(pl, (uint64_t)b * PAIRS_PER_BUF);+ smi_put_u32(pl + 8, buf_done_us[b % NBUF]);+ pl[12] = PAIRS_PER_BUF / SMI_BLOCK;+ size_t o = 13;+ for (int g = 0; g < PAIRS_PER_BUF / SMI_BLOCK; g++) {+ const uint16_t *base = s + g * SMI_BLOCK * 2;+ o += smi_pack_block(base, 2, pl + o); // ch0: even samples+ o += smi_pack_block(base + 1, 2, pl + o); // ch1: odd samples+ }+ smi_begin_frame(frame, SMI_T_DATA, (uint16_t)o, seq++);+ size_t n = smi_finish_frame(frame, (uint16_t)o);+ cdc_write_all(frame, n);+}++static void send_sync(const sync_evt_t *e) {+ uint8_t f[SMI_HDR_LEN + 13 + 2];+ uint8_t *pl = f + SMI_HDR_LEN;+ smi_put_u64(pl, e->pair);+ smi_put_u32(pl + 8, e->t_us);+ pl[12] = e->level;+ smi_begin_frame(f, SMI_T_SYNC, 13, seq++);+ cdc_write_all(f, smi_finish_frame(f, 13));+}++static void send_status(void) {+ uint8_t f[SMI_HDR_LEN + 24 + 2];+ uint8_t *pl = f + SMI_HDR_LEN;+ smi_put_u64(pl, (uint64_t)bufs_done * PAIRS_PER_BUF);+ smi_put_u32(pl + 8, dropped_bufs);+ smi_put_u32(pl + 12, sync_lost);+ smi_put_u32(pl + 16, TOTAL_SPS);+ smi_put_u32(pl + 20, time_us_32());+ smi_begin_frame(f, SMI_T_STATUS, 24, seq++);+ cdc_write_all(f, smi_finish_frame(f, 24));+}++static void send_info(void) {+ char txt[160];+ int n = snprintf(txt, sizeof txt,+ "smi-pico fw " FW_VERSION "; total_sps=%u; per_channel_sps=%u; pairs_per_frame=%u; block=%u; sync_gpio=%u",+ TOTAL_SPS, TOTAL_SPS / 2, PAIRS_PER_BUF, SMI_BLOCK, SYNC_GPIO);+ uint8_t f[SMI_HDR_LEN + 160 + 2];+ memcpy(f + SMI_HDR_LEN, txt, (size_t)n);+ smi_begin_frame(f, SMI_T_INFO, (uint16_t)n, seq++);+ cdc_write_all(f, smi_finish_frame(f, (uint16_t)n));+}++static char cmd[32];+static int cmd_len;++static void poll_commands(void) {+ while (tud_cdc_available()) {+ int c = tud_cdc_read_char();+ if (c < 0) break;+ if (c == '\n' || c == '\r') {+ cmd[cmd_len] = 0;+ if (!strcmp(cmd, "start")) acq_start();+ else if (!strcmp(cmd, "stop")) acq_stop();+ else if (!strcmp(cmd, "info")) send_info();+ cmd_len = 0;+ } else if (cmd_len < (int)sizeof cmd - 1) {+ cmd[cmd_len++] = (char)c;+ }+ }+}++int main(void) {+ tusb_init();++ adc_init();+ adc_gpio_init(26);+ adc_gpio_init(27);+ // FIFO on, DREQ on, DREQ threshold 1, no error bit, no byte shift (12-bit samples).+ adc_fifo_setup(true, true, 1, false, false);+ adc_set_clkdiv(0); // back-to-back: 96 ADC clocks = 2 us per conversion+ dma_setup();++ gpio_init(SYNC_GPIO);+ gpio_set_dir(SYNC_GPIO, GPIO_IN);+ gpio_disable_pulls(SYNC_GPIO); // R151 on the board holds the buffer input low+ gpio_set_irq_enabled_with_callback(SYNC_GPIO, GPIO_IRQ_EDGE_RISE | GPIO_IRQ_EDGE_FALL, true, sync_irq);++ bool was_connected = false;+ uint32_t last_status = 0;+ while (true) {+ tud_task();+ bool conn = tud_cdc_connected();+ if (conn && !was_connected) { send_info(); acq_start(); }+ if (!conn && was_connected) acq_stop();+ was_connected = conn;+ if (!conn) continue;+ poll_commands();++ while (sync_count) {+ sync_evt_t e = sync_q[sync_tail];+ sync_tail = (sync_tail + 1) % SYNC_QUEUE;+ uint32_t irq = save_and_disable_interrupts();+ sync_count--;+ restore_interrupts(irq);+ send_sync(&e);+ }++ while (running && bufs_sent < bufs_done) {+ uint32_t done = bufs_done;+ if (done - bufs_sent >= NBUF - 1) {+ // Fell behind: skip to the newest complete buffers. The host sees the+ // gap in first_pair and the STATUS frame counts it.+ bufs_sent = done - 2;+ }+ send_data(bufs_sent);+ bufs_sent++;+ }++ uint32_t now = time_us_32();+ if (now - last_status > 500000) { last_status = now; send_status(); }+ }+}
software/firmware/src/smi_frame.cadded+94@@ -0,0 +1,94 @@+// SPDX-License-Identifier: MIT+#include "smi_frame.h"++uint16_t smi_crc16(const uint8_t *p, size_t n, uint16_t crc) {+ // CRC-16/CCITT-FALSE: poly 0x1021, init 0xFFFF, no reflection, no xorout.+ for (size_t i = 0; i < n; i++) {+ crc ^= (uint16_t)p[i] << 8;+ for (int b = 0; b < 8; b++) crc = (crc & 0x8000) ? (uint16_t)((crc << 1) ^ 0x1021) : (uint16_t)(crc << 1);+ }+ return crc;+}++static inline uint32_t zigzag(int32_t d) { return ((uint32_t)d << 1) ^ (uint32_t)(d >> 31); }+static inline int32_t unzigzag(uint32_t z) { return (int32_t)(z >> 1) ^ -(int32_t)(z & 1); }++size_t smi_pack_block(const uint16_t *s, size_t stride, uint8_t *dst) {+ uint32_t zz[SMI_BLOCK - 1];+ uint32_t all = 0;+ uint16_t prev = s[0] & 0x0FFF;+ for (int i = 1; i < SMI_BLOCK; i++) {+ uint16_t v = s[i * stride] & 0x0FFF;+ zz[i - 1] = zigzag((int32_t)v - (int32_t)prev);+ all |= zz[i - 1];+ prev = v;+ }+ unsigned w = 0;+ while (w < 32 && (all >> w)) w++;+ unsigned code = w;+ if (w > 12) {+ code = SMI_RAW_CODE;+ w = 12;+ for (int i = 1; i < SMI_BLOCK; i++) zz[i - 1] = s[i * stride] & 0x0FFF;+ }+ smi_put_u16(dst, (uint16_t)((s[0] & 0x0FFF) | (code << 12)));+ size_t o = 2;+ if (w == 0) return o;+ uint32_t acc = 0;+ unsigned nb = 0;+ for (int i = 0; i < SMI_BLOCK - 1; i++) {+ acc |= zz[i] << nb;+ nb += w;+ while (nb >= 8) { dst[o++] = (uint8_t)acc; acc >>= 8; nb -= 8; }+ }+ if (nb) dst[o++] = (uint8_t)acc;+ return o;+}++size_t smi_unpack_block(const uint8_t *src, size_t avail, uint16_t *out) {+ if (avail < 2) return 0;+ uint16_t head = (uint16_t)(src[0] | (src[1] << 8));+ unsigned code = head >> 12;+ out[0] = head & 0x0FFF;+ if (code > 12 && code != SMI_RAW_CODE) return 0;+ unsigned w = code == SMI_RAW_CODE ? 12 : code;+ size_t need = 2 + (63 * w + 7) / 8;+ if (avail < need) return 0;+ uint32_t acc = 0;+ unsigned nb = 0;+ size_t o = 2;+ int32_t prev = out[0];+ for (int i = 1; i < SMI_BLOCK; i++) {+ uint32_t z = 0;+ if (w) {+ while (nb < w) { acc |= (uint32_t)src[o++] << nb; nb += 8; }+ z = acc & ((1u << w) - 1);+ acc >>= w;+ nb -= w;+ }+ if (code == SMI_RAW_CODE) {+ out[i] = (uint16_t)z;+ } else {+ prev += unzigzag(z);+ if (prev < 0 || prev > 4095) return 0;+ out[i] = (uint16_t)prev;+ }+ }+ return need;+}++void smi_begin_frame(uint8_t *dst, uint8_t type, uint16_t payload_len, uint16_t seq) {+ dst[0] = SMI_SYNC0;+ dst[1] = SMI_SYNC1;+ dst[2] = type;+ dst[3] = 0;+ smi_put_u16(dst + 4, payload_len);+ smi_put_u16(dst + 6, seq);+}++size_t smi_finish_frame(uint8_t *frame, uint16_t payload_len) {+ size_t end = SMI_HDR_LEN + payload_len;+ uint16_t crc = smi_crc16(frame + 2, end - 2, 0xFFFF);+ smi_put_u16(frame + end, crc);+ return end + 2;+}
software/firmware/src/smi_frame.hadded+59@@ -0,0 +1,59 @@+// SPDX-License-Identifier: MIT+// Framing and block packing for the self-mixing interferometer stream.+// Portable C99: built into the Pico firmware and into the host-side test.+//+// Frame (all fields little-endian):+// 0xA5 0x5A sync word+// u8 type SMI_T_DATA, SMI_T_SYNC, SMI_T_STATUS, SMI_T_INFO+// u8 flags reserved, 0+// u16 payload_len+// u16 seq per-frame counter, wraps+// ... payload ...+// u16 crc CRC-16/CCITT-FALSE over type..end of payload+//+// DATA payload:+// u64 first_pair index of the first ADC0/ADC1 sample pair in this frame+// u32 t_us time_us_32() when the DMA buffer completed+// u8 n_groups groups of 64 pairs; each group is a ch0 block then a ch1 block+// blocks...+// Block (64 samples of one channel):+// u16 head bits 0..11 first sample, bits 12..15 width code w+// payload w in 0..12: 63 zigzag deltas of w bits each, LSB first+// w == 15: 63 raw 12-bit samples, LSB first+// padded to a whole byte+#ifndef SMI_FRAME_H+#define SMI_FRAME_H++#include <stdint.h>+#include <stddef.h>++#define SMI_SYNC0 0xA5+#define SMI_SYNC1 0x5A+#define SMI_T_DATA 1+#define SMI_T_SYNC 2+#define SMI_T_STATUS 3+#define SMI_T_INFO 4++#define SMI_BLOCK 64+#define SMI_RAW_CODE 15+#define SMI_HDR_LEN 8+#define SMI_MAX_BLOCK_BYTES (2 + (63 * 12 + 7) / 8)++uint16_t smi_crc16(const uint8_t *p, size_t n, uint16_t crc);++// Pack 64 samples (12-bit values) into dst. Returns bytes written.+size_t smi_pack_block(const uint16_t *s, size_t stride, uint8_t *dst);++// Unpack one block. Returns bytes consumed, or 0 on malformed input.+size_t smi_unpack_block(const uint8_t *src, size_t avail, uint16_t *out);++// Write a frame header at dst[0..8). Fill in the CRC with smi_finish_frame.+void smi_begin_frame(uint8_t *dst, uint8_t type, uint16_t payload_len, uint16_t seq);+// Appends the CRC after the payload; returns the total frame length.+size_t smi_finish_frame(uint8_t *frame, uint16_t payload_len);++static inline void smi_put_u16(uint8_t *p, uint16_t v) { p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); }+static inline void smi_put_u32(uint8_t *p, uint32_t v) { for (int i = 0; i < 4; i++) p[i] = (uint8_t)(v >> (8 * i)); }+static inline void smi_put_u64(uint8_t *p, uint64_t v) { for (int i = 0; i < 8; i++) p[i] = (uint8_t)(v >> (8 * i)); }++#endif
software/firmware/src/tusb_config.hadded+16@@ -0,0 +1,16 @@+// SPDX-License-Identifier: MIT+#ifndef TUSB_CONFIG_H+#define TUSB_CONFIG_H+#define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_FULL_SPEED)+#define CFG_TUSB_OS OPT_OS_PICO+#define CFG_TUD_ENABLED 1+#define CFG_TUD_ENDPOINT0_SIZE 64+#define CFG_TUD_CDC 1+#define CFG_TUD_MSC 0+#define CFG_TUD_HID 0+#define CFG_TUD_MIDI 0+#define CFG_TUD_VENDOR 0+#define CFG_TUD_CDC_RX_BUFSIZE 256+#define CFG_TUD_CDC_TX_BUFSIZE 8192+#define CFG_TUD_CDC_EP_BUFSIZE 64+#endif
software/firmware/src/usb_descriptors.cadded+71@@ -0,0 +1,71 @@+// SPDX-License-Identifier: MIT+// USB descriptors: one CDC ACM interface. The serial number string is the+// RP2040 flash unique ID so several Picos can be told apart on one host.+#include <string.h>+#include "tusb.h"+#include "pico/unique_id.h"++#define USBD_VID 0x2E8A // Raspberry Pi+#define USBD_PID 0x000A // Raspberry Pi Pico SDK CDC+#define EPNUM_CDC_NOTIF 0x81+#define EPNUM_CDC_OUT 0x02+#define EPNUM_CDC_IN 0x82++static const tusb_desc_device_t desc_device = {+ .bLength = sizeof(tusb_desc_device_t),+ .bDescriptorType = TUSB_DESC_DEVICE,+ .bcdUSB = 0x0200,+ .bDeviceClass = TUSB_CLASS_MISC,+ .bDeviceSubClass = MISC_SUBCLASS_COMMON,+ .bDeviceProtocol = MISC_PROTOCOL_IAD,+ .bMaxPacketSize0 = CFG_TUD_ENDPOINT0_SIZE,+ .idVendor = USBD_VID,+ .idProduct = USBD_PID,+ .bcdDevice = 0x0100,+ .iManufacturer = 1,+ .iProduct = 2,+ .iSerialNumber = 3,+ .bNumConfigurations = 1,+};++const uint8_t *tud_descriptor_device_cb(void) { return (const uint8_t *)&desc_device; }++enum { ITF_NUM_CDC = 0, ITF_NUM_CDC_DATA, ITF_NUM_TOTAL };+#define CONFIG_TOTAL_LEN (TUD_CONFIG_DESC_LEN + TUD_CDC_DESC_LEN)++static const uint8_t desc_cfg[] = {+ TUD_CONFIG_DESCRIPTOR(1, ITF_NUM_TOTAL, 0, CONFIG_TOTAL_LEN, 0, 250),+ TUD_CDC_DESCRIPTOR(ITF_NUM_CDC, 4, EPNUM_CDC_NOTIF, 8, EPNUM_CDC_OUT, EPNUM_CDC_IN, 64),+};++const uint8_t *tud_descriptor_configuration_cb(uint8_t index) { (void)index; return desc_cfg; }++static const char *strings[] = {+ "", // 0: language, handled below+ "Adom", // 1: manufacturer+ "SMI Interferometer Digitizer", // 2: product+ NULL, // 3: serial, from the flash unique ID+ "SMI stream", // 4: CDC interface+};++static uint16_t desc_str[33];++const uint16_t *tud_descriptor_string_cb(uint8_t index, uint16_t langid) {+ (void)langid;+ char serial[2 * PICO_UNIQUE_BOARD_ID_SIZE_BYTES + 1];+ const char *s;+ uint8_t n;+ if (index == 0) {+ desc_str[1] = 0x0409;+ n = 1;+ } else {+ if (index >= sizeof strings / sizeof strings[0]) return NULL;+ if (index == 3) { pico_get_unique_board_id_string(serial, sizeof serial); s = serial; }+ else s = strings[index];+ n = (uint8_t)strlen(s);+ if (n > 32) n = 32;+ for (uint8_t i = 0; i < n; i++) desc_str[1 + i] = (uint8_t)s[i];+ }+ desc_str[0] = (uint16_t)((TUSB_DESC_STRING << 8) | (2 * n + 2));+ return desc_str;+}
software/firmware/test/stream_gen.cadded+38@@ -0,0 +1,38 @@+// SPDX-License-Identifier: MIT+// Test helper: read raw little-endian u16 sample pairs (ch0, ch1) from stdin and+// write the firmware's framed stream to stdout, 1024 pairs per DATA frame, with a+// SYNC rising edge frame every `sync_every` pairs (argv[1], 0 = none). Uses the+// firmware's own smi_frame.c, so the dashboard is tested against the real packer.+#include <stdio.h>+#include <stdlib.h>+#include "smi_frame.h"++int main(int argc, char **argv) {+ long sync_every = argc > 1 ? atol(argv[1]) : 0;+ static uint16_t pairs[2048];+ static uint8_t frame[8 + 13 + 32 * SMI_MAX_BLOCK_BYTES + 2];+ uint64_t first = 0;+ uint16_t seq = 0;+ while (fread(pairs, 4, 1024, stdin) == 1024) {+ if (sync_every && (first / sync_every) != ((first + 1024) / sync_every)) {+ uint8_t f[8 + 13 + 2];+ uint64_t at = ((first + 1024) / sync_every) * sync_every;+ smi_put_u64(f + 8, at); smi_put_u32(f + 16, 0); f[20] = 1;+ smi_begin_frame(f, SMI_T_SYNC, 13, seq++);+ fwrite(f, 1, smi_finish_frame(f, 13), stdout);+ }+ uint8_t *pl = frame + 8;+ smi_put_u64(pl, first);+ smi_put_u32(pl + 8, (uint32_t)(first * 2));+ pl[12] = 16;+ size_t o = 13;+ for (int g = 0; g < 16; g++) {+ o += smi_pack_block(pairs + g * 128, 2, pl + o);+ o += smi_pack_block(pairs + g * 128 + 1, 2, pl + o);+ }+ smi_begin_frame(frame, SMI_T_DATA, (uint16_t)o, seq++);+ fwrite(frame, 1, smi_finish_frame(frame, (uint16_t)o), stdout);+ first += 1024;+ }+ return 0;+}
software/firmware/test/test_pack.cadded+69@@ -0,0 +1,69 @@+// SPDX-License-Identifier: MIT+// Host-side round-trip test of the block packer and frame CRC, and a writer of+// a reference stream (test/vectors.bin) that the dashboard's Rust decoder+// checks against in its own unit tests.+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <math.h>+#include "smi_frame.h"++static unsigned rng = 12345;+static unsigned rnd(void) { rng = rng * 1103515245u + 12345u; return (rng >> 16) & 0x7fff; }++int main(int argc, char **argv) {+ const char *out = argc > 1 ? argv[1] : "vectors.bin";+ int fails = 0;+ uint16_t s[2 * SMI_BLOCK], back[SMI_BLOCK];+ uint8_t buf[SMI_MAX_BLOCK_BYTES];+ size_t bytes_total = 0, samples_total = 0;+ for (int t = 0; t < 20000; t++) {+ int kind = t % 4;+ for (int i = 0; i < 2 * SMI_BLOCK; i++) {+ double x = 2048 + 1500 * sin((t * 128 + i) * 0.01 * (1 + kind));+ if (kind == 0) s[i] = (uint16_t)(x + rnd() % 8); // slow signal plus noise+ else if (kind == 1) s[i] = (uint16_t)(rnd() & 0x0FFF); // white noise: forces raw+ else if (kind == 2) s[i] = 1000; // constant: width 0+ else s[i] = (uint16_t)((i * 37 + t) & 0x0FFF); // sawtooth with wraps+ }+ for (int ch = 0; ch < 2; ch++) {+ size_t n = smi_pack_block(s + ch, 2, buf);+ size_t m = smi_unpack_block(buf, n, back);+ bytes_total += n; samples_total += SMI_BLOCK;+ if (m != n) { fails++; continue; }+ for (int i = 0; i < SMI_BLOCK; i++) if (back[i] != s[ch + 2 * i]) { fails++; break; }+ }+ }+ // CRC-16/CCITT-FALSE check value for "123456789" is 0x29B1.+ uint16_t c = smi_crc16((const uint8_t *)"123456789", 9, 0xFFFF);+ if (c != 0x29B1) { printf("ERROR: crc16 check value %04X, expected 29B1\n", c); fails++; }++ // Reference stream: 4 DATA frames of 1024 pairs with a known ramp signal.+ FILE *f = fopen(out, "wb");+ if (!f) { printf("ERROR: cannot write %s\n", out); return 1; }+ static uint8_t frame[8 + 13 + 32 * SMI_MAX_BLOCK_BYTES + 2];+ for (int fr = 0; fr < 4; fr++) {+ static uint16_t pairs[2048];+ for (int i = 0; i < 1024; i++) {+ long n = fr * 1024L + i;+ pairs[2 * i] = (uint16_t)(2048 + 1200 * sin(n * 0.05));+ pairs[2 * i + 1] = (uint16_t)((n * 7) % 4096);+ }+ uint8_t *pl = frame + 8;+ smi_put_u64(pl, (uint64_t)fr * 1024);+ smi_put_u32(pl + 8, 1000u + 2048u * (unsigned)fr);+ pl[12] = 16;+ size_t o = 13;+ for (int g = 0; g < 16; g++) {+ o += smi_pack_block(pairs + g * 128, 2, pl + o);+ o += smi_pack_block(pairs + g * 128 + 1, 2, pl + o);+ }+ smi_begin_frame(frame, SMI_T_DATA, (uint16_t)o, (uint16_t)fr);+ fwrite(frame, 1, smi_finish_frame(frame, (uint16_t)o), f);+ }+ fclose(f);+ if (fails) { printf("ERROR: %d round-trip failures\n", fails); return 1; }+ printf("OK: 40000 blocks round-trip exactly; crc16 check 29B1; mean %.2f bits/sample incl. headers; wrote %s\n",+ 8.0 * bytes_total / samples_total, out);+ return 0;+}
software/firmware/test/vectors.binadded⋯ 1 unchanged line ⋯
software/screenshots/dashboard-constant-speed.pngadded⋯ 1 unchanged line ⋯
software/screenshots/direction-reversal.pngadded⋯ 1 unchanged line ⋯
software/screenshots/multimode-fading.pngadded⋯ 1 unchanged line ⋯
software/screenshots/settings.pngadded⋯ 1 unchanged line ⋯
software/screenshots/sine-return-to-zero.pngadded⋯ 1 unchanged line ⋯