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
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057
// SPDX-License-Identifier: MIT
//! Test stage on board 1.3.1's STAGE connector (J4): a TMC2209 on STEP, DIR,
//! EN_N and its single-wire UART, and a normally closed HOME switch.
//!
//! - The protocol: firmware/src/smi_stage.h (op 0x09 on the CMD/ACK channel,
//!   STAGE frames 0x13).
//! - A simulated stage that runs the firmware's own smi_stage.c over FFI
//!   against a simulated TMC2209 (CRC, registers, IFCNT) and a mechanism model
//!   (screw, lever, lost motion at reversals, thermal drift, HOME switch).
//! - The self-test analysis (the stage map's step-out-and-back sequence) and
//!   Calibrate, which uses the stage as the moving target that Tune needs.
//!
//! Nothing here has run on an assembled stage. Every result the simulator
//! produces is labelled "simulated".

use crate::engine::SourceKind;
use crate::server::App;
use crate::tune::{self, Fail};
use serde::Serialize;
use serde_json::{json, Value};
use std::os::raw::c_void;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};

pub const OP_STAGE: u8 = 0x09;
/// stage-map.json motion: 500 um lead / 3200 microsteps x 5 / 50 lever.
pub const NM_PER_PULSE: f64 = 15.625;
pub const GEOMETRY_NM_PER_PULSE: [f64; 2] = [14.64, 16.65];
pub const TRAVEL: i32 = 1600;
pub const RATE_DEFAULT: i32 = 160;
pub const RATE_MAX: i32 = 640;

pub mod sub {
    pub const STATUS: u8 = 0;
    pub const HOME: u8 = 1;
    pub const STEP: u8 = 2;
    pub const SPEED: u8 = 3;
    pub const STOP: u8 = 4;
    pub const OFF: u8 = 5;
    pub const CURRENT: u8 = 6;
    pub const SELFTEST: u8 = 7;
    pub const MOVE_TO: u8 = 8;
}

pub const ST_OFF: u8 = 0;
pub const ST_IDLE: u8 = 1;
pub const ST_SELFTEST: u8 = 4;
pub const ST_FAULTED: u8 = 5;

pub static SELFTEST_RUNNING: AtomicBool = AtomicBool::new(false);
pub static CAL_RUNNING: AtomicBool = AtomicBool::new(false);
pub static CAL_CANCEL: AtomicBool = AtomicBool::new(false);

pub fn cmd(sub: u8, arg: i32) -> Vec<u8> {
    let mut p = vec![OP_STAGE, sub];
    p.extend_from_slice(&arg.to_le_bytes());
    p
}

pub fn state_name(s: u8) -> &'static str {
    ["off", "idle", "homing", "moving", "selftest", "faulted"].get(s as usize).copied().unwrap_or("?")
}

pub fn fault_text(f: u8) -> &'static str {
    match f {
        0 => "none",
        1 => "TMC2209 configuration or status read failed",
        2 => "HOME stayed high through the release search (stuck or disconnected switch)",
        3 => "no HOME edge within the search limit",
        4 => "HOME went high during a normal move",
        5 => "host link lost while enabled",
        6 => "TMC2209 reported over-temperature, a short or an open load",
        _ => "unknown",
    }
}

pub fn status_text(s: u8) -> &'static str {
    match s {
        0 => "ok",
        1 => "command too short",
        2 => "unknown stage command",
        11 => "the stage is not homed: only homing may move it",
        12 => "outside the travel, 0 to 1600 pulses from HOME",
        13 => "busy: a home, move or self-test is running",
        14 => "the TMC2209 did not configure (UART, CRC, IFCNT or version)",
        15 => "a stage fault is latched",
        16 => "speed must be 1 to 640 pulses/s",
        _ => "unknown status",
    }
}

fn hint_for(s: u8) -> Vec<String> {
    match s {
        11 => vec!["Home it first: `smi-dash stage home` (the Home button)".into()],
        12 => vec!["Moves must stay within 0..1600 pulses (0 to 25 um at the mirror, nominal) from HOME".into()],
        13 => vec!["Wait for it, or `smi-dash stage stop`".into()],
        14 => vec!["Check the stage controller's power (10 to 13.2 V on VIN) and the J4 harness; the driver stays disabled".into()],
        15 => vec!["Read the fault with `smi-dash stage`, then `smi-dash stage off` and `smi-dash stage home`".into()],
        16 => vec!["The stage map's default is 160 pulses/s and its maximum 640".into()],
        _ => vec![],
    }
}

#[derive(Clone, Debug, Serialize, Default)]
pub struct StageState {
    pub state: u8,
    pub enabled: bool,
    pub homed: bool,
    pub home_in: bool,
    pub moving: bool,
    pub fault: u8,
    pub home_phase: u8,
    pub pos: i32,
    pub target: i32,
    pub rate: u16,
    pub st_index: u8,
    pub ifcnt: u8,
    pub steps_total: u32,
    pub drv_status: u32,
}

impl StageState {
    pub fn parse(p: &[u8]) -> Option<Self> {
        if p.len() < 24 {
            return None;
        }
        let i32le = |o: usize| i32::from_le_bytes([p[o], p[o + 1], p[o + 2], p[o + 3]]);
        let fl = p[1];
        Some(Self {
            state: p[0],
            enabled: fl & 1 != 0,
            homed: fl & 2 != 0,
            home_in: fl & 4 != 0,
            moving: fl & 8 != 0,
            fault: p[2],
            home_phase: p[3],
            pos: i32le(4),
            target: i32le(8),
            rate: u16::from_le_bytes([p[12], p[13]]),
            st_index: p[14],
            ifcnt: p[15],
            steps_total: i32le(16) as u32,
            drv_status: i32le(20) as u32,
        })
    }
    pub fn view(&self) -> Value {
        json!({
            "state": state_name(self.state), "enabled": self.enabled, "homed": self.homed, "home_in": self.home_in,
            "moving": self.moving, "fault": self.fault, "fault_text": fault_text(self.fault),
            "pos_pulses": self.pos, "target_pulses": self.target, "rate_pps": self.rate,
            "pos_nm_nominal": self.pos as f64 * NM_PER_PULSE, "selftest_rung": self.st_index,
            "steps_total": self.steps_total, "drv_status": format!("0x{:08X}", self.drv_status),
        })
    }
}

// ------------------------------------------------------------ simulated stage --

extern "C" {
    fn smi_stage_shim_size() -> usize;
    fn smi_stage_shim_init(
        s: *mut c_void,
        ctx: *mut c_void,
        put: extern "C" fn(*mut c_void, u8, bool),
        home: extern "C" fn(*mut c_void) -> bool,
        wait: extern "C" fn(*mut c_void, u32),
        uart: extern "C" fn(*mut c_void, *const u8, usize, *mut u8, usize) -> bool,
    );
    fn smi_stage_tick(s: *mut c_void, now_us: u32);
    fn smi_stage_command(s: *mut c_void, p: *const u8, n: usize, seq: u16, now_us: u32, resp: *mut u8) -> usize;
    fn smi_stage_state(s: *const c_void, out: *mut u8) -> usize;
}

/// Model values for the simulated mechanism, not measurements. The true scale
/// sits inside the stage map's geometry-only range (14.64 to 16.65 nm/pulse)
/// but off the nominal 15.625, so the self-test and Calibrate have something
/// real to find.
pub mod mech {
    pub const TRUE_NM_PER_PULSE: f64 = 15.31;
    /// Lost motion at each reversal (static friction and driver compliance), pulses.
    pub const LOST_PULSES: f64 = 1.6;
    /// Mirror follows the screw through the lever with this time constant, s.
    pub const TAU_S: f64 = 0.002;
    /// PETG warming drift of the apparent position, nm/s.
    pub const DRIFT_NM_S: f64 = 0.6;
    /// Where the screw is at power-up, pulses from the HOME edge.
    pub const START_PULSES: i64 = 830;
}

const SIM_STEP_GPIO: u8 = 10;
const SIM_DIR_GPIO: u8 = 11;
const SIM_EN_GPIO: u8 = 12;

/// The simulated TMC2209 and mechanism behind the HAL callbacks.
pub struct Mech {
    step: bool,
    dir: bool,
    en_n: bool,
    /// Screw position in pulses from the HOME switch edge (switch opens at <= 0).
    pub pulses: i64,
    /// Effective (after lost motion) position, pulses.
    eff: f64,
    regs: [u32; 128],
    ifcnt: u8,
    pub uart_ok: bool,
}

extern "C" fn m_put(ctx: *mut c_void, g: u8, v: bool) {
    // SAFETY: ctx is the Box<Mech> owned by the SimStage that registered it.
    let m = unsafe { &mut *(ctx as *mut Mech) };
    match g {
        SIM_STEP_GPIO => {
            if v && !m.step && !m.en_n {
                // Firmware DIR level true = positive (away from HOME).
                m.pulses += if m.dir { 1 } else { -1 };
            }
            m.step = v;
        }
        SIM_DIR_GPIO => m.dir = v,
        SIM_EN_GPIO => m.en_n = v,
        _ => {}
    }
}
extern "C" fn m_home(ctx: *mut c_void) -> bool {
    // SAFETY: as above.
    let m = unsafe { &*(ctx as *const Mech) };
    m.pulses <= 0
}
extern "C" fn m_wait(_ctx: *mut c_void, _us: u32) {}

fn tmc_crc(d: &[u8]) -> u8 {
    let mut crc = 0u8;
    for &x in d {
        let mut b = x;
        for _ in 0..8 {
            crc = if ((crc >> 7) ^ (b & 1)) != 0 { (crc << 1) ^ 0x07 } else { crc << 1 };
            b >>= 1;
        }
    }
    crc
}

extern "C" fn m_uart(ctx: *mut c_void, tx: *const u8, ntx: usize, rx: *mut u8, nrx: usize) -> bool {
    // SAFETY: ctx as above; tx has ntx bytes and rx room for nrx bytes (smi_stage.c).
    let m = unsafe { &mut *(ctx as *mut Mech) };
    let tx = unsafe { std::slice::from_raw_parts(tx, ntx) };
    if !m.uart_ok || ntx < 4 || tx[0] != 0x05 || tx[ntx - 1] != tmc_crc(&tx[..ntx - 1]) {
        return false;
    }
    let reg = (tx[2] & 0x7F) as usize;
    if ntx == 8 && tx[2] & 0x80 != 0 {
        let v = u32::from_be_bytes([tx[3], tx[4], tx[5], tx[6]]);
        if reg == 0x01 { m.regs[reg] &= !v } else { m.regs[reg] = v }
        m.ifcnt = m.ifcnt.wrapping_add(1);
        return nrx == 0;
    }
    if ntx != 4 || nrx != 8 {
        return false;
    }
    let v = match reg {
        0x02 => m.ifcnt as u32,
        0x06 => (0x21u32 << 24) | 0x40, // version 0x21, SPREAD high
        _ => m.regs[reg],
    };
    let b = v.to_be_bytes();
    let mut r = [0x05, 0xFF, reg as u8, b[0], b[1], b[2], b[3], 0];
    r[7] = tmc_crc(&r[..7]);
    // SAFETY: rx has room for 8 bytes.
    unsafe { std::ptr::copy_nonoverlapping(r.as_ptr(), rx, 8) };
    true
}

pub struct SimStage {
    core: Vec<u64>,
    pub mech: Box<Mech>,
    /// Mirror displacement, nm (lagging the effective screw position, plus drift).
    pub mirror_nm: f64,
    drift_nm: f64,
    last_us: u64,
}

/// Mirror positions over one chunk, one every `dt_us`.
pub struct StageTraj {
    pub nm: Vec<f64>,
    pub dt_us: f64,
}

impl SimStage {
    pub fn new(now_us: u64) -> Self {
        // SAFETY: plain C struct size.
        let n = unsafe { smi_stage_shim_size() };
        let mut regs = [0u32; 128];
        regs[0x01] = 1; // GSTAT reset flag set after power-up
        let mut s = SimStage {
            core: vec![0u64; n.div_ceil(8) + 1],
            mech: Box::new(Mech { step: false, dir: true, en_n: true, pulses: mech::START_PULSES, eff: mech::START_PULSES as f64, regs, ifcnt: 0, uart_ok: true }),
            mirror_nm: mech::START_PULSES as f64 * mech::TRUE_NM_PER_PULSE,
            drift_nm: 0.0,
            last_us: now_us,
        };
        let ctx = &mut *s.mech as *mut Mech as *mut c_void;
        // SAFETY: core is large enough for smi_stage_t; ctx outlives it (both owned here).
        unsafe { smi_stage_shim_init(s.core.as_mut_ptr() as *mut c_void, ctx, m_put, m_home, m_wait, m_uart) };
        s
    }

    pub fn command(&mut self, payload: &[u8], seq: u16, now_us: u64) -> Vec<u8> {
        let mut r = vec![0u8; 64];
        // SAFETY: r has room for the 28-byte ACK.
        let n = unsafe { smi_stage_command(self.core.as_mut_ptr() as *mut c_void, payload.as_ptr(), payload.len(), seq, now_us as u32, r.as_mut_ptr()) };
        r.truncate(n);
        r
    }

    pub fn state(&self) -> StageState {
        let mut r = [0u8; 32];
        // SAFETY: r has room for the 24-byte state block.
        let n = unsafe { smi_stage_state(self.core.as_ptr() as *const c_void, r.as_mut_ptr()) };
        StageState::parse(&r[..n]).unwrap_or_default()
    }

    /// Run the firmware core every 50 us up to `now_us` and move the mechanism.
    pub fn advance(&mut self, now_us: u64) -> StageTraj {
        const DT: u64 = 50;
        let mut nm = vec![];
        let a = 1.0 - (-(DT as f64) * 1e-6 / mech::TAU_S).exp();
        while self.last_us + DT <= now_us {
            self.last_us += DT;
            // SAFETY: core initialised in new().
            unsafe { smi_stage_tick(self.core.as_mut_ptr() as *mut c_void, self.last_us as u32) };
            let m = &mut *self.mech;
            let p = m.pulses as f64;
            let half = mech::LOST_PULSES / 2.0;
            if p - m.eff > half {
                m.eff = p - half;
            } else if m.eff - p > half {
                m.eff = p + half;
            }
            self.drift_nm += mech::DRIFT_NM_S * DT as f64 * 1e-6;
            let want = m.eff * mech::TRUE_NM_PER_PULSE + self.drift_nm;
            self.mirror_nm += (want - self.mirror_nm) * a;
            nm.push(self.mirror_nm);
        }
        StageTraj { nm, dt_us: DT as f64 }
    }
}

// ----------------------------------------------------------------- analysis --

/// One point of the stage trace (50 Hz): what the stage reported and what the
/// fringes counted at the same sample.
#[derive(Clone, Debug, Serialize)]
pub struct TracePt {
    pub t_s: f64,
    pub pos: i32,
    pub moving: bool,
    pub state: u8,
    pub homed: bool,
    /// Counted displacement (raw fringe count x lambda/2), nm.
    pub meas_nm: f64,
    /// Simulated mirror position, nm (NaN on hardware).
    pub truth_nm: f64,
}

#[derive(Clone, Debug, Serialize)]
pub struct Plateau {
    pub pos: i32,
    pub t_s: f64,
    pub meas_nm: f64,
    pub truth_nm: f64,
    pub n: usize,
}

/// Plateaus of a self-test: runs of points in the self-test state, not moving,
/// at one position; the mean of the last 60 % of each (settled).
pub fn plateaus(tr: &[TracePt]) -> Vec<Plateau> {
    let mut out = vec![];
    let mut i = 0;
    while i < tr.len() {
        let p = &tr[i];
        if p.state != ST_SELFTEST || p.moving {
            i += 1;
            continue;
        }
        let mut j = i;
        while j < tr.len() && tr[j].state == ST_SELFTEST && !tr[j].moving && tr[j].pos == p.pos {
            j += 1;
        }
        let run = &tr[i..j];
        if run.len() >= 5 {
            let k = run.len() * 2 / 5;
            let s = &run[k..];
            let n = s.len() as f64;
            out.push(Plateau {
                pos: p.pos,
                t_s: s.iter().map(|x| x.t_s).sum::<f64>() / n,
                meas_nm: s.iter().map(|x| x.meas_nm).sum::<f64>() / n,
                truth_nm: s.iter().map(|x| x.truth_nm).sum::<f64>() / n,
                n: s.len(),
            });
        }
        i = j;
    }
    out
}

/// Least squares y = s p + d t + b. Returns (s, d, b).
fn fit3(ps: &[(f64, f64, f64)]) -> Option<(f64, f64, f64)> {
    let mut a = [[0.0f64; 3]; 3];
    let mut r = [0.0f64; 3];
    for &(p, t, y) in ps {
        let x = [p, t, 1.0];
        for i in 0..3 {
            for j in 0..3 {
                a[i][j] += x[i] * x[j];
            }
            r[i] += x[i] * y;
        }
    }
    // Gaussian elimination with partial pivoting.
    for c in 0..3 {
        let piv = (c..3).max_by(|&i, &j| a[i][c].abs().partial_cmp(&a[j][c].abs()).unwrap())?;
        if a[piv][c].abs() < 1e-12 {
            return None;
        }
        a.swap(c, piv);
        r.swap(c, piv);
        for i in 0..3 {
            if i != c {
                let f = a[i][c] / a[c][c];
                for j in 0..3 {
                    a[i][j] -= f * a[c][j];
                }
                r[i] -= f * r[c];
            }
        }
    }
    Some((r[0] / a[0][0], r[1] / a[1][1], r[2] / a[2][2]))
}

/// The stage map's self-test analysis on one set of plateaus, for either the
/// counted (`truth = false`) or the simulated true (`truth = true`) position.
fn analyse_one(pl: &[Plateau], truth: bool) -> Value {
    let y = |p: &Plateau| if truth { p.truth_nm } else { p.meas_nm };
    let pts: Vec<(f64, f64, f64)> = pl.iter().map(|p| (p.pos as f64, p.t_s - pl[0].t_s, y(p))).collect();
    let Some((s, d, b)) = fit3(&pts) else { return json!(null) };
    let resid: Vec<f64> = pts.iter().map(|&(p, t, v)| v - (s * p + d * t + b)).collect();
    let rms = (resid.iter().map(|r| r * r).sum::<f64>() / resid.len() as f64).sqrt();
    // Matched forward and reverse plateaus at the same commanded position.
    let mut rev = vec![];
    for i in 1..pl.len() {
        for j in (i + 1)..pl.len() {
            if pl[i].pos == pl[j].pos && j != pl.len() - 1 {
                let e = (y(&pl[j]) - y(&pl[i])) - d * (pl[j].t_s - pl[i].t_s);
                rev.push(json!({"pos_pulses": pl[i].pos, "reverse_minus_forward_nm": (e * 10.0).round() / 10.0}));
            }
        }
    }
    let last = pl.len() - 1;
    let ret_raw = y(&pl[last]) - y(&pl[0]);
    let ret = ret_raw - d * (pl[last].t_s - pl[0].t_s);
    json!({
        "nm_per_pulse": s, "scale_vs_nominal_pct": (s / NM_PER_PULSE - 1.0) * 100.0,
        "drift_nm_s": d, "fit_rms_nm": rms, "reversal": rev,
        "return_residual_nm": ret_raw, "return_residual_drift_corrected_nm": ret,
        "plateau_residuals_nm": resid.iter().map(|r| (r * 10.0).round() / 10.0).collect::<Vec<_>>(),
    })
}

/// Scale from the fringe edges of one-direction motion: each change of the
/// count is placed at the stage position where it happened, and a straight
/// line through (pulses, counted nm) gives the slope far below one fringe.
/// Returns (nm per pulse, edges, rms of the fit in nm).
pub fn edge_fit(tr: &[TracePt]) -> Option<(f64, usize, f64)> {
    let mut pts = vec![];
    for w in tr.windows(2) {
        if (w[1].meas_nm - w[0].meas_nm).abs() > 1.0 && w[1].pos != w[0].pos {
            pts.push(((w[0].pos + w[1].pos) as f64 / 2.0, w[1].meas_nm));
        }
    }
    if pts.len() < 6 {
        return None;
    }
    let n = pts.len() as f64;
    let (mx, my) = (pts.iter().map(|p| p.0).sum::<f64>() / n, pts.iter().map(|p| p.1).sum::<f64>() / n);
    let sxx: f64 = pts.iter().map(|p| (p.0 - mx).powi(2)).sum();
    if sxx <= 0.0 {
        return None;
    }
    let k = pts.iter().map(|p| (p.0 - mx) * (p.1 - my)).sum::<f64>() / sxx;
    let rms = (pts.iter().map(|p| (p.1 - my - k * (p.0 - mx)).powi(2)).sum::<f64>() / n).sqrt();
    Some((k, pts.len(), rms))
}

pub fn analyse(pl: &[Plateau], simulated: bool, half_wave_nm: f64) -> Value {
    let counted = analyse_one(pl, false);
    let mut v = json!({
        "status": "done",
        "simulated": simulated,
        "label": if simulated { "simulated" } else { "measured" },
        "plateaus": pl,
        "counted": counted,
        "resolution_nm": half_wave_nm,
        "note": format!("The fringe counter resolves whole fringes, {half_wave_nm:.0} nm, so a residual below that is not resolved by counting. The headline scale is fitted to the counted fringe edges, each placed at the stage position where it happened, which resolves the slope far below one fringe; the plateau fit uses whole-fringe plateaus and is coarser."),
    });
    if simulated {
        v["truth"] = analyse_one(pl, true);
        v["truth_note"] = json!(format!("Simulated mechanism: true {:.3} nm/pulse, {:.1} pulses of lost motion at each reversal, {:.1} nm/s drift (model values)", mech::TRUE_NM_PER_PULSE, mech::LOST_PULSES, mech::DRIFT_NM_S));
    }
    v
}

// ------------------------------------------------------------------ commands --

fn fail(m: impl Into<String>, h: &[&str]) -> Fail {
    (m.into(), h.iter().map(|s| s.to_string()).collect())
}

/// Send one stage command to the simulated stage or the Pico.
pub async fn stage_cmd(a: &Arc<App>, s: u8, arg: i32) -> Result<(u8, StageState), Fail> {
    let (sim, link) = {
        let e = a.engine.lock().unwrap();
        (matches!(e.source, SourceKind::Sim), e.cmdlink.clone())
    };
    let payload = cmd(s, arg);
    let r = if sim {
        a.engine.lock().unwrap().sim_stage_command(&payload)
    } else {
        match tokio::task::spawn_blocking(move || link.call(&payload)).await {
            Ok(Ok(ack)) => {
                let mut v = vec![0u8, 0, ack.op, ack.status];
                v.extend_from_slice(&ack.data);
                v
            }
            Ok(Err(m)) => return Err((m, vec!["The Pico needs firmware 1.3.1 for the stage (`smi-dash status` shows its info line)".into()])),
            Err(e) => return Err(fail(format!("command task failed: {e}"), &[])),
        }
    };
    if r.len() < 28 || r[2] != OP_STAGE {
        return Err(fail("no stage answer: the firmware may predate 1.3.1", &["Flash smi_pico.uf2 1.3.1"]));
    }
    let st = StageState::parse(&r[4..]).ok_or_else(|| fail("malformed stage ACK", &[]))?;
    if !sim {
        a.engine.lock().unwrap().pico_stage = Some((st.clone(), Instant::now()));
    }
    Ok((r[3], st))
}

/// As stage_cmd, but a refusal is an error with the firmware's reason.
pub async fn stage_ok(a: &Arc<App>, s: u8, arg: i32) -> Result<StageState, Fail> {
    let (code, st) = stage_cmd(a, s, arg).await?;
    if code != 0 {
        let mut h = hint_for(code);
        if code == 15 || st.fault != 0 {
            h.insert(0, format!("Fault: {}", fault_text(st.fault)));
        }
        return Err((status_text(code).to_string(), h));
    }
    Ok(st)
}

pub fn current_state(a: &Arc<App>) -> Option<StageState> {
    a.engine.lock().unwrap().stage_state()
}

/// Wait until the stage is not homing, moving or self-testing.
pub async fn wait_idle(a: &Arc<App>, max: Duration) -> Result<StageState, Fail> {
    let t = Instant::now();
    loop {
        tokio::time::sleep(Duration::from_millis(40)).await;
        let Some(st) = current_state(a) else { return Err(fail("no stage state", &["Is the Pico running firmware 1.3.1?"])) };
        if st.state == ST_FAULTED {
            return Err((format!("stage fault: {}", fault_text(st.fault)), vec!["`smi-dash stage off`, fix the cause, then `smi-dash stage home`".into()]));
        }
        if !matches!(st.state, 2..=4) {
            return Ok(st);
        }
        if t.elapsed() > max {
            return Err(fail(format!("the stage did not finish within {} s", max.as_secs()), &["`smi-dash stage stop`"]));
        }
        if CAL_CANCEL.load(Ordering::SeqCst) && CAL_RUNNING.load(Ordering::SeqCst) {
            let _ = stage_cmd(a, sub::STOP, 0).await;
            return Err(fail("stopped", &[]));
        }
    }
}

/// The simulator's target becomes the stage mirror (profile "stage").
pub fn sim_follow_stage(a: &Arc<App>) -> bool {
    let mut e = a.engine.lock().unwrap();
    if matches!(e.source, SourceKind::Sim) && e.sim_p.profile != crate::sim::Profile::Stage {
        e.sim_p.profile = crate::sim::Profile::Stage;
        e.sim_rev += 1;
        return true;
    }
    false
}

/// Counted displacement now (raw count x lambda/2), nm.
fn counted(a: &Arc<App>) -> f64 {
    a.engine.lock().unwrap().det.displacement_nm()
}

/// Home if needed; returns the state.
pub async fn ensure_homed(a: &Arc<App>) -> Result<StageState, Fail> {
    let st = current_state(a).ok_or_else(|| fail("no stage state", &[]))?;
    if st.homed && st.enabled {
        return Ok(st);
    }
    stage_ok(a, sub::HOME, 0).await?;
    let st = wait_idle(a, Duration::from_secs(60)).await?;
    if !st.homed {
        return Err(fail("homing did not complete", &[]));
    }
    Ok(st)
}

// ----------------------------------------------------------------- self-test --

fn st_progress(a: &Arc<App>, v: Value) {
    a.engine.lock().unwrap().stage_selftest = v;
}

/// Run the firmware self-test (origin 128, +128 x 4, -128 x 4, 1 s dwells) and
/// analyse the plateaus from the stage trace.
pub async fn selftest(a: &Arc<App>) -> Result<Value, Fail> {
    sim_follow_stage(a);
    ensure_homed(a).await?;
    let t0 = a.engine.lock().unwrap().head as f64 / crate::sim::FS;
    st_progress(a, json!({"status": "running", "rung": 0}));
    stage_ok(a, sub::SELFTEST, 0).await?;
    let t = Instant::now();
    loop {
        tokio::time::sleep(Duration::from_millis(100)).await;
        let st = current_state(a).ok_or_else(|| fail("no stage state", &[]))?;
        if st.state == ST_FAULTED {
            return Err((format!("stage fault during the self-test: {}", fault_text(st.fault)), vec![]));
        }
        if st.state != ST_SELFTEST {
            break;
        }
        st_progress(a, json!({"status": "running", "rung": st.st_index, "pos_pulses": st.pos}));
        if t.elapsed() > Duration::from_secs(90) {
            let _ = stage_cmd(a, sub::STOP, 0).await;
            return Err(fail("the self-test did not finish within 90 s", &[]));
        }
    }
    tokio::time::sleep(Duration::from_millis(60)).await;
    let (tr, sim, half) = {
        let e = a.engine.lock().unwrap();
        let tr: Vec<TracePt> = e.stage_trace.iter().filter(|p| p.t_s >= t0).cloned().collect();
        (tr, matches!(e.source, SourceKind::Sim), e.det.half_wave_nm())
    };
    let pl = plateaus(&tr);
    if pl.len() != 9 {
        return Err((format!("found {} plateaus, expected 9 (origin plus 8 rungs)", pl.len()), vec!["Was the self-test stopped? Run it again".into()]));
    }
    let mut v = analyse(&pl, sim, half);
    // Sub-fringe scale from the counted fringe edges, outbound and return sweeps.
    for (k, a0, a1) in [("edge_fit_out", pl[0].t_s, pl[4].t_s), ("edge_fit_back", pl[4].t_s, pl[8].t_s)] {
        let seg: Vec<TracePt> = tr.iter().filter(|p| p.t_s >= a0 && p.t_s <= a1).cloned().collect();
        v["counted"][k] = match edge_fit(&seg) {
            Some((s, n, r)) => json!({"nm_per_pulse": s, "edges": n, "rms_nm": r}),
            None => Value::Null,
        };
    }
    v["seconds"] = json!(t.elapsed().as_secs_f64());
    // Headline scale: the edge fits, weighted by their edge counts; else the plateau fit.
    let (mut sw, mut nw) = (0.0, 0.0);
    for k in ["edge_fit_out", "edge_fit_back"] {
        if let (Some(x), Some(n)) = (v["counted"][k]["nm_per_pulse"].as_f64(), v["counted"][k]["edges"].as_f64()) {
            sw += x.abs() * n;
            nw += n;
        }
    }
    let both = !v["counted"]["edge_fit_out"].is_null() && !v["counted"]["edge_fit_back"].is_null();
    v["scale_nm_per_pulse"] = if both { json!(sw / nw) } else { Value::Null };
    v["scale_edges"] = json!(nw);
    let slope = if both { sw / nw } else { 0.0 };
    if slope < 0.5 * GEOMETRY_NM_PER_PULSE[0] || slope > 1.5 * GEOMETRY_NM_PER_PULSE[1] {
        let on = a.engine.lock().unwrap().board_state().is_some_and(|s| s.laser_on);
        v["warning"] = json!(if !on {
            "No fringes were counted: the laser is off. Turn it on (`smi-dash laser on --beam-safe`) or run `smi-dash calibrate --beam-safe`"
        } else {
            "The counted scale is far from the stage's geometry range: fringes were missed. Run `smi-dash calibrate --beam-safe` (or Tune with the stage moving)"
        });
    }
    st_progress(a, v.clone());
    Ok(v)
}

pub fn spawn_selftest(a: Arc<App>) -> Result<(), Fail> {
    if SELFTEST_RUNNING.swap(true, Ordering::SeqCst) {
        return Err(fail("a self-test is already running", &["Watch it with `smi-dash stage selftest --status`"]));
    }
    st_progress(&a, json!({"status": "running", "rung": 0}));
    tokio::spawn(async move {
        match selftest(&a).await {
            Ok(v) => {
                let c = &v["counted"];
                let txt = match v["scale_nm_per_pulse"].as_f64() {
                    Some(sc) => format!("Self-test ({}): {:.3} nm/pulse, return residual {:.0} nm (counted)", v["label"].as_str().unwrap_or(""), sc, c["return_residual_nm"].as_f64().unwrap_or(0.0)),
                    None => format!("Self-test ({}): fringes missed; see the warning", v["label"].as_str().unwrap_or("")),
                };
                a.broadcast("toast", json!({"text": txt, "kind": if v["warning"].is_null() { "success" } else { "error" }}));
            }
            Err((m, h)) => {
                st_progress(&a, json!({"status": "failed", "error": m, "hints": h}));
                a.broadcast("toast", json!({"text": format!("Self-test: {m}"), "kind": "error"}));
            }
        }
        SELFTEST_RUNNING.store(false, Ordering::SeqCst);
    });
    Ok(())
}

// ----------------------------------------------------------------- calibrate --

fn cal_progress(a: &Arc<App>, step: &str, k: usize, extra: Value) {
    let mut e = a.engine.lock().unwrap();
    let mut v = e.calib.clone();
    v["status"] = json!("running");
    v["step"] = json!(step);
    v["step_n"] = json!(k);
    v["steps_total"] = json!(6);
    if let Some(o) = extra.as_object() {
        for (key, val) in o {
            v[key] = val.clone();
        }
    }
    e.calib = v;
}

fn cancelled() -> Result<(), Fail> {
    if CAL_CANCEL.load(Ordering::SeqCst) {
        return Err(fail("calibration stopped", &[]));
    }
    Ok(())
}

/// Settings and fringe score now, for the before/after report.
fn snapshot_settings(a: &Arc<App>) -> Value {
    let e = a.engine.lock().unwrap();
    let st = e.board_state();
    let map = &e.map;
    let s1 = e.chan_stats(1, 50_000);
    let gain = |ch: u8| map.find("gain", Some(ch), Some("amp")).and_then(|i| st.as_ref().and_then(|s| s.targets.get(i).copied()));
    let off = |ch: u8| map.find("offset", Some(ch), None).and_then(|i| st.as_ref().and_then(|s| s.targets.get(i).copied()));
    json!({
        "laser_on": st.as_ref().is_some_and(|s| s.laser_on),
        "laser_mA": st.as_ref().map(|s| s.laser_target_ma),
        "measured_mA": st.as_ref().filter(|s| s.isense_valid).map(|s| s.isense_ma),
        "isense_zero_code": st.as_ref().and_then(|s| s.zero_code),
        "ch1_gain": gain(1), "ch2_gain": gain(2), "ch1_offset_V": off(1), "ch2_offset_V": off(2),
        "ch1_mean": s1.mean.round(),
    })
}

/// Step the stage +pulses from its present position, count the fringes, and
/// come back. Returns the counted distance against the commanded one.
async fn check_distance(a: &Arc<App>, start: i32, pulses: i32, rate: i32) -> Result<Value, Fail> {
    stage_ok(a, sub::SPEED, rate).await?;
    stage_ok(a, sub::MOVE_TO, start).await?;
    wait_idle(a, Duration::from_secs(30)).await?;
    tokio::time::sleep(Duration::from_millis(400)).await;
    // Put the plot's counted trace on the commanded one here (laser changes
    // before this, such as Tune's current steps, also make fringes).
    a.engine.lock().unwrap().stage_align();
    let c0 = counted(a);
    let t0 = truth(a);
    let ts0 = a.engine.lock().unwrap().head as f64 / crate::sim::FS;
    stage_ok(a, sub::MOVE_TO, start + pulses).await?;
    // The fringe swing and noise while the target moves (mid-move, 1 s).
    let move_s = pulses as f64 / rate as f64;
    tokio::time::sleep(Duration::from_secs_f64((move_s / 2.0 + 0.5).min(move_s - 0.1).max(0.2))).await;
    let ms = a.engine.lock().unwrap().chan_stats(1, ((move_s * 0.4).min(1.0) * 250_000.0) as usize);
    wait_idle(a, Duration::from_secs(30)).await?;
    let ts1 = a.engine.lock().unwrap().head as f64 / crate::sim::FS;
    let seg: Vec<TracePt> = a.engine.lock().unwrap().stage_trace.iter().filter(|p| p.t_s >= ts0 && p.t_s <= ts1).cloned().collect();
    let fit = edge_fit(&seg);
    tokio::time::sleep(Duration::from_millis(400)).await;
    let c1 = counted(a);
    let t1 = truth(a);
    stage_ok(a, sub::MOVE_TO, start).await?;
    wait_idle(a, Duration::from_secs(30)).await?;
    tokio::time::sleep(Duration::from_millis(400)).await;
    let c2 = counted(a);
    let t2 = truth(a);
    let nominal = pulses as f64 * NM_PER_PULSE;
    let cnt = c1 - c0;
    Ok(json!({
        "pulses": pulses, "commanded_nm_nominal": nominal, "counted_nm": cnt,
        "counted_fringes": (cnt / a.engine.lock().unwrap().det.half_wave_nm()).round(),
        "error_vs_nominal_nm": cnt - nominal, "error_vs_nominal_pct": if nominal != 0.0 { (cnt / nominal - 1.0) * 100.0 } else { 0.0 },
        "nm_per_pulse_counted": cnt / pulses as f64,
        "nm_per_pulse_edge_fit": fit.map(|f| f.0), "edge_fit_edges": fit.map(|f| f.1), "edge_fit_rms_nm": fit.map(|f| f.2),
        "moving_swing_codes": ms.swing.round(), "moving_noise_codes": (ms.noise * 100.0).round() / 100.0, "moving_score": (tune::score(&ms) * 10.0).round() / 10.0,
        "error_vs_truth_nm": cnt - (t1 - t0),
        "return_counted_nm": c2 - c0,
        "truth_nm": t1 - t0, "truth_return_nm": t2 - t0,
    }))
}

fn truth(a: &Arc<App>) -> f64 {
    a.engine.lock().unwrap().readout()["truth_nm"].as_f64().unwrap_or(f64::NAN)
}

/// Move the stage back and forth until `stop` is set (the moving target for Tune).
fn spawn_bounce(a: Arc<App>, stop: Arc<AtomicBool>) -> tokio::task::JoinHandle<()> {
    tokio::spawn(async move {
        let mut up = true;
        let _ = stage_cmd(&a, sub::SPEED, RATE_MAX).await;
        while !stop.load(Ordering::SeqCst) {
            let st = current_state(&a);
            if st.as_ref().is_some_and(|s| s.state == ST_IDLE) {
                let _ = stage_cmd(&a, sub::MOVE_TO, if up { TRAVEL - 200 } else { 200 }).await;
                up = !up;
            }
            if st.as_ref().is_some_and(|s| s.state == ST_FAULTED || s.state == ST_OFF) {
                break;
            }
            tokio::time::sleep(Duration::from_millis(30)).await;
        }
        let _ = stage_cmd(&a, sub::STOP, 0).await;
    })
}

#[derive(Clone, Debug, serde::Deserialize)]
#[serde(default)]
pub struct CalParams {
    pub confirm: Option<String>,
    /// Pulses for the re-check move.
    pub check_pulses: i32,
    /// Laser current to start from when the laser is off (mA).
    pub start_ma: f64,
}

impl Default for CalParams {
    fn default() -> Self {
        Self { confirm: None, check_pulses: 1024, start_ma: 75.0 }
    }
}

/// Calibrate: the stage is the moving target. Home; record the settings and a
/// counted-against-commanded check as they are; zero the current readback with
/// the laser off; turn it back on; auto-centre; tune while the stage moves back
/// and forth; check again; report before and after.
pub async fn calibrate(a: &Arc<App>, p: &CalParams) -> Result<Value, Fail> {
    let t0 = Instant::now();
    let sim = matches!(a.engine.lock().unwrap().source, SourceKind::Sim);
    let li = a.engine.lock().unwrap().map.laser();
    sim_follow_stage(a);
    cal_progress(a, "home", 1, json!({}));
    ensure_homed(a).await?;
    cancelled()?;

    // 1. Before: as the board is, laser on (from the start current if it was off).
    let was_on = a.engine.lock().unwrap().board_state().is_some_and(|s| s.laser_on);
    cal_progress(a, "before", 2, json!({}));
    if !was_on {
        let cur = a.engine.lock().unwrap().board_state().map(|s| s.laser_target_ma as f64).unwrap_or(0.0);
        tune::laser(a, true).await?;
        if cur < 1.0 {
            tune::set(a, li, 0, p.start_ma).await?;
        }
        tune::wait_settled(a).await?;
        tokio::time::sleep(Duration::from_millis(300)).await;
    }
    let before = snapshot_settings(a);
    let before_check = check_distance(a, 128, p.check_pulses, RATE_DEFAULT).await?;
    cancelled()?;

    // 2. Current-readback zero: laser off, wait for the zero code to settle.
    cal_progress(a, "readback zero", 3, json!({"before": {"settings": before, "check": before_check}}));
    let keep_ma = a.engine.lock().unwrap().board_state().map(|s| s.laser_target_ma as f64).unwrap_or(p.start_ma);
    tune::laser(a, false).await?;
    let tz = Instant::now();
    let zero = loop {
        tokio::time::sleep(Duration::from_millis(100)).await;
        let st = a.engine.lock().unwrap().board_state();
        let z = st.as_ref().and_then(|s| s.zero_code);
        let ma = st.as_ref().filter(|s| s.isense_valid).map(|s| s.isense_ma);
        if tz.elapsed() > Duration::from_millis(1500) && z.is_some() {
            break json!({"zero_code": z, "reading_with_laser_off_mA": ma, "seconds": tz.elapsed().as_secs_f64()});
        }
        if tz.elapsed() > Duration::from_secs(6) {
            return Err(fail("the current readback did not validate its zero within 6 s with the laser off", &["Check the head ADS1115 with `smi-dash board`"]));
        }
    };
    cancelled()?;

    // 3. Back on at the same set-point, then auto-centre both channels.
    cal_progress(a, "auto-centre", 4, json!({"zero": zero}));
    tune::laser(a, true).await?;
    tune::set(a, li, 0, keep_ma).await?;
    tune::wait_settled(a).await?;
    let mut centre = vec![];
    for ch in [1u8, 2] {
        centre.push(tune::auto_centre(a, ch).await.unwrap_or_else(|(m, _)| json!({"channel": ch, "error": m})));
    }
    cancelled()?;

    // 4. Tune with the stage moving back and forth at its maximum rate.
    cal_progress(a, "tune (stage moving)", 5, json!({"centre": centre}));
    if tune::TUNE_RUNNING.swap(true, Ordering::SeqCst) {
        return Err(fail("a tune is already running", &["Stop it with `smi-dash tune --stop`"]));
    }
    tune::TUNE_CANCEL.store(false, Ordering::SeqCst);
    let stop = Arc::new(AtomicBool::new(false));
    let bounce = spawn_bounce(a.clone(), stop.clone());
    let tuned = tune::tune(a.clone(), tune::TuneParams::default()).await;
    stop.store(true, Ordering::SeqCst);
    let _ = bounce.await;
    tune::TUNE_RUNNING.store(false, Ordering::SeqCst);
    let tuned = tuned?;
    wait_idle(a, Duration::from_secs(30)).await?;
    cancelled()?;

    // 5. Re-check: counted against commanded distance with the new settings.
    cal_progress(a, "re-check", 6, json!({"tune": {"best_mA": tuned["best_mA"], "gain": tuned["gain"], "final_score": tuned["final_score"], "steps": tuned["steps"].as_array().map(|s| s.len())}}));
    let after = snapshot_settings(a);
    let after_check = check_distance(a, 128, p.check_pulses, RATE_DEFAULT).await?;
    stage_ok(a, sub::SPEED, RATE_DEFAULT).await?;

    // 6. Report, and keep the counted scale for the commanded trace.
    let scale = after_check["nm_per_pulse_edge_fit"].as_f64().or(after_check["nm_per_pulse_counted"].as_f64()).unwrap_or(f64::NAN);
    let plausible = scale.abs() > 0.5 * GEOMETRY_NM_PER_PULSE[0] && scale.abs() < 1.5 * GEOMETRY_NM_PER_PULSE[1];
    if plausible {
        a.engine.lock().unwrap().stage_cal = Some(json!({"nm_per_pulse": scale.abs(), "sign": scale.signum(), "simulated": sim, "at": chrono::Local::now().to_rfc3339()}));
    }
    let report = json!({
        "status": "done",
        "simulated": sim,
        "label": if sim { "simulated" } else { "measured" },
        "seconds": t0.elapsed().as_secs_f64(),
        "before": {"settings": before, "check": before_check},
        "zero": zero,
        "centre": centre,
        "tune": {"best_mA": tuned["best_mA"], "gain": tuned["gain"], "final_score": tuned["final_score"], "note": tuned["note"], "steps": tuned["steps"].as_array().map(|s| s.len())},
        "after": {"settings": after, "check": after_check},
        "scale_nm_per_pulse": if plausible { json!(scale.abs()) } else { Value::Null },
        "scale_note": if plausible { json!(format!("Commanded positions now use {:.3} nm/pulse (fitted to the counted fringe edges of the re-check) instead of the nominal 15.625", scale.abs())) } else { json!("The counted scale is outside the plausible range; the nominal 15.625 nm/pulse stays") },
        "laser_left_on": true,
        "note": if was_on { "The laser was on before and is on after." } else { "The laser was off before; Calibrate turned it on with the interlock confirmed and leaves it on. `smi-dash laser off` turns it off." },
    });
    a.engine.lock().unwrap().calib = report.clone();
    Ok(report)
}

pub fn spawn_calibrate(a: Arc<App>, p: CalParams) -> Result<(), Fail> {
    if CAL_RUNNING.swap(true, Ordering::SeqCst) {
        return Err(fail("Calibrate is already running", &["Watch it with `smi-dash calibrate --status`"]));
    }
    CAL_CANCEL.store(false, Ordering::SeqCst);
    a.engine.lock().unwrap().calib = json!({"status": "running", "step": "start", "step_n": 0, "steps_total": 6});
    tokio::spawn(async move {
        match calibrate(&a, &p).await {
            Ok(r) => {
                let ca = &r["after"]["check"];
                let cb = &r["before"]["check"];
                a.broadcast("toast", json!({"text": format!("Calibrate ({}): counted {:.0} of {:.0} nm before, {:.0} after", r["label"].as_str().unwrap_or(""), cb["counted_nm"].as_f64().unwrap_or(0.0), cb["commanded_nm_nominal"].as_f64().unwrap_or(0.0), ca["counted_nm"].as_f64().unwrap_or(0.0)), "kind": "success"}));
            }
            Err((m, h)) => {
                tune::TUNE_CANCEL.store(true, Ordering::SeqCst);
                let mut e = a.engine.lock().unwrap();
                let mut v = e.calib.clone();
                v["status"] = json!("failed");
                v["error"] = json!(m);
                v["hints"] = json!(h);
                e.calib = v;
                drop(e);
                a.broadcast("toast", json!({"text": format!("Calibrate: {m}"), "kind": "error"}));
            }
        }
        CAL_RUNNING.store(false, Ordering::SeqCst);
    });
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn run(s: &mut SimStage, t: &mut u64, us: u64) {
        *t += us;
        s.advance(*t);
    }

    #[test]
    fn sim_stage_homes_moves_and_refuses() {
        let mut s = SimStage::new(0);
        let mut t = 0u64;
        let st = s.state();
        assert_eq!(st.state, ST_OFF);
        assert!(!st.enabled && !st.homed, "disabled at boot");
        // Not homed: a step is refused.
        let r = s.command(&cmd(sub::STEP, 10), 1, t);
        assert_eq!(r[3], 11);
        let r = s.command(&cmd(sub::HOME, 0), 2, t);
        assert_eq!(r[3], 0, "home accepted (driver configured over the simulated UART)");
        for _ in 0..400 {
            run(&mut s, &mut t, 100_000);
            if s.state().state == ST_IDLE {
                break;
            }
        }
        let st = s.state();
        assert!(st.homed && st.pos == 0, "homed at the switch edge: {st:?}");
        assert_eq!(s.mech.pulses, 0);
        // Limits.
        assert_eq!(s.command(&cmd(sub::MOVE_TO, 1601), 3, t)[3], 12);
        assert_eq!(s.command(&cmd(sub::STEP, -1), 4, t)[3], 12);
        // A move at 640 pulses/s; a retried sequence number issues no new pulses.
        assert_eq!(s.command(&cmd(sub::SPEED, 640), 5, t)[3], 0);
        assert_eq!(s.command(&cmd(sub::STEP, 320), 6, t)[3], 0);
        let again = s.command(&cmd(sub::STEP, 320), 6, t);
        assert_eq!(again[3], 0);
        run(&mut s, &mut t, 600_000);
        assert_eq!(s.state().pos, 320);
        assert_eq!(s.mech.pulses, 320, "the duplicate did not move it");
        // The mirror follows at the true scale.
        let want = 320.0 * mech::TRUE_NM_PER_PULSE;
        assert!((s.mirror_nm - want).abs() < 30.0, "mirror {} vs {want}", s.mirror_nm);
        // Off: disabled, position invalid.
        assert_eq!(s.command(&cmd(sub::OFF, 0), 7, t)[3], 0);
        assert!(!s.state().homed);
    }

    #[test]
    fn selftest_analysis_recovers_scale_and_drift() {
        let mut tr = vec![];
        let mut t = 0.0;
        let positions = [128, 256, 384, 512, 640, 512, 384, 256, 128];
        for (k, &p) in positions.iter().enumerate() {
            for i in 0..50 {
                let tt = t + i as f64 * 0.02;
                let truth = p as f64 * 15.3 + 0.6 * tt;
                // Counted: whole fringes of 329 nm.
                let meas = (truth / 329.0).round() * 329.0;
                tr.push(TracePt { t_s: tt, pos: p, moving: false, state: ST_SELFTEST, homed: true, meas_nm: meas, truth_nm: truth });
            }
            t += 1.0;
            if k < 8 {
                tr.push(TracePt { t_s: t - 0.01, pos: p, moving: true, state: ST_SELFTEST, homed: true, meas_nm: 0.0, truth_nm: 0.0 });
            }
        }
        let pl = plateaus(&tr);
        assert_eq!(pl.len(), 9);
        let v = analyse(&pl, true, 329.0);
        let s = v["truth"]["nm_per_pulse"].as_f64().unwrap();
        assert!((s - 15.3).abs() < 0.01, "truth slope {s}");
        assert!((v["truth"]["drift_nm_s"].as_f64().unwrap() - 0.6).abs() < 0.05);
        let sc = v["counted"]["nm_per_pulse"].as_f64().unwrap();
        assert!((sc - 15.3).abs() < 0.6, "counted slope {sc}");
    }
}