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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789
// 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()),
            "board_map": e.map,
            "board_map_hash": format!("{:08X}", crate::controls::ControlMap::hash()),
            "enums": {
                "sim.profile": Profile::ALL,
                "stage.action": ["status", "home", "step", "move", "speed", "stop", "off", "current", "selftest"],
                "source.kind": ["sim", "serial"],
                "record.format": ["csv", "h5"],
                "settings.surface": ["wv", "pup"],
                "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;
        }
    });
    // Host heartbeat: the firmware turns the laser off if commands stop for
    // hb_timeout_ms (3 s), so a crashed or closed dashboard cannot leave it on.
    let a4 = app.clone();
    tokio::spawn(async move {
        loop {
            tokio::time::sleep(Duration::from_millis(1000)).await;
            // Also while the stage driver is enabled: firmware 1.3.1 disables
            // the stage when a dashboard host goes quiet for the same timeout.
            let on = {
                let e = a4.engine.lock().unwrap();
                e.board_state().is_some_and(|s| s.laser_on) || (!matches!(e.source, SourceKind::Sim) && e.stage_state().is_some_and(|s| s.enabled))
            };
            if on {
                let _ = crate::tune::cmd(&a4, vec![crate::controls::OP_HEARTBEAT]).await;
            }
        }
    });
    // 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))
        .route("/board", get(board_get))
        .route("/board/laser", post(board_laser))
        .route("/board/set", post(board_set))
        .route("/board/read_current", post(board_read_current))
        .route("/board/auto_centre", post(board_centre))
        .route("/board/tune", get(board_tune_get).post(board_tune))
        .route("/board/tune/stop", post(board_tune_stop))
        .route("/board/clear_fault", post(board_clear_fault))
        .route("/board/config", post(board_config))
        .route("/stage", get(stage_get))
        .route("/stage/cmd", post(stage_cmd))
        .route("/stage/align", post(stage_align))
        .route("/stage/selftest", get(stage_selftest_get))
        .route("/calibrate", get(calibrate_get).post(calibrate_post))
        .route("/calibrate/stop", post(calibrate_stop))
        .with_state(app);
    axum::serve(listener, r).await.unwrap();
}

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", "fullscreen", "tab"];
    if !valid.contains(&verb.as_str()) {
        return refuse(StatusCode::NOT_FOUND, &format!("unknown ui verb '{verb}'"), &[format!("Valid verbs: {}", valid.join(", "))]);
    }
    if !["toast", "reload", "fullscreen", "tab"].contains(&verb.as_str()) && p.get("selector").and_then(|v| v.as_str()).is_none() {
        return refuse(StatusCode::BAD_REQUEST, "missing selector", &[format!("Send {{\"selector\": \"#btn-zero\"}}; selectors are listed by `smi-dash ui {verb} --help`")]);
    }
    let n = a.tx.receiver_count();
    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}), &[])
}

// ------------------------------------------------------------ board v1.2 --

use crate::controls;
use crate::tune;

fn fail_resp(f: tune::Fail) -> Response {
    refuse(StatusCode::CONFLICT, &f.0, &f.1)
}

fn board_now(a: &Arc<App>) -> Value {
    a.engine.lock().unwrap().board_view()
}

async fn board_get(State(a): S) -> Response {
    a.touch();
    let e = a.engine.lock().unwrap();
    let st = e.board_view();
    let hints: Vec<&str> = if st.is_null() {
        if matches!(e.source, SourceKind::Sim) { vec!["The simulator models the v1.1 board; turn the board 1.3 model on with `smi-dash sim --board on`"] } else { vec!["No STATE frames from the Pico: it needs firmware 1.3.1"] }
    } else if st["map_match"] == json!(false) {
        vec!["The firmware's control map differs from this dashboard's: flash the smi_pico.uf2 built from the same map"]
    } else {
        vec![]
    };
    ok(json!({"state": st, "map": e.map, "map_hash": format!("{:08X}", controls::ControlMap::hash()), "sim_firmware_map_hash": format!("{:08X}", controls::SimBoard::firmware_hash()), "tune": e.tune}), &hints)
}

async fn board_laser(State(a): S, Json(p): Json<Value>) -> Response {
    a.touch();
    let Some(on) = p.get("on").and_then(|v| v.as_bool()) else {
        return refuse(StatusCode::BAD_REQUEST, "missing 'on'", &["Send {\"on\": false}, or {\"on\": true, \"confirm\": \"beam-safe\"}".into()]);
    };
    if on && p.get("confirm").and_then(|v| v.as_str()) != Some("beam-safe") {
        return refuse(
            StatusCode::PRECONDITION_REQUIRED,
            "laser interlock: confirm the beam path is safe",
            &["Class 3B: enclose the beam or wear eyewear, then `smi-dash laser on --beam-safe` (the page asks you to tick the interlock box and hold Enable)".into()],
        );
    }
    match tune::laser(&a, on).await {
        Ok(_) => {
            a.broadcast("toast", json!({"text": if on { "Laser enabled: set-point written to the head, read back, then armed" } else { "Laser off" }, "kind": if on { "info" } else { "success" }}));
            ok(board_now(&a), &[if on { "Set the current with `smi-dash laser current <mA> --wait`" } else { "" }])
        }
        Err(f) => fail_resp(f),
    }
}

/// {id, value, unit: "units" | "counts" | "index"}; a switch also takes a setting label.
async fn board_set(State(a): S, Json(p): Json<Value>) -> Response {
    a.touch();
    let map = a.engine.lock().unwrap().map.clone();
    let key = p.get("id").and_then(|v| v.as_str()).unwrap_or("");
    let Some(idx) = tune::resolve(&map, key) else {
        return refuse(StatusCode::BAD_REQUEST, &format!("unknown control '{key}'"), &[format!("Controls: {} (aliases: laser, ch1-offset, ch2-offset, ch1-tia, ch1-amp, ch2-tia, ch2-amp, bias)", map.controls.iter().map(|c| c.id.as_str()).collect::<Vec<_>>().join(", "))]);
    };
    let c = &map.controls[idx];
    let unit = p.get("unit").and_then(|v| v.as_str()).unwrap_or("units");
    let mode = match unit {
        "units" => 0,
        "counts" => 1,
        "index" => 2,
        _ => return refuse(StatusCode::BAD_REQUEST, &format!("unknown unit '{unit}'"), &["Use units, counts or index".into()]),
    };
    let v = match p.get("value") {
        Some(Value::Number(n)) => n.as_f64().unwrap_or(f64::NAN),
        Some(Value::String(t)) => match t.parse::<f64>() {
            Ok(x) => x,
            Err(_) => match c.settings.iter().find(|s| s.label.to_ascii_lowercase().starts_with(&t.to_ascii_lowercase())) {
                Some(s) => s.value,
                None => return refuse(StatusCode::BAD_REQUEST, &format!("'{t}' is not a value of {}", c.id), &[format!("Settings: {}", c.settings.iter().map(|s| format!("{} ({})", s.value, s.label)).collect::<Vec<_>>().join(", "))]),
            },
        },
        _ => return refuse(StatusCode::BAD_REQUEST, "missing 'value'", &[format!("e.g. {{\"id\": \"{}\", \"value\": {}}}", c.id, c.default)]),
    };
    match tune::set(&a, idx, mode, v).await {
        Ok(ack) => {
            let d = &ack.data;
            let code = if d.len() >= 3 { u16::from_le_bytes([d[1], d[2]]) } else { 0 };
            let applied = if d.len() >= 7 { f32::from_le_bytes([d[3], d[4], d[5], d[6]]) } else { f32::NAN };
            let target = if d.len() >= 11 { f32::from_le_bytes([d[7], d[8], d[9], d[10]]) } else { f32::NAN };
            let mut hints = vec![];
            if c.role == "laser" && (applied - target).abs() > 0.01 {
                hints.push(format!("Being written (at most four set-point writes a second); `smi-dash laser current {} --wait` blocks until the measured current arrives", target));
            }
            if c.role == "gain" && c.stage.as_deref() == Some("amp") {
                hints.push("Re-centre the channel after a gain change: `smi-dash offset auto`".to_string());
            }
            let h: Vec<&str> = hints.iter().map(|s| s.as_str()).collect();
            ok(json!({"id": c.id, "code": code, "applied": applied, "target": target, "unit": c.unit, "label": c.setting_label(target as f64)}), &h)
        }
        Err(f) => fail_resp(f),
    }
}

async fn board_read_current(State(a): S) -> Response {
    a.touch();
    match tune::cmd(&a, vec![controls::OP_READ_ISENSE]).await {
        Ok(ack) if ack.data.len() >= 8 => {
            let d = &ack.data;
            let ma = f32::from_le_bytes([d[0], d[1], d[2], d[3]]);
            let st = a.engine.lock().unwrap().board_state();
            ok(json!({"measured_mA": ma, "ads1115_code": i16::from_le_bytes([d[4], d[5]]), "age_ms": u16::from_le_bytes([d[6], d[7]]),
                      "setpoint_mA": st.as_ref().map(|s| s.laser_now_ma), "target_mA": st.as_ref().map(|s| s.laser_target_ma), "valid": ack.ok()}), &[])
        }
        Ok(ack) => fail_resp(tune::refusal(&ack, None)),
        Err(f) => fail_resp(f),
    }
}

async fn board_centre(State(a): S, Json(p): Json<Value>) -> Response {
    a.touch();
    let chans: Vec<u8> = match p.get("channels") {
        Some(Value::Array(v)) => v.iter().filter_map(|x| x.as_u64()).map(|x| x as u8).collect(),
        _ => vec![1, 2],
    };
    let mut out = vec![];
    for ch in chans {
        match tune::auto_centre(&a, ch).await {
            Ok(v) => out.push(v),
            Err(f) => return fail_resp(f),
        }
    }
    a.broadcast("toast", json!({"text": "Auto-centre done", "kind": "success"}));
    ok(json!(out), &[])
}

async fn board_tune(State(a): S, Json(p): Json<Value>) -> Response {
    a.touch();
    let tp: tune::TuneParams = match serde_json::from_value(p) {
        Ok(t) => t,
        Err(e) => return refuse(StatusCode::BAD_REQUEST, &format!("invalid tune parameters: {e}"), &["Keys: channel, min_ma, max_ma, steps, dither_ma, measure_s, gains".into()]),
    };
    let st = a.engine.lock().unwrap().board_state();
    if !st.as_ref().is_some_and(|s| s.laser_on) {
        return refuse(StatusCode::CONFLICT, "the laser is off; tuning never turns it on by itself", &["Turn it on first: `smi-dash laser on --beam-safe`".into()]);
    }
    match tune::spawn_tune(a.clone(), tp) {
        Ok(()) => ok(json!({"started": true}), &["Progress: `smi-dash tune --status` (or the Controls panel); about 15 to 25 s"]),
        Err(f) => fail_resp(f),
    }
}

async fn board_tune_get(State(a): S) -> Response {
    let t = a.engine.lock().unwrap().tune.clone();
    ok(t, &[])
}

async fn board_tune_stop(State(a): S) -> Response {
    tune::TUNE_CANCEL.store(true, std::sync::atomic::Ordering::SeqCst);
    let _ = &a;
    ok(json!({"stopping": tune::TUNE_RUNNING.load(std::sync::atomic::Ordering::SeqCst)}), &[])
}

async fn board_clear_fault(State(a): S) -> Response {
    a.touch();
    match tune::cmd(&a, vec![controls::OP_CLEAR_FAULT]).await {
        Ok(_) => ok(board_now(&a), &["If the cause remains, the fault latches again"]),
        Err(f) => fail_resp(f),
    }
}

async fn board_config(State(a): S, Json(p): Json<Value>) -> Response {
    a.touch();
    let cur = a.engine.lock().unwrap().board_state();
    let hz = p.get("isense_hz").and_then(|v| v.as_u64()).unwrap_or(cur.as_ref().map(|s| s.isense_hz as u64).unwrap_or(10));
    let hb = p.get("hb_timeout_ms").and_then(|v| v.as_u64()).unwrap_or(cur.as_ref().map(|s| s.hb_timeout_ms as u64).unwrap_or(3000));
    match tune::cmd(&a, controls::cmd_config(hz.min(255) as u8, hb.min(65535) as u16)).await {
        Ok(ack) if ack.ok() => ok(board_now(&a), &[]),
        Ok(ack) => {
            let (lo, hi) = ack.range().unwrap_or((0.0, 0.0));
            refuse(StatusCode::BAD_REQUEST, &format!("out of range (allowed {lo} to {hi})"), &["isense_hz 1..50, hb_timeout_ms 500..30000".into()])
        }
        Err(f) => fail_resp(f),
    }
}

// ------------------------------------------------------------------ stage --

use crate::stage;

fn stage_hints(a: &Arc<App>) -> Vec<&'static str> {
    if matches!(a.engine.lock().unwrap().source, SourceKind::Sim) {
        vec!["Simulated stage: the firmware's stage core on a simulated TMC2209 and mechanism. Nothing is assembled yet, so no result here is a measurement"]
    } else {
        vec![]
    }
}

async fn stage_get(State(a): S) -> Response {
    a.touch();
    let v = a.engine.lock().unwrap().stage_view();
    let h = stage_hints(&a);
    ok(v, &h)
}

/// {action: status|home|step|move|speed|stop|off|current|selftest, value, unit: "pulses"|"nm"}
async fn stage_cmd(State(a): S, Json(p): Json<Value>) -> Response {
    a.touch();
    let action = p.get("action").and_then(|v| v.as_str()).unwrap_or("status").to_string();
    let unit = p.get("unit").and_then(|v| v.as_str()).unwrap_or("pulses");
    let val = p.get("value").and_then(|v| v.as_f64().or_else(|| v.as_str().and_then(|s| s.parse().ok())));
    let scale = a.engine.lock().unwrap().stage_scale();
    let pulses = |v: f64| -> i32 { if unit == "nm" { (v / scale).round() as i32 } else { v.round() as i32 } };
    let need = |what: &str| refuse(StatusCode::BAD_REQUEST, &format!("'{action}' needs a value ({what})"), &[format!("e.g. {{\"action\": \"{action}\", \"value\": 128}}")]);
    let (sub, arg) = match action.as_str() {
        "status" => (stage::sub::STATUS, 0),
        "home" => (stage::sub::HOME, 0),
        "stop" => (stage::sub::STOP, 0),
        "off" => (stage::sub::OFF, 0),
        "current" => (stage::sub::CURRENT, 0),
        "speed" => (stage::sub::SPEED, val.map(|v| v.round() as i32).unwrap_or(0)),
        "step" => match val { Some(v) => (stage::sub::STEP, pulses(v)), None => return need("signed pulses, or nm with unit nm") },
        "move" => match val { Some(v) => (stage::sub::MOVE_TO, pulses(v)), None => return need("absolute pulses from HOME, 0..1600") },
        "selftest" => {
            stage::sim_follow_stage(&a);
            return match stage::spawn_selftest(a.clone()) {
                Ok(()) => ok(json!({"started": true}), &["About 17 s at 160 pulses/s (homes first if needed). Progress and result: `smi-dash stage selftest --status`"]),
                Err(f) => fail_resp(f),
            };
        }
        _ => return refuse(StatusCode::BAD_REQUEST, &format!("unknown stage action '{action}'"), &["Actions: status, home, step, move, speed, stop, off, current, selftest".into()]),
    };
    if matches!(sub, stage::sub::HOME | stage::sub::STEP | stage::sub::MOVE_TO) && stage::sim_follow_stage(&a) {
        a.push_state();
        a.broadcast("toast", json!({"text": "Simulator target: the stage mirror", "kind": "info"}));
    }
    if stage::CAL_RUNNING.load(std::sync::atomic::Ordering::SeqCst) && !matches!(sub, stage::sub::STATUS | stage::sub::STOP | stage::sub::OFF | stage::sub::CURRENT) {
        return refuse(StatusCode::CONFLICT, "Calibrate is moving the stage", &["Wait for it, or `smi-dash calibrate --stop`".into()]);
    }
    match stage::stage_ok(&a, sub, arg).await {
        Ok(st) => {
            let mut h: Vec<String> = stage_hints(&a).iter().map(|s| s.to_string()).collect();
            if sub == stage::sub::HOME {
                h.push("Homing: 80 pulses/s to the switch, back off, 32 pulses/s to the opening edge; `smi-dash stage home` waits until it is homed unless --no-wait".into());
            }
            if sub == stage::sub::OFF {
                h.push("Driver disabled; the position is invalid until the next home".into());
            }
            if sub == stage::sub::CURRENT {
                h.push("Winding current: IRUN = IHOLD = 27/31 of 0.469 A rms, about 0.41 A rms (stage map). Commission it against the measured winding current".into());
            }
            let hr: Vec<&str> = h.iter().map(|s| s.as_str()).collect();
            let mut v = st.view();
            v["action"] = json!(action);
            v["arg"] = json!(arg);
            v["nm_per_pulse"] = json!(scale);
            ok(v, &hr)
        }
        Err(f) => fail_resp(f),
    }
}

async fn stage_align(State(a): S) -> Response {
    a.touch();
    a.engine.lock().unwrap().stage_align();
    ok(json!({"aligned": true}), &["The counted trace now starts on the commanded one"])
}

async fn stage_selftest_get(State(a): S) -> Response {
    let v = a.engine.lock().unwrap().stage_selftest.clone();
    let h = stage_hints(&a);
    ok(v, &h)
}

async fn calibrate_get(State(a): S) -> Response {
    let v = a.engine.lock().unwrap().calib.clone();
    let h = stage_hints(&a);
    ok(v, &h)
}

async fn calibrate_post(State(a): S, Json(p): Json<Value>) -> Response {
    a.touch();
    let cp: stage::CalParams = match serde_json::from_value(p) {
        Ok(c) => c,
        Err(e) => return refuse(StatusCode::BAD_REQUEST, &format!("invalid calibrate parameters: {e}"), &["Keys: confirm, check_pulses, start_ma".into()]),
    };
    if !matches!(a.engine.lock().unwrap().source, SourceKind::Sim) {
        return refuse(StatusCode::CONFLICT, "Calibrate runs on the simulator only for now", &["The stage is not assembled; switch to the simulator with `smi-dash source sim`".into()]);
    }
    if !a.engine.lock().unwrap().sim_p.board {
        return refuse(StatusCode::CONFLICT, "Calibrate needs the board model (laser, offsets and gains from software)", &["`smi-dash sim --board on`".into()]);
    }
    if cp.confirm.as_deref() != Some("beam-safe") {
        return refuse(
            StatusCode::PRECONDITION_REQUIRED,
            "laser interlock: Calibrate turns the laser off and on; confirm the beam path is safe",
            &["`smi-dash calibrate --beam-safe` (the page asks you to tick the interlock box)".into()],
        );
    }
    if !(64..=1400).contains(&cp.check_pulses) {
        return refuse(StatusCode::BAD_REQUEST, "check_pulses must be 64 to 1400", &["The re-check moves from pulse 128, so it must stay inside 0..1600".into()]);
    }
    match stage::spawn_calibrate(a.clone(), cp) {
        Ok(()) => ok(json!({"started": true}), &["About a minute (simulated). Progress and report: `smi-dash calibrate --status`"]),
        Err(f) => fail_resp(f),
    }
}

async fn calibrate_stop(State(a): S) -> Response {
    stage::CAL_CANCEL.store(true, std::sync::atomic::Ordering::SeqCst);
    tune::TUNE_CANCEL.store(true, std::sync::atomic::Ordering::SeqCst);
    let _ = stage::stage_cmd(&a, stage::sub::STOP, 0).await;
    ok(json!({"stopping": stage::CAL_RUNNING.load(std::sync::atomic::Ordering::SeqCst)}), &[])
}