main
John Lauer Software 1.3.1: test-stage firmware (J4 TMC2209, HOME, limits, self-test), Stage tab and Calibrate in smi-dash (simulat… c0c5c9b
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194
// 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 controls;
mod dsp;
mod tune;
mod engine;
mod eval;
mod proto;
mod record;
mod server;
mod sim;
mod stage;
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>,
        /// on | off: model board 1.3 (laser current, gains, offsets, bias from the Controls).
        #[arg(long)]
        board: Option<String>,
    },
    /// Laser (board 1.3): laser on --beam-safe | off | current <mA> [--wait] | read.
    ///
    /// Turning it on needs --beam-safe (the interlock: beam enclosed or eyewear on).
    /// The firmware writes each set-point to the laser head's DAC with the enable
    /// dropped, reads it back, re-arms (the head's soft-start ramps the current),
    /// limits set-point writes to four a second, refuses
    /// anything above the rated current, and turns the laser off if the dashboard
    /// stops sending heartbeats.
    Laser {
        action: String,
        value: Option<f64>,
        #[arg(long = "beam-safe")]
        beam_safe: bool,
        /// With `current`: wait until the set-point is written and the measured current has arrived.
        #[arg(long)]
        wait: bool,
    },
    /// Offsets: offset ch1|ch2 <V> [--counts] | offset auto [ch1|ch2|both].
    ///
    /// auto servoes each channel's mean to mid-scale (2048) with its offset DAC.
    Offset {
        target: String,
        #[arg(allow_hyphen_values = true)]
        value: Option<String>,
        /// The value is DAC counts instead of volts.
        #[arg(long)]
        counts: bool,
    },
    /// Gain switches: gain ch1-tia|ch1-amp|ch2-tia|ch2-amp|<id> <value or label>, e.g. `gain ch1-amp -20`.
    Gain {
        stage: String,
        #[arg(allow_hyphen_values = true)]
        value: String,
    },
    /// Monitor photodiode bias: bias low|mid|high or a value in volts (laser off).
    Bias { value: String },
    /// Any control by id: ctl <id> <value> [--counts | --index].
    Ctl {
        id: String,
        #[arg(allow_hyphen_values = true)]
        value: String,
        #[arg(long)]
        counts: bool,
        #[arg(long)]
        index: bool,
    },
    /// Board state and map: board [state | map | clear-fault | config --isense-hz N --hb-timeout-ms N].
    Board {
        action: Option<String>,
        #[arg(long = "isense-hz")]
        isense_hz: Option<u64>,
        #[arg(long = "hb-timeout-ms")]
        hb_timeout_ms: Option<u64>,
    },
    /// Tune for fringes: step the laser current, re-centre, score fringe contrast, try the second-stage gains.
    ///
    /// Needs the laser on; it never turns it on itself. On board 1.3 (as on 1.2.1) the head
    /// DAC cannot be dithered, so move the target while tuning; changing an
    /// offset or gain briefly turns the laser off and back on at the same
    /// set-point (board rule: no writes while armed). Returns every step's score.
    Tune {
        #[arg(long, default_value_t = 1)]
        channel: u8,
        #[arg(long = "min-ma")]
        min_ma: Option<f64>,
        #[arg(long = "max-ma")]
        max_ma: Option<f64>,
        #[arg(long, default_value_t = 8)]
        steps: usize,
        /// Leave the second-stage gain as it is.
        #[arg(long = "no-gains")]
        no_gains: bool,
        /// Return at once instead of waiting for the result.
        #[arg(long = "no-wait")]
        no_wait: bool,
        #[arg(long)]
        status: bool,
        #[arg(long)]
        stop: bool,
    },
    /// Test stage on the STAGE connector (board 1.3.1 J4, TMC2209 + HOME switch).
    ///
    /// stage [status | home | step N | move POS | speed [PPS] | stop | off | current | selftest | align].
    /// Steps are pulses (15.625 nm nominal at the mirror) or nm with --nm. The
    /// stage is disabled at boot; home it first. Moves stay inside 0..1600
    /// pulses from HOME. home, step, move and selftest wait until done unless
    /// --no-wait. On the simulator every result is labelled simulated.
    Stage {
        action: Option<String>,
        #[arg(allow_negative_numbers = true)]
        value: Option<f64>,
        /// The value is in nm at the mirror (converted with the current scale).
        #[arg(long)]
        nm: bool,
        #[arg(long = "no-wait")]
        no_wait: bool,
        /// selftest: print the last result instead of starting one.
        #[arg(long)]
        status: bool,
    },
    /// Calibrate the board with the stage as the moving target (simulator only for now).
    ///
    /// Homes the stage, records the settings and a counted-against-commanded
    /// step as they are, zeroes the laser current readback with the laser off,
    /// turns it back on, auto-centres, tunes while the stage moves back and
    /// forth, re-checks the step, and prints a before/after report. Turns the
    /// laser on, so it needs --beam-safe.
    Calibrate {
        #[arg(long = "beam-safe")]
        beam_safe: bool,
        /// Pulses for the re-check step (64..1400, default 1024 = 16 um nominal).
        #[arg(long = "check-pulses")]
        check_pulses: Option<i32>,
        #[arg(long = "no-wait")]
        no_wait: bool,
        #[arg(long)]
        status: bool,
        #[arg(long)]
        stop: bool,
    },
    /// Fringe detector parameters.
    Detect {
        #[arg(long = "lp-hz")]
        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 |
    /// ui fullscreen on|off (Hydrogen shows it as a 90% dialog) | ui tab board|sim.
    ///
    /// Selectors: #btn-pause #btn-zero #btn-record #btn-settings #src-sim #src-serial
    /// [data-profile=constant|sine|step|hand|hold] #mm-toggle #c-slider #speed-slider
    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,
        /// Board 1.3 suite: laser current x stage-2 gain through the simulated board.
        #[arg(long)]
        board: bool,
        #[arg(long, default_value = "constant")]
        profile: String,
        #[arg(long, default_value_t = 2.0)]
        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"));
    // Auto-centre with the laser on cycles it for every offset write, so allow it time.
    let secs = if path.starts_with("/board/auto_centre") { 120 } else { 10 };
    let req = ureq::request(method, &url).set("User-Agent", &ua).timeout(std::time::Duration::from_secs(secs));
    let res = match body {
        Some(b) => req.send_json(b),
        None => req.call(),
    };
    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::Laser { .. } | Cmd::Offset { .. } | Cmd::Gain { .. } | Cmd::Bias { .. } | Cmd::Ctl { .. } | Cmd::Board { .. } | Cmd::Tune { .. } => board_cli(&cli, &out),
        Cmd::Stage { .. } | Cmd::Calibrate { .. } => stage_cli(&cli, &out),
        Cmd::Sim { profile, speed_um_s, range_um, amp_um, freq_hz, step_um, jitter_um, c, alpha, m, noise, multimode, wavelength_nm, board } => {
            let port = find_port(&cli, &out);
            let mut b = json!({});
            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));
            }
            if let Some(bd) = board {
                b["board"] = json!(onoff(bd, &out));
            }
            let v = call(&out, port, "POST", "/sim", Some(b));
            let d = &v["data"];
            out.ok(&format!("simulator: profile {}, C {}, multimode {}", d["profile"].as_str().unwrap_or("?"), d["c"], d["multimode"]), d.clone(), &[]);
        }
        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!({}),
                "fullscreen" => json!({"on": onoff(arg.as_deref().unwrap_or("on"), &out)}),
                "tab" => json!({"tab": arg.clone().unwrap_or("board".into())}),
                _ => match arg {
                    Some(sel) => json!({"selector": sel}),
                    None => out.err(&format!("ui {verb} needs a selector"), &[format!("e.g. `smi-dash ui {verb} '#btn-zero'`")]),
                },
            };
            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, board, profile, seconds, c, speed_um_s, multimode, noise, lp_hz } => {
            if *board {
                let t = Instant::now();
                let rows = eval::board_suite();
                out.ok(&format!("board suite of {} cases in {:.1} s\n{}", rows.len(), t.elapsed().as_secs_f64(), eval::board_markdown(&rows)), json!(rows), &[]);
            } else if *suite {
                let t = Instant::now();
                let rows = eval::suite();
                let table = eval::markdown(&rows);
                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()]),
    }
}

fn laser_line(st: &Value) -> String {
    if st.is_null() {
        return "no board state".into();
    }
    let l = &st["laser"];
    let meas = l["measured_mA"].as_f64().map(|m| format!("{m:.2} mA")).unwrap_or("n/a".into());
    let mut m = if l["on"].as_bool() == Some(true) {
        format!("laser ON, set-point {:.2} mA (target {:.2}{}), measured {meas}", l["setpoint_mA"].as_f64().unwrap_or(0.0), l["target_mA"].as_f64().unwrap_or(0.0), if l["ramping"].as_bool() == Some(true) { ", writing" } else { "" })
    } else {
        format!("laser {}, measured {meas}", l["state"].as_str().unwrap_or("off"))
    };
    if st["fault"].as_u64().unwrap_or(0) != 0 {
        m += &format!("; FAULT: {}", st["fault_text"].as_str().unwrap_or(""));
    }
    if st["map_match"] == json!(false) {
        m += "; WARNING: firmware control map differs from the dashboard's";
    }
    m
}

fn controls_lines(st: &Value, map: &Value) -> String {
    let mut lines = vec![];
    if let (Some(cs), Some(ms)) = (st["controls"].as_array(), map["controls"].as_array()) {
        for (c, m) in cs.iter().zip(ms) {
            let v = c["applied"].as_f64().unwrap_or(0.0);
            let lab = c["label"].as_str().map(|l| format!(" ({l})")).unwrap_or_default();
            lines.push(format!("  {:<26} {:>10.4} {}{}  code {}", m["id"].as_str().unwrap_or(""), v, m["unit"].as_str().unwrap_or(""), lab, c["code"]));
        }
    }
    lines.join("\n")
}

fn board_cli(cli: &Cli, out: &Out) {
    let port = find_port(cli, out);
    let set = |id: &str, value: Value, unit: &str| -> Value { call(out, port, "POST", "/board/set", Some(json!({"id": id, "value": value, "unit": unit}))) };
    let num_or_str = |v: &str| -> Value { v.parse::<f64>().map(|x| json!(x)).unwrap_or(json!(v)) };
    let state = || call(out, port, "GET", "/board", None)["data"].clone();
    match &cli.cmd {
        Cmd::Laser { action, value, beam_safe, wait } => match action.as_str() {
            "on" => {
                let mut b = json!({"on": true});
                if *beam_safe {
                    b["confirm"] = json!("beam-safe");
                }
                let v = call(out, port, "POST", "/board/laser", Some(b));
                out.ok(&laser_line(&v["data"]), v["data"].clone(), &hints_of(&v));
            }
            "off" => {
                let v = call(out, port, "POST", "/board/laser", Some(json!({"on": false})));
                out.ok(&laser_line(&v["data"]), v["data"].clone(), &[]);
            }
            "current" => {
                let Some(ma) = value else { out.err("laser current needs a value in mA", &["e.g. `smi-dash laser current 95 --wait`".into()]) };
                let v = set("laser", json!(ma), "units");
                let mut h = hints_of(&v);
                if *wait {
                    let t = Instant::now();
                    loop {
                        let d = state();
                        let l = &d["state"]["laser"];
                        let sp = l["setpoint_mA"].as_f64().unwrap_or(0.0);
                        let arrived = l["measured_mA"].as_f64().is_some_and(|m| (m - sp).abs() < (0.03 * sp).max(1.0));
                        if l["on"].as_bool() != Some(true) || (l["ramping"].as_bool() != Some(true) && (arrived || t.elapsed().as_secs() > 3)) {
                            h.clear();
                            break;
                        }
                        if t.elapsed().as_secs() > 30 {
                            out.err("the set-point did not settle within 30 s", &[]);
                        }
                        std::thread::sleep(std::time::Duration::from_millis(100));
                    }
                }
                let d = state();
                if d["state"]["laser"]["on"].as_bool() != Some(true) {
                    h.push("The laser is off: the set-point is stored and applies when it is enabled".into());
                }
                out.ok(&laser_line(&d["state"]), v["data"].clone(), &h);
            }
            "read" => {
                let v = call(out, port, "POST", "/board/read_current", Some(json!({})));
                let d = &v["data"];
                out.ok(&format!("measured {:.2} mA (head ADS1115 code {}, {} ms old), set-point {:.2} mA", d["measured_mA"].as_f64().unwrap_or(f64::NAN), d["ads1115_code"], d["age_ms"], d["setpoint_mA"].as_f64().unwrap_or(0.0)), d.clone(), &[]);
            }
            a => out.err(&format!("unknown laser action '{a}'"), &["Use `smi-dash laser on --beam-safe | off | current <mA> | read`".into()]),
        },
        Cmd::Offset { target, value, counts } => {
            if target == "auto" {
                let chans: Vec<u8> = match value.as_deref() {
                    Some("ch1") | Some("1") => vec![1],
                    Some("ch2") | Some("2") => vec![2],
                    None | Some("both") => vec![1, 2],
                    Some(x) => out.err(&format!("unknown channel '{x}'"), &["Use ch1, ch2 or both".into()]),
                };
                let v = call(out, port, "POST", "/board/auto_centre", Some(json!({"channels": chans})));
                let msg = v["data"].as_array().map(|a| a.iter().map(|r| format!("channel {}: offset {:.4} V, mean {:.0} codes after {} steps", r["channel"], r["offset_V"].as_f64().unwrap_or(0.0), r["mean"].as_f64().unwrap_or(0.0), r["iterations"])).collect::<Vec<_>>().join("; ")).unwrap_or_default();
                out.ok(&msg, v["data"].clone(), &[]);
            } else {
                let id = match target.as_str() {
                    "ch1" | "1" => "ch1-offset",
                    "ch2" | "2" => "ch2-offset",
                    x => x,
                };
                let Some(val) = value else { out.err("offset needs a value", &["e.g. `smi-dash offset ch1 0.52` or `smi-dash offset ch1 650 --counts`".into()]) };
                let v = set(id, num_or_str(val), if *counts { "counts" } else { "units" });
                let d = &v["data"];
                out.ok(&format!("{} = {:.4} V (code {})", d["id"].as_str().unwrap_or(""), d["applied"].as_f64().unwrap_or(0.0), d["code"]), d.clone(), &hints_of(&v));
            }
        }
        Cmd::Gain { stage, value } => {
            let v = set(stage, num_or_str(value), "units");
            let d = &v["data"];
            out.ok(&format!("{} = {} {}{}", d["id"].as_str().unwrap_or(""), d["target"], d["unit"].as_str().unwrap_or(""), d["label"].as_str().map(|l| format!(" ({l})")).unwrap_or_default()), d.clone(), &hints_of(&v));
        }
        Cmd::Bias { value } => {
            let v = set("bias", num_or_str(value), "units");
            let d = &v["data"];
            out.ok(&format!("monitor bias = {} V{}", d["target"], d["label"].as_str().map(|l| format!(" ({l})")).unwrap_or_default()), d.clone(), &hints_of(&v));
        }
        Cmd::Ctl { id, value, counts, index } => {
            let unit = if *counts { "counts" } else if *index { "index" } else { "units" };
            let v = set(id, num_or_str(value), unit);
            let d = &v["data"];
            out.ok(&format!("{} = {} {} (code {})", d["id"].as_str().unwrap_or(""), d["applied"], d["unit"].as_str().unwrap_or(""), d["code"]), d.clone(), &hints_of(&v));
        }
        Cmd::Board { action, isense_hz, hb_timeout_ms } => match action.as_deref().unwrap_or("state") {
            "state" => {
                let v = call(out, port, "GET", "/board", None);
                let d = &v["data"];
                out.ok(&format!("{}\n{}", laser_line(&d["state"]), controls_lines(&d["state"], &d["map"])), d.clone(), &hints_of(&v));
            }
            "map" => {
                let v = call(out, port, "GET", "/board", None);
                let m = &v["data"]["map"];
                let lines: Vec<String> = m["controls"].as_array().map(|a| a.iter().map(|c| {
                    let range = if c["kind"] == "switch" { c["settings"].as_array().map(|s| s.iter().map(|x| format!("{} ({})", x["value"], x["label"].as_str().unwrap_or(""))).collect::<Vec<_>>().join(" | ")).unwrap_or_default() } else { format!("{} to {} {}", c["min"], c["max"], c["unit"].as_str().unwrap_or("")) };
                    format!("  {:<26} {:<7} {}  default {}{}", c["id"].as_str().unwrap_or(""), c["kind"].as_str().unwrap_or(""), range, c["default"], if c["requires_laser_off"] == json!(true) { "  [laser off only]" } else { "" })
                }).collect()).unwrap_or_default();
                out.ok(&format!("control map {} (hash {})\n{}", m["map_version"].as_str().unwrap_or(""), v["data"]["map_hash"].as_str().unwrap_or(""), lines.join("\n")), v["data"].clone(), &[]);
            }
            "clear-fault" => {
                let v = call(out, port, "POST", "/board/clear_fault", Some(json!({})));
                out.ok(&laser_line(&v["data"]), v["data"].clone(), &hints_of(&v));
            }
            "config" => {
                let mut b = json!({});
                if let Some(x) = isense_hz { b["isense_hz"] = json!(x) }
                if let Some(x) = hb_timeout_ms { b["hb_timeout_ms"] = json!(x) }
                let v = call(out, port, "POST", "/board/config", Some(b));
                out.ok(&format!("current sense {} Hz, heartbeat timeout {} ms", v["data"]["isense_hz"], v["data"]["hb_timeout_ms"]), v["data"].clone(), &[]);
            }
            a => out.err(&format!("unknown board action '{a}'"), &["Use `smi-dash board state | map | clear-fault | config`".into()]),
        },
        Cmd::Tune { channel, min_ma, max_ma, steps, no_gains, no_wait, status, stop } => {
            let summary = |t: &Value| -> String {
                let rows: Vec<String> = t["steps"].as_array().map(|a| a.iter().map(|r| format!("  {:<7} {:>7.2} mA  measured {:>7.2}  score {:>6.1}  swing {:>5}  noise {:>5}  clip {:.3}{}", r["phase"].as_str().unwrap_or(""), r["set_mA"].as_f64().unwrap_or(0.0), r["measured_mA"].as_f64().unwrap_or(f64::NAN), r["score"].as_f64().unwrap_or(0.0), r["swing"], r["noise"], r["clip"].as_f64().unwrap_or(0.0), r["gain"].as_f64().map(|g| format!("  gain {g}")).unwrap_or_default())).collect()).unwrap_or_default();
                let head = match t["status"].as_str() {
                    Some("done") => format!("tuned channel {}: best {:.2} mA, score {:.1}{} in {:.1} s", t["channel"], t["best_mA"].as_f64().unwrap_or(0.0), t["final_score"].as_f64().unwrap_or(0.0), t["gain"]["value"].as_f64().map(|g| format!(", {} = {g}", t["gain"]["id"].as_str().unwrap_or(""))).unwrap_or_default(), t["seconds"].as_f64().unwrap_or(0.0)),
                    Some("failed") => format!("tuning failed: {}", t["error"].as_str().unwrap_or("")),
                    Some(s) => format!("tuning {s}, step {}", t["step"]),
                    None => "no tune yet".into(),
                };
                let note = t["note"].as_str().map(|n| format!("\nNote: {n}")).unwrap_or_default();
                format!("{head}{note}\n{}", rows.join("\n"))
            };
            if *stop {
                let v = call(out, port, "POST", "/board/tune/stop", Some(json!({})));
                out.ok("stop requested", v["data"].clone(), &[]);
                return;
            }
            if *status {
                let v = call(out, port, "GET", "/board/tune", None);
                out.ok(&summary(&v["data"]), v["data"].clone(), &[]);
                return;
            }
            let mut b = json!({"channel": channel, "steps": steps, "gains": !no_gains});
            if let Some(x) = min_ma { b["min_ma"] = json!(x) }
            if let Some(x) = max_ma { b["max_ma"] = json!(x) }
            let v = call(out, port, "POST", "/board/tune", Some(b));
            if *no_wait {
                out.ok("tuning started", v["data"].clone(), &hints_of(&v));
                return;
            }
            let t = Instant::now();
            loop {
                std::thread::sleep(std::time::Duration::from_millis(500));
                let v = call(out, port, "GET", "/board/tune", None);
                let st = v["data"]["status"].as_str().unwrap_or("");
                if st == "done" {
                    out.ok(&summary(&v["data"]), v["data"].clone(), &[]);
                    return;
                }
                if st == "failed" {
                    out.err(&summary(&v["data"]), &hints_of(&json!({"hints": v["data"]["hints"]})));
                }
                if t.elapsed().as_secs() > 180 {
                    out.err("tuning did not finish within 180 s", &["Check `smi-dash tune --status`; stop it with `smi-dash tune --stop`".into()]);
                }
            }
        }
        _ => unreachable!(),
    }
}

fn stage_line(v: &Value) -> String {
    if v.is_null() {
        return "no stage state".into();
    }
    let f = v["fault"].as_u64().unwrap_or(0);
    format!(
        "stage {}{}, {} pulses ({:.0} nm nominal){}, {} pulses/s{}",
        v["state"].as_str().unwrap_or("?"),
        if v["homed"] == json!(true) { ", homed" } else if v["enabled"] == json!(true) { ", not homed" } else { ", driver disabled" },
        v["pos_pulses"],
        v["pos_nm_nominal"].as_f64().unwrap_or(0.0),
        if v["target_pulses"] != v["pos_pulses"] { format!(" -> {}", v["target_pulses"]) } else { String::new() },
        v["rate_pps"],
        if f != 0 { format!(", FAULT: {}", v["fault_text"].as_str().unwrap_or("")) } else { String::new() }
    )
}

fn selftest_text(v: &Value) -> String {
    match v["status"].as_str() {
        Some("done") => {
            let c = &v["counted"];
            let lab = v["label"].as_str().unwrap_or("");
            let head = match v["scale_nm_per_pulse"].as_f64() {
                Some(sc) => format!("self-test ({lab}): {sc:.3} nm/pulse from {} counted fringe edges ({:+.2} % vs nominal 15.625), return residual {:.0} nm counted\n", v["scale_edges"].as_f64().unwrap_or(0.0) as i64, (sc / 15.625 - 1.0) * 100.0, c["return_residual_nm"].as_f64().unwrap_or(f64::NAN)),
                None => format!("self-test ({lab}): fringes were missed, no scale\n"),
            };
            let mut s = head + &format!(
                "plateau fit (whole fringes): {:.3} nm/pulse ({:+.2} %), drift {:.2} nm/s, return residual {:.0} nm ({:.0} nm drift-corrected), rms {:.0} nm",
                c["nm_per_pulse"].as_f64().unwrap_or(f64::NAN),
                c["scale_vs_nominal_pct"].as_f64().unwrap_or(f64::NAN),
                c["drift_nm_s"].as_f64().unwrap_or(f64::NAN),
                c["return_residual_nm"].as_f64().unwrap_or(f64::NAN),
                c["return_residual_drift_corrected_nm"].as_f64().unwrap_or(f64::NAN),
                c["fit_rms_nm"].as_f64().unwrap_or(f64::NAN),
            );
            for k in ["edge_fit_out", "edge_fit_back"] {
                if let Some(x) = c[k]["nm_per_pulse"].as_f64() {
                    s += &format!("\n{} sweep, fitted to {} counted fringe edges: {:.3} nm/pulse", if k.ends_with("out") { "outbound" } else { "return" }, c[k]["edges"], x.abs());
                }
            }
            s += "\nplateaus (pulses: counted nm):";
            for p in v["plateaus"].as_array().into_iter().flatten() {
                s += &format!(" {}: {:.0}", p["pos"], p["meas_nm"].as_f64().unwrap_or(0.0));
            }
            for r in c["reversal"].as_array().into_iter().flatten() {
                s += &format!("\nreversal at {} pulses: reverse - forward {:+.0} nm", r["pos_pulses"], r["reverse_minus_forward_nm"].as_f64().unwrap_or(0.0));
            }
            if v["truth"].is_object() {
                let t = &v["truth"];
                s += &format!(
                    "\nsimulated truth: {:.3} nm/pulse, return residual {:.1} nm drift-corrected ({})",
                    t["nm_per_pulse"].as_f64().unwrap_or(f64::NAN),
                    t["return_residual_drift_corrected_nm"].as_f64().unwrap_or(f64::NAN),
                    v["truth_note"].as_str().unwrap_or("")
                );
            }
            s += &format!("\nNote: {}", v["note"].as_str().unwrap_or(""));
            if let Some(w) = v["warning"].as_str() {
                s = format!("{s}\nWARNING: {w}");
            }
            s
        }
        Some("running") => format!("self-test running, rung {}", v["rung"]),
        Some("failed") => format!("self-test failed: {}", v["error"].as_str().unwrap_or("")),
        _ => "no self-test yet".into(),
    }
}

fn calib_text(v: &Value) -> String {
    match v["status"].as_str() {
        Some("done") => {
            let lab = v["label"].as_str().unwrap_or("");
            let (b, a) = (&v["before"], &v["after"]);
            let num = |x: &Value, d: usize| x.as_f64().map(|f| format!("{f:.d$}")).unwrap_or_else(|| "n/a".into());
            let row = |name: &str, x: String, y: String| format!("  {name:<34} {x:>14} {y:>14}\n");
            let mut s = format!("Calibrate ({lab}), {:.0} s\n  {:<34} {:>14} {:>14}\n", v["seconds"].as_f64().unwrap_or(0.0), "", "before", "after");
            s += &row("laser current, mA", num(&b["settings"]["laser_mA"], 2), num(&a["settings"]["laser_mA"], 2));
            s += &row("measured current, mA", num(&b["settings"]["measured_mA"], 2), num(&a["settings"]["measured_mA"], 2));
            s += &row("ch1 second-stage gain, V/V", num(&b["settings"]["ch1_gain"], 0), num(&a["settings"]["ch1_gain"], 0));
            s += &row("ch1 offset, V", num(&b["settings"]["ch1_offset_V"], 3), num(&a["settings"]["ch1_offset_V"], 3));
            s += &row("ch1 mean, codes", num(&b["settings"]["ch1_mean"], 0), num(&a["settings"]["ch1_mean"], 0));
            s += &row("readback zero code", num(&b["settings"]["isense_zero_code"], 2), num(&a["settings"]["isense_zero_code"], 2));
            let (cb, ca) = (&b["check"], &a["check"]);
            s += &row(&format!("step {} pulses: commanded nm", cb["pulses"]), num(&cb["commanded_nm_nominal"], 0), num(&ca["commanded_nm_nominal"], 0));
            s += &row("  counted nm", num(&cb["counted_nm"], 0), num(&ca["counted_nm"], 0));
            s += &row("  counted fringes", num(&cb["counted_fringes"], 0), num(&ca["counted_fringes"], 0));
            s += &row("  error vs nominal, %", num(&cb["error_vs_nominal_pct"], 2), num(&ca["error_vs_nominal_pct"], 2));
            s += &row("  scale from fringe edges, nm/pulse", num(&cb["nm_per_pulse_edge_fit"], 3), num(&ca["nm_per_pulse_edge_fit"], 3));
            s += &row("  return (counted), nm", num(&cb["return_counted_nm"], 0), num(&ca["return_counted_nm"], 0));
            s += &row("  fringe swing while moving, codes", num(&cb["moving_swing_codes"], 0), num(&ca["moving_swing_codes"], 0));
            s += &row("  fringe score while moving", num(&cb["moving_score"], 1), num(&ca["moving_score"], 1));
            if v["simulated"] == json!(true) {
                s += &row("  simulated truth, nm", num(&cb["truth_nm"], 0), num(&ca["truth_nm"], 0));
                s += &row("  counted minus truth, nm", num(&cb["error_vs_truth_nm"], 0), num(&ca["error_vs_truth_nm"], 0));
            }
            s += &format!("tune: best {} mA, score {}, gain {}\n", num(&v["tune"]["best_mA"], 2), num(&v["tune"]["final_score"], 1), v["tune"]["gain"]["label"].as_str().unwrap_or("unchanged"));
            s += &format!("{}\n{}", v["scale_note"].as_str().unwrap_or(""), v["note"].as_str().unwrap_or(""));
            s
        }
        Some("running") => format!("Calibrate running: step {} of {}, {}", v["step_n"], v["steps_total"], v["step"].as_str().unwrap_or("")),
        Some("failed") => format!("Calibrate failed at '{}': {}", v["step"].as_str().unwrap_or(""), v["error"].as_str().unwrap_or("")),
        _ => "no calibration yet".into(),
    }
}

fn stage_cli(cli: &Cli, out: &Out) {
    let port = find_port(cli, out);
    match &cli.cmd {
        Cmd::Stage { action, value, nm, no_wait, status } => {
            let act = action.as_deref().unwrap_or("status");
            if act == "align" {
                let v = call(out, port, "POST", "/stage/align", Some(json!({})));
                out.ok("counted trace aligned with the commanded position", v["data"].clone(), &hints_of(&v));
                return;
            }
            if act == "selftest" && *status {
                let v = call(out, port, "GET", "/stage/selftest", None);
                out.ok(&selftest_text(&v["data"]), v["data"].clone(), &hints_of(&v));
                return;
            }
            let mut b = json!({"action": act, "unit": if *nm { "nm" } else { "pulses" }});
            if let Some(x) = value {
                b["value"] = json!(x);
            }
            let v = call(out, port, "POST", "/stage/cmd", Some(b));
            let hints = hints_of(&v);
            if act == "selftest" {
                if *no_wait {
                    out.ok("self-test started", v["data"].clone(), &hints);
                    return;
                }
                let t = Instant::now();
                loop {
                    std::thread::sleep(std::time::Duration::from_millis(500));
                    let r = call(out, port, "GET", "/stage/selftest", None);
                    match r["data"]["status"].as_str() {
                        Some("done") => return out.ok(&selftest_text(&r["data"]), r["data"].clone(), &hints_of(&r)),
                        Some("failed") => out.err(&selftest_text(&r["data"]), &hints_of(&json!({"hints": r["data"]["hints"]}))),
                        _ => {}
                    }
                    if t.elapsed().as_secs() > 120 {
                        out.err("the self-test did not finish within 120 s", &["`smi-dash stage selftest --status`; `smi-dash stage stop`".into()]);
                    }
                }
            }
            let waits = matches!(act, "home" | "step" | "move") && !*no_wait;
            if !waits {
                return out.ok(&stage_line(&v["data"]), v["data"].clone(), &hints);
            }
            let t = Instant::now();
            loop {
                std::thread::sleep(std::time::Duration::from_millis(150));
                let r = call(out, port, "GET", "/stage", None);
                let st = &r["data"]["state"];
                let s = st["state"].as_str().unwrap_or("");
                if s == "faulted" {
                    out.err(&stage_line(st), &["`smi-dash stage off`, fix the cause, then `smi-dash stage home`".into()]);
                }
                if !matches!(s, "homing" | "moving" | "selftest") {
                    return out.ok(&stage_line(st), st.clone(), &hints);
                }
                if t.elapsed().as_secs() > 90 {
                    out.err("the stage did not finish within 90 s", &["`smi-dash stage stop`".into()]);
                }
            }
        }
        Cmd::Calibrate { beam_safe, check_pulses, no_wait, status, stop } => {
            if *stop {
                let v = call(out, port, "POST", "/calibrate/stop", Some(json!({})));
                return out.ok("stop requested", v["data"].clone(), &[]);
            }
            if *status {
                let v = call(out, port, "GET", "/calibrate", None);
                return out.ok(&calib_text(&v["data"]), v["data"].clone(), &hints_of(&v));
            }
            let mut b = json!({});
            if *beam_safe {
                b["confirm"] = json!("beam-safe");
            }
            if let Some(c) = check_pulses {
                b["check_pulses"] = json!(c);
            }
            let v = call(out, port, "POST", "/calibrate", Some(b));
            if *no_wait {
                return out.ok("Calibrate started", v["data"].clone(), &hints_of(&v));
            }
            let t = Instant::now();
            let mut last = String::new();
            loop {
                std::thread::sleep(std::time::Duration::from_millis(500));
                let r = call(out, port, "GET", "/calibrate", None);
                let d = &r["data"];
                match d["status"].as_str() {
                    Some("done") => return out.ok(&calib_text(d), d.clone(), &hints_of(&r)),
                    Some("failed") => out.err(&calib_text(d), &hints_of(&json!({"hints": d["hints"]}))),
                    _ => {
                        let s = calib_text(d);
                        if s != last && !out.json {
                            eprintln!("{s}");
                            last = s;
                        }
                    }
                }
                if t.elapsed().as_secs() > 300 {
                    out.err("Calibrate did not finish within 300 s", &["`smi-dash calibrate --status`; `smi-dash calibrate --stop`".into()]);
                }
            }
        }
        _ => unreachable!(),
    }
}