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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
// SPDX-License-Identifier: MIT
//! Acquisition and processing: one engine owns the sample rings, the detector,
//! the running displacement and the recorder. Sources (simulator or Pico over
//! USB serial) feed it chunks; the server reads display snapshots from it.

use crate::controls::{BoardState, CmdLink, ControlMap, SimBoard};
use crate::dsp::{spectrum, DetectParams, Detector, Fringe};
use crate::proto::{Decoder, Frame};
use crate::record::{Format, Meta, RecStatus, Recorder};
use crate::sim::{SimParams, Simulator, FS};
use crate::stage::{SimStage, StageState, TracePt, NM_PER_PULSE};
use rustfft::FftPlanner;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::VecDeque;
use std::io::Read;
use std::sync::mpsc;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

const RING_BITS: u32 = 19; // 524288 pairs, 2.1 s per channel
const RING: usize = 1 << RING_BITS;
const MASK: u64 = (RING as u64) - 1;
const DISP_STEP: u64 = 250; // one displacement point per millisecond
const DISP_KEEP: usize = 120_000; // two minutes
pub const MAX_COLS: usize = 1200;

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default)]
pub struct View {
    /// Width of the live channel plots, ms.
    pub window_ms: f64,
    pub paused: bool,
    /// When paused, how far back from the pause point the window ends, ms.
    pub pan_ms: f64,
    /// Span of the displacement trace, s.
    pub history_s: f64,
    /// Ask the open page to hold a screen wake lock (for unattended recordings).
    /// Off by default; turn it off afterwards so the display can rest.
    pub keep_awake: bool,
}

impl Default for View {
    fn default() -> Self {
        Self { window_ms: 10.0, paused: false, pan_ms: 0.0, history_s: 4.0, keep_awake: false }
    }
}

#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum SourceKind {
    Sim,
    Serial { port: String },
}

#[derive(Default, Serialize, Clone)]
pub struct LinkStats {
    pub connected: bool,
    pub frames: u64,
    pub crc_errors: u64,
    pub gaps: u64,
    pub dropped_bufs: u32,
    pub sync_lost: u32,
    pub info: String,
    pub error: String,
    pub rate_sps: f64,
}

pub struct Engine {
    pub source: SourceKind,
    /// Simulator parameters; the acquisition thread owns the Simulator itself
    /// and picks up changes by revision, so generation never holds this lock.
    pub sim_p: SimParams,
    pub sim_rev: u64,
    pub det: Detector,
    pub view: View,
    ch1: Vec<u16>,
    ch2: Vec<u16>,
    filt: Vec<f32>,
    pub head: u64,
    paused_head: u64,
    fringes: VecDeque<Fringe>,
    syncs: VecDeque<(u64, u8)>,
    sync_level: u8,
    disp: VecDeque<(f32, f32)>,
    disp_head: u64,
    next_disp_pair: u64,
    truth_now: f64,
    truth_zero: f64,
    have_truth: bool,
    pub rec: Option<Recorder>,
    pub last_rec: Option<RecStatus>,
    pub link: LinkStats,
    planner: FftPlanner<f64>,
    spec_cache: Value,
    spec_at: Instant,
    pub generation: u64,
    rate_t0: Instant,
    rate_p0: u64,
    pub rec_error: Option<String>,
    /// Board v1.2 controls.
    pub map: ControlMap,
    pub simboard: SimBoard,
    /// Simulated time of the board, us (advances with the simulated samples).
    pub board_us: u64,
    sim_cmd_seq: u16,
    pub cmdlink: Arc<CmdLink>,
    /// Latest STATE frame from a real Pico and when it arrived.
    pub pico_state: Option<(BoardState, Instant)>,
    pub isense_pauses: u32,
    /// Main 5.3 V analog rail from ADC2 (Pico STATUS), volts.
    pub rail_v: Option<f64>,
    /// Progress of the tune-for-fringes routine (see tune.rs).
    pub tune: Value,
    /// Test stage (board 1.3.1 J4): the simulated one, and the Pico's last STAGE frame.
    pub simstage: SimStage,
    stage_seq: u16,
    pub pico_stage: Option<(StageState, Instant)>,
    /// 50 Hz trace of the stage position against the counted displacement.
    pub stage_trace: VecDeque<TracePt>,
    next_trace_pair: u64,
    /// (position in pulses, counted nm, truth nm) when the stage last finished homing:
    /// the plot puts the counted trace on the commanded one there.
    pub stage_ref: Option<(f64, f64, f64)>,
    stage_was_homed: bool,
    /// Calibrated scale from Calibrate: {nm_per_pulse, sign, simulated, at}.
    pub stage_cal: Option<Value>,
    pub stage_selftest: Value,
    pub calib: Value,
}

/// Summary of one channel over a window of recent samples, ADC codes.
#[derive(Clone, Debug, Serialize)]
pub struct ChanStats {
    pub n: usize,
    pub mean: f64,
    /// p99 - p1 of the 16-sample average: the fringe swing.
    pub swing: f64,
    /// Robust rms of raw minus the 16-sample average: the broadband noise.
    pub noise: f64,
    pub clip: f64,
    pub min: u16,
    pub max: u16,
}

impl Engine {
    pub fn new(sim: SimParams, det: DetectParams, view: View) -> Self {
        Self {
            source: SourceKind::Sim,
            sim_p: sim,
            sim_rev: 0,
            det: Detector::new(det, FS),
            view,
            ch1: vec![2048; RING],
            ch2: vec![2048; RING],
            filt: vec![2048.0; RING],
            head: 0,
            paused_head: 0,
            fringes: VecDeque::new(),
            syncs: VecDeque::new(),
            sync_level: 0,
            disp: VecDeque::new(),
            disp_head: 0,
            next_disp_pair: DISP_STEP,
            truth_now: 0.0,
            truth_zero: 0.0,
            have_truth: false,
            rec: None,
            last_rec: None,
            link: LinkStats::default(),
            planner: FftPlanner::new(),
            spec_cache: Value::Null,
            spec_at: Instant::now() - Duration::from_secs(10),
            generation: 0,
            rate_t0: Instant::now(),
            rate_p0: 0,
            rec_error: None,
            map: ControlMap::load(),
            simboard: SimBoard::new(0),
            board_us: 0,
            sim_cmd_seq: 0,
            cmdlink: Arc::new(CmdLink::default()),
            pico_state: None,
            isense_pauses: 0,
            rail_v: None,
            tune: json!({"status": "idle"}),
            simstage: SimStage::new(0),
            stage_seq: 0,
            pico_stage: None,
            stage_trace: VecDeque::new(),
            next_trace_pair: 0,
            stage_ref: None,
            stage_was_homed: false,
            stage_cal: None,
            stage_selftest: json!({"status": "idle"}),
            calib: json!({"status": "idle"}),
        }
    }

    /// Run one stage command on the simulated stage (the firmware's stage core).
    pub fn sim_stage_command(&mut self, payload: &[u8]) -> Vec<u8> {
        self.stage_seq = self.stage_seq.wrapping_add(1).max(1);
        let now = self.board_us;
        self.simstage.command(payload, self.stage_seq, now)
    }

    /// The stage's state: simulated, or the Pico's last STAGE frame or ACK (2 s).
    pub fn stage_state(&self) -> Option<StageState> {
        match &self.source {
            SourceKind::Sim => Some(self.simstage.state()),
            SourceKind::Serial { .. } => self.pico_stage.as_ref().filter(|(_, t)| t.elapsed() < Duration::from_secs(2)).map(|(s, _)| s.clone()),
        }
    }

    /// Commanded scale for the plot: Calibrate's counted scale, else nominal.
    pub fn stage_scale(&self) -> f64 {
        self.stage_cal.as_ref().and_then(|c| c["nm_per_pulse"].as_f64()).unwrap_or(NM_PER_PULSE)
    }

    /// Add a point to the stage trace (at most every 20 ms of samples).
    pub fn stage_point(&mut self, st: &StageState) {
        if self.head < self.next_trace_pair {
            return;
        }
        self.next_trace_pair = self.head + 5_000;
        let meas = self.det.displacement_nm();
        let truth = if self.have_truth { self.truth_now - self.truth_zero } else { f64::NAN };
        if st.homed && !self.stage_was_homed {
            self.stage_ref = Some((st.pos as f64, meas, truth));
        }
        self.stage_was_homed = st.homed;
        self.stage_trace.push_back(TracePt { t_s: self.head as f64 / FS, pos: st.pos, moving: st.moving, state: st.state, homed: st.homed, meas_nm: meas, truth_nm: truth });
        while self.stage_trace.len() > 6_000 {
            self.stage_trace.pop_front();
        }
    }

    /// Re-align the counted trace with the commanded position now.
    pub fn stage_align(&mut self) {
        if let Some(st) = self.stage_state() {
            let truth = if self.have_truth { self.truth_now - self.truth_zero } else { f64::NAN };
            self.stage_ref = Some((st.pos as f64, self.det.displacement_nm(), truth));
        }
    }

    /// Stage view for the page: state, the trace (last 30 s, at most 750 points) and results.
    pub fn stage_view(&self) -> Value {
        let st = self.stage_state();
        let scale = self.stage_scale();
        let sign = self.stage_cal.as_ref().and_then(|c| c["sign"].as_f64()).unwrap_or(1.0);
        let t_end = self.head as f64 / FS;
        let pts: Vec<&TracePt> = self.stage_trace.iter().filter(|p| p.t_s >= t_end - 30.0).collect();
        let stride = pts.len().div_ceil(750).max(1);
        let (rp, rm, rt) = self.stage_ref.unwrap_or_else(|| pts.first().map(|p| (p.pos as f64, p.meas_nm, p.truth_nm)).unwrap_or((0.0, 0.0, 0.0)));
        let rc = rp * scale;
        let r1 = |v: f64| (v * 10.0).round() / 10.0;
        let (mut t, mut c, mut m, mut tr): (Vec<f64>, Vec<Value>, Vec<f64>, Vec<Value>) = (vec![], vec![], vec![], vec![]);
        for (k, p) in pts.iter().enumerate() {
            if k % stride != 0 && k + 1 != pts.len() {
                continue;
            }
            t.push(r1((p.t_s - t_end) * 100.0) / 100.0);
            // The position is only valid once homed (homing counts from wherever it started).
            c.push(if p.homed { json!(r1(p.pos as f64 * scale)) } else { Value::Null });
            m.push(r1(rc + sign * (p.meas_nm - rm)));
            tr.push(if p.truth_nm.is_nan() || rt.is_nan() { Value::Null } else { json!(r1(rc + (p.truth_nm - rt))) });
        }
        let sim = matches!(self.source, SourceKind::Sim);
        json!({
            "state": st.as_ref().map(|s| s.view()),
            "simulated": sim,
            "follows_stage": sim && self.sim_p.profile == crate::sim::Profile::Stage,
            "scale_nm_per_pulse": scale, "calibrated": self.stage_cal,
            "trace": {"t": t, "cmd": c, "meas": m, "truth": tr},
            "aligned": self.stage_ref.is_some(),
            "selftest": self.stage_selftest, "calib": self.calib,
        })
    }

    /// Run one command on the simulated board (its firmware core).
    pub fn sim_command(&mut self, payload: &[u8]) -> Vec<u8> {
        self.sim_cmd_seq = self.sim_cmd_seq.wrapping_add(1);
        let now = self.board_us;
        self.simboard.command(payload, self.sim_cmd_seq, now)
    }

    /// The board's control state: the simulated board, or the Pico's last
    /// STATE frame (None if none arrived in the last 2 s).
    pub fn board_state(&self) -> Option<BoardState> {
        match &self.source {
            SourceKind::Sim if self.sim_p.board => Some(self.simboard.state(self.board_us)),
            SourceKind::Sim => None,
            SourceKind::Serial { .. } => self.pico_state.as_ref().filter(|(_, t)| t.elapsed() < Duration::from_secs(2)).map(|(s, _)| s.clone()),
        }
    }

    pub fn board_view(&self) -> Value {
        match self.board_state() {
            Some(st) => {
                let mut v = st.view(&self.map);
                v["source"] = json!(if matches!(self.source, SourceKind::Sim) { "simulated board" } else { "pico" });
                v
            }
            None => json!(null),
        }
    }

    /// Statistics of channel `ch` (1 or 2) over the last `n` pairs.
    pub fn chan_stats(&self, ch: u8, n: usize) -> ChanStats {
        let n = n.min(self.head as usize).min(RING - 1000).max(1);
        let buf = if ch == 2 { &self.ch2 } else { &self.ch1 };
        let start = self.head - n as u64;
        let raw: Vec<u16> = (start..self.head).map(|p| buf[(p & MASK) as usize]).collect();
        let mut sum = 0.0;
        let mut clip = 0usize;
        let (mut mn, mut mx) = (u16::MAX, 0u16);
        for &v in &raw {
            sum += v as f64;
            if v <= 1 || v >= 4094 {
                clip += 1;
            }
            mn = mn.min(v);
            mx = mx.max(v);
        }
        let mean = sum / raw.len() as f64;
        let k = 16usize;
        let mut avg = Vec::with_capacity(raw.len());
        let mut acc = 0.0;
        let mut res = Vec::with_capacity(raw.len());
        for (i, &v) in raw.iter().enumerate() {
            acc += v as f64;
            if i >= k {
                acc -= raw[i - k] as f64;
            }
            if i + 1 >= k {
                let a = acc / k as f64;
                avg.push(a);
                res.push((raw[i + 1 - k / 2] as f64 - a).abs());
            }
        }
        // Median absolute residual x 1.4826 = rms for Gaussian noise, and the
        // sawtooth's sparse sharp edges do not move a median.
        let noise = if res.is_empty() {
            0.0
        } else {
            let m = res.len() / 2;
            res.select_nth_unstable_by(m, |a, b| a.partial_cmp(b).unwrap());
            res[m] * 1.4826
        };
        avg.sort_by(|a, b| a.partial_cmp(b).unwrap());
        let swing = if avg.len() > 10 { avg[avg.len() * 99 / 100] - avg[avg.len() / 100] } else { 0.0 };
        ChanStats { n: raw.len(), mean, swing, noise, clip: clip as f64 / raw.len() as f64, min: mn, max: mx }
    }

    /// Forget all buffered data (used when the source changes).
    pub fn reset_stream(&mut self) {
        self.head = 0;
        self.paused_head = 0;
        self.fringes.clear();
        self.syncs.clear();
        self.disp.clear();
        self.disp_head = 0;
        self.next_disp_pair = DISP_STEP;
        self.det = Detector::new(self.det.p.clone(), FS);
        self.truth_zero = 0.0;
        self.truth_now = 0.0;
        self.link = LinkStats::default();
        self.generation += 1;
        for v in self.ch1.iter_mut().chain(self.ch2.iter_mut()) {
            *v = 2048;
        }
    }

    pub fn zero(&mut self) {
        self.det.zero();
        self.truth_zero = self.truth_now;
        self.disp.clear();
        self.disp_head = 0;
    }

    pub fn set_paused(&mut self, p: bool) {
        if p && !self.view.paused {
            self.paused_head = self.head;
        }
        if !p {
            self.view.pan_ms = 0.0;
        }
        self.view.paused = p;
    }

    /// Feed a contiguous chunk of pairs that starts at absolute pair `first`.
    pub fn ingest(&mut self, first: u64, ch1: &[u16], ch2: &[u16], truth_nm: Option<&[f64]>, sync: &[(u64, u8)]) {
        // A gap (dropped USB buffers) is filled with the last value so pair
        // indices stay aligned with the Pico's clock.
        if first > self.head && self.head > 0 {
            let fill = (first - self.head).min(RING as u64);
            let (l1, l2) = (self.ch1[((self.head - 1) & MASK) as usize], self.ch2[((self.head - 1) & MASK) as usize]);
            for k in 0..fill {
                let i = ((first - fill + k) & MASK) as usize;
                self.ch1[i] = l1;
                self.ch2[i] = l2;
            }
        }
        let level_at_start = self.sync_level;
        for &s in sync {
            self.syncs.push_back(s);
            self.sync_level = s.1;
        }
        let mut new_fr: Vec<(u64, i8)> = vec![];
        let rec_on = self.rec.is_some();
        let mut disp_col: Vec<f32> = if rec_on { Vec::with_capacity(ch1.len()) } else { vec![] };
        let half = self.det.half_wave_nm();
        for i in 0..ch1.len() {
            let p = first + i as u64;
            let idx = (p & MASK) as usize;
            self.ch1[idx] = ch1[i];
            self.ch2[idx] = ch2[i];
            if let Some(f) = self.det.push(ch1[i], p) {
                self.fringes.push_back(f);
                new_fr.push((f.pair, f.dir));
            }
            self.filt[idx] = self.det.filtered_last as f32;
            if let Some(t) = truth_nm {
                self.truth_now = t[i];
                self.have_truth = true;
            }
            if rec_on {
                disp_col.push((self.det.count as f64 * half) as f32);
            }
            if p + 1 >= self.next_disp_pair {
                let truth = if self.have_truth && truth_nm.is_some() { (self.truth_now - self.truth_zero) as f32 } else { f32::NAN };
                self.disp.push_back((self.det.displacement_nm() as f32, truth));
                self.disp_head += 1;
                if self.disp.len() > DISP_KEEP {
                    self.disp.pop_front();
                }
                self.next_disp_pair += DISP_STEP;
            }
        }
        if truth_nm.is_none() {
            self.have_truth = false;
        }
        self.head = first + ch1.len() as u64;
        let oldest = self.head.saturating_sub(RING as u64);
        while self.fringes.front().is_some_and(|f| f.pair < oldest) {
            self.fringes.pop_front();
        }
        while self.syncs.front().is_some_and(|s| s.0 < oldest) {
            self.syncs.pop_front();
        }
        if let Some(r) = self.rec.as_mut() {
            // Truth is recorded relative to the same zero as the counted displacement.
            let tz = self.truth_zero;
            let truth_rel: Option<Vec<f64>> = truth_nm.map(|t| t.iter().map(|v| v - tz).collect());
            if let Err(e) = r.write(first, ch1, ch2, &disp_col, truth_rel.as_deref(), sync, &new_fr, level_at_start) {
                self.rec_error = Some(e.to_string());
            }
            if r.done() {
                let r = self.rec.take().unwrap();
                match r.finish() {
                    Ok(st) => self.last_rec = Some(st),
                    Err(e) => self.rec_error = Some(e),
                }
            }
        }
        let el = self.rate_t0.elapsed().as_secs_f64();
        if el > 1.0 {
            self.link.rate_sps = (self.head.saturating_sub(self.rate_p0)) as f64 * 2.0 / el;
            self.rate_t0 = Instant::now();
            self.rate_p0 = self.head;
        }
    }

    pub fn start_record(&mut self, dir: &std::path::Path, format: Format, seconds: Option<f64>) -> Result<String, String> {
        if self.rec.is_some() {
            return Err("already recording".into());
        }
        let meta = Meta {
            source: match &self.source {
                SourceKind::Sim => format!("simulator {}", serde_json::to_string(&self.sim_p).unwrap_or_default()),
                SourceKind::Serial { port } => format!("pico on {port}"),
            },
            wavelength_nm: self.det.p.wavelength_nm,
            lp_hz: self.det.p.lp_hz,
            threshold: self.det.p.threshold,
        };
        let r = Recorder::start(dir, format, seconds, self.head, meta).map_err(|e| e.to_string())?;
        let p = r.path.display().to_string();
        self.rec = Some(r);
        self.rec_error = None;
        Ok(p)
    }

    pub fn stop_record(&mut self) -> Result<RecStatus, String> {
        let r = self.rec.take().ok_or("not recording")?;
        let st = r.finish()?;
        self.last_rec = Some(st.clone());
        Ok(st)
    }

    fn velocity_um_s(&self, field: usize) -> f64 {
        // Least-squares slope over the last 40 ms of the 1 kHz displacement trace.
        let n = self.disp.len().min(40);
        if n < 5 {
            return 0.0;
        }
        let pts = self.disp.iter().skip(self.disp.len() - n);
        let (mut sx, mut sy, mut sxx, mut sxy) = (0.0, 0.0, 0.0, 0.0);
        for (i, d) in pts.enumerate() {
            let x = i as f64 * 1e-3;
            let y = if field == 0 { d.0 } else { d.1 } as f64;
            if y.is_nan() {
                return f64::NAN;
            }
            sx += x;
            sy += y;
            sxx += x * x;
            sxy += x * y;
        }
        let nf = n as f64;
        let slope = (nf * sxy - sx * sy) / (nf * sxx - sx * sx); // nm/s
        slope / 1000.0
    }

    pub fn readout(&self) -> Value {
        let disp = self.det.displacement_nm();
        let v = self.velocity_um_s(0);
        let half = self.det.half_wave_nm();
        let mut r = json!({
            "disp_nm": disp,
            "disp_um": disp / 1000.0,
            "vel_um_s": v,
            "count": self.det.count,
            "fringe_rate_hz": (v * 1000.0 / half).abs(),
            "dir": self.fringes.back().map(|f| f.dir).unwrap_or(0),
            "half_wave_nm": half,
            "seconds": self.head as f64 / FS,
        });
        if self.have_truth {
            let truth = self.truth_now - self.truth_zero;
            // RMS over the displacement history currently shown.
            let n = ((self.view.history_s * 1000.0) as usize).min(self.disp.len());
            let mut se = 0.0;
            let mut mx: f64 = 0.0;
            for d in self.disp.iter().skip(self.disp.len() - n) {
                let e = (d.0 - d.1) as f64;
                se += e * e;
                mx = mx.max(e.abs());
            }
            r["truth_nm"] = json!(truth);
            r["err_nm"] = json!(disp - truth);
            r["rms_err_nm"] = json!(if n > 0 { (se / n as f64).sqrt() } else { 0.0 });
            r["max_err_nm"] = json!(mx);
            r["truth_vel_um_s"] = json!(self.velocity_um_s(1));
        }
        r
    }

    /// Build one display frame.
    pub fn snapshot(&mut self, want_spec: bool) -> Value {
        let end_head = if self.view.paused { self.paused_head } else { self.head };
        let pan = if self.view.paused { (self.view.pan_ms * 250.0) as u64 } else { 0 };
        let max_w = (RING as u64) - 1000;
        let w = ((self.view.window_ms * 250.0) as u64).clamp(25, max_w);
        let end = end_head.saturating_sub(pan).max(w.min(end_head));
        let oldest = self.head.saturating_sub(max_w);
        let end = end.max(oldest + w).min(self.head);
        let start = end.saturating_sub(w);
        let cols = (w as usize).min(MAX_COLS);
        let mut mn1 = Vec::with_capacity(cols);
        let mut mx1 = Vec::with_capacity(cols);
        let mut mn2 = Vec::with_capacity(cols);
        let mut mx2 = Vec::with_capacity(cols);
        let mut f1 = Vec::with_capacity(cols);
        for c in 0..cols {
            let a = start + (c as u64) * w / cols as u64;
            let b = (start + ((c as u64) + 1) * w / cols as u64).max(a + 1);
            let (mut l1, mut h1, mut l2, mut h2, mut fs) = (u16::MAX, 0u16, u16::MAX, 0u16, 0f32);
            for p in a..b {
                let i = (p & MASK) as usize;
                l1 = l1.min(self.ch1[i]);
                h1 = h1.max(self.ch1[i]);
                l2 = l2.min(self.ch2[i]);
                h2 = h2.max(self.ch2[i]);
                fs += self.filt[i];
            }
            mn1.push(l1);
            mx1.push(h1);
            mn2.push(l2);
            mx2.push(h2);
            f1.push((fs / (b - a) as f32 * 10.0).round() / 10.0);
        }
        let scale = cols as f64 / w as f64;
        let fr: Vec<(f64, i8)> = self
            .fringes
            .iter()
            .filter(|f| f.pair >= start && f.pair < end)
            .map(|f| (((f.pair - start) as f64 * scale * 10.0).round() / 10.0, f.dir))
            .collect();
        let sy: Vec<(f64, u8)> = self
            .syncs
            .iter()
            .filter(|s| s.0 >= start && s.0 < end)
            .map(|s| (((s.0 - start) as f64 * scale * 10.0).round() / 10.0, s.1))
            .collect();
        // Displacement trace, decimated to at most 1000 points.
        let hist_n = ((self.view.history_s * 1000.0) as usize).min(self.disp.len());
        let skip = self.disp.len() - hist_n;
        let stride = hist_n.div_ceil(1000).max(1);
        let mut dm = vec![];
        let mut dt = vec![];
        for (k, d) in self.disp.iter().skip(skip).enumerate() {
            if k % stride == 0 || k + 1 == hist_n {
                dm.push((d.0 * 10.0).round() / 10.0);
                dt.push(if d.1.is_nan() { Value::Null } else { json!((d.1 * 10.0).round() / 10.0) });
            }
        }
        if want_spec || self.spec_at.elapsed() > Duration::from_millis(250) {
            self.spec_at = Instant::now();
            let n = 8192usize;
            if self.head >= n as u64 {
                let s = end - (n as u64).min(end);
                let a: Vec<u16> = (s..s + n as u64).map(|p| self.ch1[(p & MASK) as usize]).collect();
                let b: Vec<u16> = (s..s + n as u64).map(|p| self.ch2[(p & MASK) as usize]).collect();
                let sa = spectrum(&a, 512, &mut self.planner);
                let sb = spectrum(&b, 512, &mut self.planner);
                let lo = 512 * 300 / 125_000; // ignore below 300 Hz
                let (pk, _) = sa.iter().enumerate().skip(lo.max(1)).fold((0, -200.0f32), |acc, (i, &v)| if v > acc.1 { (i, v) } else { acc });
                let round = |v: &Vec<f32>| v.iter().map(|x| (x * 10.0).round() / 10.0).collect::<Vec<f32>>();
                self.spec_cache = json!({
                    "f_max": FS / 2.0, "ch1": round(&sa), "ch2": round(&sb),
                    "peak_hz": (pk as f64 + 0.5) * FS / 2.0 / 512.0,
                });
            }
        }
        let (s1, s2) = (self.chan_stats(1, 12_500), self.chan_stats(2, 12_500));
        json!({
            "head": self.head,
            "start": start,
            "win_ms": w as f64 / 250.0,
            "cols": cols,
            "paused": self.view.paused,
            "ch1": {"mn": mn1, "mx": mx1, "f": f1},
            "ch2": {"mn": mn2, "mx": mx2},
            "fr": fr,
            "sy": sy,
            "disp": {"dt_s": stride as f64 * 1e-3, "meas": dm, "truth": dt, "span_s": hist_n as f64 * 1e-3},
            "spec": self.spec_cache,
            "readout": self.readout(),
            "link": self.link,
            "rec": self.rec.as_ref().map(|r| serde_json::to_value(r.status()).unwrap()),
            "last_rec": self.last_rec.as_ref().map(|r| serde_json::to_value(r).unwrap()),
            "rec_error": self.rec_error,
            "sync_level": self.sync_level,
            "board": self.board_view(),
            "means": [s1.mean.round(), s2.mean.round()],
            "swing": [s1.swing.round(), s2.swing.round()],
            "min_pp_codes": self.det.p.min_pp_codes,
            "tune": self.tune,
            "isense_pauses": self.isense_pauses,
            // The simulated board's rail is ideal; a Pico reports the measured one.
            "stage": self.stage_view(),
            "rail_v": match self.source { SourceKind::Sim => if self.sim_p.board { json!(5.3) } else { Value::Null }, _ => json!(self.rail_v) },
        })
    }
}

/// Run the acquisition loop forever on its own thread.
pub fn run_acquisition(engine: Arc<Mutex<Engine>>) {
    std::thread::Builder::new()
        .name("acquisition".into())
        .spawn(move || {
            let mut serial: Option<(String, mpsc::Receiver<SerialMsg>, Arc<std::sync::atomic::AtomicBool>)> = None;
            let mut gen = u64::MAX;
            let mut t0 = Instant::now();
            let mut sim_pairs: u64 = 0;
            let (p0, mut rev) = {
                let e = engine.lock().unwrap();
                (e.sim_p.clone(), e.sim_rev)
            };
            let mut sim = Simulator::new(p0);
            loop {
                let (kind, g, new_p) = {
                    let e = engine.lock().unwrap();
                    let np = if e.sim_rev != rev { rev = e.sim_rev; Some(e.sim_p.clone()) } else { None };
                    (e.source.clone(), e.generation, np)
                };
                if let Some(p) = new_p {
                    sim.set_params(p);
                }
                if g != gen {
                    gen = g;
                    t0 = Instant::now();
                    sim_pairs = 0;
                    if let Some((_, _, stop)) = serial.take() {
                        stop.store(true, std::sync::atomic::Ordering::SeqCst);
                    }
                    if let SourceKind::Serial { port } = &kind {
                        let link = engine.lock().unwrap().cmdlink.clone();
                        serial = Some(spawn_serial(port.clone(), link));
                    }
                }
                match kind {
                    SourceKind::Sim => {
                        // Generate in real time, in chunks of at most 10 ms, outside the lock.
                        let due = (t0.elapsed().as_secs_f64() * FS) as u64;
                        if due < sim_pairs + 1000 {
                            std::thread::sleep(Duration::from_millis(2));
                            continue;
                        }
                        if due - sim_pairs > 50_000 {
                            // More than 0.2 s behind (slow machine, sleep): run slower than
                            // real time rather than locking everyone out to catch up.
                            t0 = Instant::now();
                            sim_pairs = 0;
                            continue;
                        }
                        let n = ((due - sim_pairs) as usize).min(2_500);
                        // The simulated board advances on the samples' clock (4 us per pair).
                        let (analog, traj) = {
                            let mut e = engine.lock().unwrap();
                            let dt = n as u64 * 4;
                            e.board_us += dt;
                            let now = e.board_us;
                            let traj = e.simstage.advance(now);
                            (if e.sim_p.board { Some(e.simboard.advance(now, dt)) } else { None }, traj)
                        };
                        sim.set_stage(traj.nm, traj.dt_us);
                        let ch = sim.generate_with(n, analog.as_ref());
                        let base = sim.tick / 2 - n as u64;
                        let mut e = engine.lock().unwrap();
                        let first = e.head;
                        let sync: Vec<(u64, u8)> = ch.sync.iter().map(|s| (s.0 - base + first, s.1)).collect();
                        e.ingest(first, &ch.ch1, &ch.ch2, Some(&ch.truth_nm), &sync);
                        e.link.connected = true;
                        let st = e.simstage.state();
                        e.stage_point(&st);
                        drop(e);
                        sim_pairs += n as u64;
                    }
                    SourceKind::Serial { .. } => {
                        let Some((_, rx, _)) = serial.as_ref() else {
                            std::thread::sleep(Duration::from_millis(50));
                            continue;
                        };
                        match rx.recv_timeout(Duration::from_millis(100)) {
                            Ok(SerialMsg::Frames(frames, stats)) => {
                                let mut e = engine.lock().unwrap();
                                e.link.connected = true;
                                e.link.frames = stats.frames;
                                e.link.crc_errors = stats.crc_errors;
                                e.link.gaps = stats.gaps;
                                e.link.error.clear();
                                let mut pending_sync = vec![];
                                for f in frames {
                                    match f {
                                        Frame::Data { first_pair, ch1, ch2, .. } => {
                                            let sync: Vec<(u64, u8)> = std::mem::take(&mut pending_sync);
                                            e.ingest(first_pair, &ch1, &ch2, None, &sync);
                                        }
                                        Frame::Sync { pair, level, .. } => pending_sync.push((pair, level)),
                                        Frame::Status { dropped_bufs, sync_lost, isense_pauses, rail_mv, .. } => {
                                            e.rail_v = rail_mv.map(|m| m as f64 / 1000.0);
                                            e.link.dropped_bufs = dropped_bufs;
                                            e.link.sync_lost = sync_lost;
                                            e.isense_pauses = isense_pauses.unwrap_or(0);
                                        }
                                        Frame::Info { text, .. } => e.link.info = text,
                                        Frame::State { payload, .. } => {
                                            if let Some(st) = BoardState::parse(&payload) {
                                                e.pico_state = Some((st, Instant::now()));
                                            }
                                        }
                                        Frame::Stage { payload, .. } => {
                                            if let Some(st) = StageState::parse(&payload) {
                                                e.stage_point(&st);
                                                e.pico_stage = Some((st, Instant::now()));
                                            }
                                        }
                                        Frame::Ack { .. } | Frame::Cmd { .. } => {}
                                    }
                                }
                                if !pending_sync.is_empty() {
                                    let h = e.head;
                                    e.ingest(h, &[], &[], None, &pending_sync);
                                }
                            }
                            Ok(SerialMsg::Error(msg)) => {
                                let mut e = engine.lock().unwrap();
                                e.link.connected = false;
                                e.link.error = msg;
                            }
                            Err(_) => {}
                        }
                    }
                }
            }
        })
        .expect("spawn acquisition thread");
}

pub enum SerialMsg {
    Frames(Vec<Frame>, crate::proto::DecodeStats),
    Error(String),
}

fn spawn_serial(port: String, link: Arc<CmdLink>) -> (String, mpsc::Receiver<SerialMsg>, Arc<std::sync::atomic::AtomicBool>) {
    let (tx, rx) = mpsc::channel();
    let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
    let stop2 = stop.clone();
    let p2 = port.clone();
    std::thread::spawn(move || {
        while !stop2.load(std::sync::atomic::Ordering::SeqCst) {
            let opened = serialport::new(&p2, 115_200).timeout(Duration::from_millis(10)).open();
            let mut sp = match opened {
                Ok(s) => s,
                Err(e) => {
                    let _ = tx.send(SerialMsg::Error(format!("cannot open {p2}: {e}")));
                    std::thread::sleep(Duration::from_secs(1));
                    continue;
                }
            };
            // DTR starts the stream on the Pico.
            let _ = sp.write_data_terminal_ready(true);
            let _ = sp.write_all(b"start\n");
            let (ctx, crx) = mpsc::channel::<Vec<u8>>();
            *link.tx.lock().unwrap() = Some(ctx);
            let mut dec = Decoder::default();
            let mut buf = vec![0u8; 65536];
            let mut frames = vec![];
            let mut last_send = Instant::now();
            loop {
                if stop2.load(std::sync::atomic::Ordering::SeqCst) {
                    *link.tx.lock().unwrap() = None;
                    let _ = sp.write_data_terminal_ready(false);
                    return;
                }
                while let Ok(f) = crx.try_recv() {
                    if let Err(e) = sp.write_all(&f) {
                        let _ = tx.send(SerialMsg::Error(format!("write error on {p2}: {e}")));
                    }
                }
                match sp.read(&mut buf) {
                    Ok(0) => {}
                    Ok(n) => {
                        dec.push(&buf[..n], &mut frames);
                        // ACKs go straight to whoever is waiting for them.
                        frames.retain_mut(|f| match f {
                            Frame::Ack { payload, .. } => {
                                link.deliver(std::mem::take(payload));
                                false
                            }
                            _ => true,
                        });
                    }
                    Err(e) if e.kind() == std::io::ErrorKind::TimedOut => {}
                    Err(e) => {
                        *link.tx.lock().unwrap() = None;
                        let _ = tx.send(SerialMsg::Error(format!("read error on {p2}: {e}")));
                        break;
                    }
                }
                if !frames.is_empty() && last_send.elapsed() > Duration::from_millis(4) {
                    let _ = tx.send(SerialMsg::Frames(std::mem::take(&mut frames), dec.stats.clone()));
                    last_send = Instant::now();
                }
            }
            std::thread::sleep(Duration::from_millis(500));
        }
    });
    (port, rx, stop)
}

use std::io::Write as _;