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
// SPDX-License-Identifier: MIT
//! Board operations shared by the page, the CLI and the tuner: send a command
//! (simulated board or Pico), auto-centre a channel, and tune for fringes.

use crate::controls::{self, Ack, ControlMap};
use crate::engine::{ChanStats, SourceKind};
use crate::server::App;
use serde_json::{json, Value};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};

pub static TUNE_CANCEL: AtomicBool = AtomicBool::new(false);
pub static TUNE_RUNNING: AtomicBool = AtomicBool::new(false);
const MID: f64 = 2048.0;
const LSB: f64 = 3.3 / 4096.0;

pub type Fail = (String, Vec<String>);

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

/// Send one command payload to whichever board is the source.
pub async fn cmd(a: &Arc<App>, payload: Vec<u8>) -> Result<Ack, Fail> {
    let (sim, board, link) = {
        let e = a.engine.lock().unwrap();
        (matches!(e.source, SourceKind::Sim), e.sim_p.board, e.cmdlink.clone())
    };
    if sim {
        if !board {
            return Err(fail("the simulator is modelling the v1.1 board, which has no software controls", &["Turn the board 1.3 model on: `smi-dash sim --board on`"]));
        }
        let r = a.engine.lock().unwrap().sim_command(&payload);
        return Ack::parse(&r).ok_or_else(|| fail("malformed ACK from the simulated board", &[]));
    }
    let op = payload.first().copied().unwrap_or(0);
    let refresh = !matches!(op, controls::OP_HEARTBEAT | controls::OP_GET_STATE | controls::OP_READ_ISENSE);
    let link2 = link.clone();
    match tokio::task::spawn_blocking(move || link.call(&payload)).await {
        Ok(Ok(ack)) => {
            // The Pico pushes STATE four times a second; after a change, fetch it
            // now so the next reader (a --wait loop, the page) sees the change.
            if refresh {
                if let Ok(Ok(st)) = tokio::task::spawn_blocking(move || link2.call(&[controls::OP_GET_STATE])).await {
                    if let Some(bs) = controls::BoardState::parse(&st.data) {
                        a.engine.lock().unwrap().pico_state = Some((bs, Instant::now()));
                    }
                }
            }
            Ok(ack)
        }
        Ok(Err(m)) => Err((m, vec!["Check the link with `smi-dash status`; the Pico must run firmware 1.3.1 (`smi-dash board map`)".into()])),
        Err(e) => Err(fail(format!("command task failed: {e}"), &[])),
    }
}

/// Explain a refused ACK in terms of the control.
pub fn refusal(ack: &Ack, c: Option<&controls::Control>) -> Fail {
    let mut m = controls::status_text(ack.status).to_string();
    let mut h = vec![];
    if let (Some((lo, hi)), Some(c)) = (ack.range(), c) {
        m = format!("{} ({}) out of range", c.label, c.unit);
        if c.kind == "switch" {
            h.push(format!("{} takes one of: {}", c.id, c.settings.iter().map(|s| format!("{} ({})", s.value, s.label)).collect::<Vec<_>>().join(", ")));
        } else {
            h.push(format!("{} accepts {lo:.4} to {hi:.4} {}", c.id, c.unit));
        }
        if c.role == "laser" {
            h.push(format!("The firmware limit is the lower of the DAC's top ({:.2} mA) and the rated {:.0} mA", c.max, c.rated.unwrap_or(c.max)));
        }
    }
    match ack.status {
        5 => h.push("Turn the laser on with `smi-dash laser on --beam-safe` (the page needs the interlock box ticked)".into()),
        6 => h.push("Read the fault in `smi-dash board`, fix the cause, then `smi-dash board clear-fault`".into()),
        9 => h.push("The firmware checks the current readback at zero with the laser off first; try again in a second".into()),
        10 => {
            if let Some(c) = c {
                h.push(format!("Turn the laser off (`smi-dash laser off`), change {}, then turn it on again. Board note: {}", c.id, c.safety.clone().unwrap_or_default()));
            }
        }
        _ => {}
    }
    (m, h)
}

/// Resolve a control from an id or a short alias (ch1-tia, ch2-amp, ch1-offset, bias, laser).
pub fn resolve(map: &ControlMap, key: &str) -> Option<usize> {
    if let Some(i) = map.index(key) {
        return Some(i);
    }
    let k = key.to_ascii_lowercase();
    let ch = if k.contains("ch1") || k.contains("monitor") { Some(1) } else if k.contains("ch2") || k.contains("external") { Some(2) } else { None };
    if k.contains("offset") {
        return map.find("offset", ch, None);
    }
    if k.contains("tia") {
        return map.find("gain", ch, Some("tia"));
    }
    if k.contains("amp") || k.contains("stage") {
        return map.find("gain", ch, Some("amp"));
    }
    if k.contains("bias") {
        return map.find("bias", None, None);
    }
    if k.contains("laser") || k.contains("current") {
        return Some(map.laser());
    }
    None
}

/// Set control `idx`. mode 0 = units, 1 = DAC counts, 2 = setting index.
pub async fn set(a: &Arc<App>, idx: usize, mode: u8, v: f64) -> Result<Ack, Fail> {
    let c = a.engine.lock().unwrap().map.controls.get(idx).cloned();
    let Some(c) = c else { return Err(fail(format!("no control {idx}"), &["List them with `smi-dash board map`"])) };
    let ack = cmd(a, controls::cmd_set(idx, mode, v as f32)).await?;
    if !ack.ok() {
        return Err(refusal(&ack, Some(&c)));
    }
    Ok(ack)
}

/// Set a control the board says to change only with the laser off. If the
/// laser is on, this turns it off, writes, and turns it back on at the same
/// set-point, then waits for the head's soft-start (board 1.2.1 contract: no
/// writes while armed). It never turns on a laser that was off.
pub async fn set_disarmed(a: &Arc<App>, idx: usize, mode: u8, v: f64) -> Result<Ack, Fail> {
    let (needs_off, on) = {
        let e = a.engine.lock().unwrap();
        (e.map.controls.get(idx).is_some_and(|c| c.requires_laser_off), e.board_state().is_some_and(|s| s.laser_on))
    };
    if !(needs_off && on) {
        return set(a, idx, mode, v).await;
    }
    laser(a, false).await?;
    let r = set(a, idx, mode, v).await;
    laser(a, true).await?;
    wait_settled(a).await?;
    r
}

/// Is the laser on a gated head DAC (written in one step, soft-start on the head)?
pub fn gated(a: &Arc<App>) -> bool {
    let e = a.engine.lock().unwrap();
    let c = &e.map.controls[e.map.laser()];
    c.min_write_ms.unwrap_or(0) > 0 && c.ramp_per_s.unwrap_or(0.0) == 0.0
}

/// Wait for the set-point to be written and, with the laser on, for the
/// measured current to arrive near it (the head's soft-start).
pub async fn wait_settled(a: &Arc<App>) -> Result<(), Fail> {
    wait_ramp(a).await?;
    let t = Instant::now();
    let mut near = 0;
    loop {
        let st = a.engine.lock().unwrap().board_state();
        let Some(s) = st else { return Ok(()) };
        if !s.laser_on || s.laser_now_ma < 0.5 {
            return Ok(());
        }
        let tol = (0.03 * s.laser_now_ma).max(1.0);
        if s.isense_valid && (s.isense_ma - s.laser_now_ma).abs() < tol {
            near += 1;
            if near >= 3 {
                return Ok(());
            }
        } else {
            near = 0;
        }
        if t.elapsed() > Duration::from_secs(2) {
            return Ok(()); // the reading says what it says; the caller scores what is there
        }
        tokio::time::sleep(Duration::from_millis(25)).await;
    }
}

pub async fn laser(a: &Arc<App>, on: bool) -> Result<Ack, Fail> {
    let ack = cmd(a, controls::cmd_laser(on)).await?;
    if !ack.ok() {
        return Err(refusal(&ack, None));
    }
    Ok(ack)
}

fn head(a: &Arc<App>) -> u64 {
    a.engine.lock().unwrap().head
}

/// Wait until `pairs` new sample pairs have arrived after now.
async fn fresh(a: &Arc<App>, pairs: u64) -> Result<(), Fail> {
    let h0 = head(a);
    let t = Instant::now();
    while head(a) < h0 + pairs {
        if t.elapsed() > Duration::from_secs(3) {
            return Err(fail("no new samples are arriving", &["Check the source with `smi-dash status`"]));
        }
        tokio::time::sleep(Duration::from_millis(4)).await;
    }
    Ok(())
}

/// Wait for the laser set-point to finish ramping.
pub async fn wait_ramp(a: &Arc<App>) -> Result<(), Fail> {
    let t = Instant::now();
    loop {
        let st = a.engine.lock().unwrap().board_state();
        match st {
            Some(s) if !s.laser_on => return Ok(()),
            // The core clears "ramping" once the set-point is written (a gated DAC
            // lands on the nearest code, which can differ from the target by
            // half a count) or a stepped ramp has arrived.
            Some(s) if !s.ramping => return Ok(()),
            None => return Err(fail("no board state", &["Is the Pico running firmware 1.3.1?"])),
            _ => {}
        }
        if t.elapsed() > Duration::from_secs(15) {
            return Err(fail("the laser set-point did not settle within 15 s", &[]));
        }
        tokio::time::sleep(Duration::from_millis(20)).await;
    }
}

fn stats(a: &Arc<App>, ch: u8, n: usize) -> ChanStats {
    a.engine.lock().unwrap().chan_stats(ch, n)
}

/// Servo channel `ch`'s mean to mid-scale with its offset DAC.
pub async fn auto_centre(a: &Arc<App>, ch: u8) -> Result<Value, Fail> {
    let (oi, c, k) = {
        let e = a.engine.lock().unwrap();
        let Some(oi) = e.map.find("offset", Some(ch), None) else { return Err(fail(format!("no offset control for channel {ch}"), &[])) };
        let c = e.map.controls[oi].clone();
        // Board map: Vstage = (1 + K) Voffset - K Vbuffer, so the ADC moves (1 + |K|) per offset volt.
        let k = c.gain_link.as_ref().and_then(|g| e.map.index(g)).and_then(|gi| e.board_state().and_then(|s| s.targets.get(gi).copied())).map(|kv| 1.0 + (kv as f64).abs()).or(c.adc_V_per_unit).unwrap_or(2.0);
        (oi, c, k)
    };
    let mut slope = k;
    let mut cur = a.engine.lock().unwrap().board_state().and_then(|s| s.targets.get(oi).copied()).unwrap_or(c.default as f32) as f64;
    let mut prev: Option<(f64, f64)> = None;
    let mut steps = vec![];
    for it in 0..10 {
        fresh(a, 2500).await?;
        let st = stats(a, ch, 2500);
        let err = st.mean - MID;
        steps.push(json!({"offset_V": cur, "mean": st.mean, "clip": st.clip}));
        if err.abs() < 12.0 && st.clip < 0.002 {
            return Ok(json!({"channel": ch, "offset_V": cur, "mean": st.mean, "iterations": it, "slope_V_per_V": slope, "steps": steps}));
        }
        if let Some((po, pm)) = prev {
            let d = cur - po;
            // Secant update when both points were off the rails.
            if d.abs() > 1e-4 && st.clip < 0.05 && (pm - MID).abs() < 2000.0 {
                let s = (st.mean - pm) * LSB / d;
                if s > 0.3 * k && s < 3.0 * k {
                    slope = s;
                }
            }
        }
        prev = Some((cur, st.mean));
        let want = (cur - err * LSB / slope).clamp(c.min, c.max);
        if (want - cur).abs() < c.per_code.unwrap_or(1e-3) * 0.5 {
            return Err(fail(
                format!("cannot centre channel {ch}: the offset DAC is at {:.3} V, its limit, and the mean is still {:.0} codes from mid-scale", cur, err),
                &["Lower the second-stage gain, or choose a monitor bias that keeps the stage inside the ADC rails (with the laser off)"],
            ));
        }
        set_disarmed(a, oi, 0, want).await?;
        cur = want;
    }
    let st = stats(a, ch, 2500);
    Ok(json!({"channel": ch, "offset_V": cur, "mean": st.mean, "iterations": 10, "converged": false, "steps": steps}))
}

/// Fringe score of channel `ch` over the last `n` pairs: fringe swing over the
/// broadband noise, penalised for clipping.
pub fn score(s: &ChanStats) -> f64 {
    let pen = (1.0 - 20.0 * s.clip).max(0.0);
    s.swing / s.noise.max(0.5) * pen
}

fn progress(a: &Arc<App>, v: Value) {
    a.engine.lock().unwrap().tune = v.clone();
    a.broadcast("tune", v);
}

#[derive(Clone, Debug, serde::Deserialize)]
#[serde(default)]
pub struct TuneParams {
    pub channel: u8,
    pub min_ma: Option<f64>,
    pub max_ma: Option<f64>,
    pub steps: usize,
    /// Current dither while scoring, so a still target still makes fringes
    /// (current tuning moves the wavelength), mA peak.
    pub dither_ma: f64,
    pub measure_s: f64,
    /// Also try the second-stage gains.
    pub gains: bool,
}

impl Default for TuneParams {
    fn default() -> Self {
        Self { channel: 1, min_ma: None, max_ma: None, steps: 8, dither_ma: 0.5, measure_s: 0.4, gains: true }
    }
}

async fn measure(a: &Arc<App>, li: usize, base: f64, p: &TuneParams, ch: u8) -> Result<(ChanStats, i64), Fail> {
    let n = (p.measure_s * 250_000.0) as usize;
    let c0 = a.engine.lock().unwrap().det.count;
    let h0 = head(a);
    let lim = a.engine.lock().unwrap().map.controls[li].limit();
    let mut up = true;
    // A gated head DAC cannot be dithered: every write disarms the laser and
    // restarts its soft-start. There the score needs a moving target.
    let dither = if gated(a) { 0.0 } else { p.dither_ma };
    while head(a) < h0 + n as u64 {
        if TUNE_CANCEL.load(Ordering::SeqCst) {
            return Err(fail("tuning stopped", &[]));
        }
        if dither > 0.0 {
            let t = if up { base + dither } else { base - dither };
            set(a, li, 0, t.clamp(0.0, lim)).await?;
        }
        up = !up;
        tokio::time::sleep(Duration::from_millis(60)).await;
    }
    if dither > 0.0 {
        set(a, li, 0, base).await?;
    }
    let st = stats(a, ch, n);
    let fr = a.engine.lock().unwrap().det.count - c0;
    Ok((st, fr))
}

/// Step the laser current, re-centre, score the fringes, then try the second-stage gains.
pub async fn tune(a: Arc<App>, p: TuneParams) -> Result<Value, Fail> {
    let (li, lim, map) = {
        let e = a.engine.lock().unwrap();
        let li = e.map.laser();
        (li, e.map.controls[li].limit(), e.map.clone())
    };
    let st = a.engine.lock().unwrap().board_state().ok_or_else(|| fail("no board state", &[]))?;
    if !st.laser_on {
        return Err(fail("the laser is off; tuning never turns it on by itself", &["Turn it on first: `smi-dash laser on --beam-safe`, then `smi-dash tune`"]));
    }
    let ch = p.channel.clamp(1, 2);
    let start_ma = st.laser_target_ma as f64;
    let lo = p.min_ma.unwrap_or(lim * 0.4).clamp(0.0, lim);
    let hi = p.max_ma.unwrap_or(lim).clamp(lo, lim);
    let t0 = Instant::now();
    let mut log: Vec<Value> = vec![];
    let mut best: Option<(f64, f64)> = None; // (score, mA)
    let coarse: Vec<f64> = (0..p.steps.max(2)).map(|k| lo + (hi - lo) * k as f64 / (p.steps.max(2) - 1) as f64).collect();
    for ma in coarse {
        let s = step(&a, li, ma, &p, ch, "current", &mut log, t0).await?;
        if best.is_none_or(|b| s > b.0) {
            best = Some((s, ma));
        }
    }
    let (_, b) = best.unwrap();
    let span = (hi - lo) / (p.steps.max(2) - 1) as f64;
    let fine: Vec<f64> = (-2..=2).map(|k| b + k as f64 * span / 4.0).filter(|m| *m >= lo && *m <= hi && (*m - b).abs() > 1e-6).collect();
    for ma in fine {
        let s = step(&a, li, ma, &p, ch, "fine", &mut log, t0).await?;
        if s > best.unwrap().0 {
            best = Some((s, ma));
        }
    }
    let (bs, bma) = best.unwrap();
    let mut gain_choice = Value::Null;
    if p.gains {
        if let Some(gi) = map.find("gain", Some(ch), Some("amp")) {
            let g = &map.controls[gi];
            let mut gbest: Option<(f64, f64)> = None;
            for s in &g.settings {
                if TUNE_CANCEL.load(Ordering::SeqCst) {
                    return Err(fail("tuning stopped", &[]));
                }
                set_disarmed(&a, gi, 0, s.value).await?;
                let sc = step(&a, li, bma, &p, ch, "gain", &mut log, t0).await?;
                log.last_mut().unwrap()["gain"] = json!(s.value);
                if gbest.is_none_or(|b| sc > b.0) {
                    gbest = Some((sc, s.value));
                }
            }
            let (_, gv) = gbest.unwrap();
            set_disarmed(&a, gi, 0, gv).await?;
            gain_choice = json!({"id": g.id, "value": gv, "label": g.setting_label(gv)});
        }
    }
    // Final: best current, centred, scored once more.
    let fs = step(&a, li, bma, &p, ch, "final", &mut log, t0).await?;
    // Leave both channels centred for the gains now in place.
    for c2 in [1u8, 2] {
        let _ = auto_centre(&a, c2).await;
    }
    let fringes: i64 = log.iter().map(|r| r["fringes"].as_i64().unwrap_or(0).abs()).sum();
    // Nothing to score: put the current back where it was rather than keep a
    // "best" chosen from noise.
    let bma = if fringes == 0 {
        set(&a, li, 0, start_ma).await?;
        wait_settled(&a).await?;
        for c2 in [1u8, 2] {
            let _ = auto_centre(&a, c2).await;
        }
        start_ma
    } else {
        bma
    };
    let note = if fringes == 0 {
        Value::String(if gated(&a) {
            "No fringes were seen. On this board the laser current cannot be dithered (every write restarts the head's soft-start), so move the target while tuning.".into()
        } else {
            "No fringes were seen; check the alignment and the target.".into()
        })
    } else {
        Value::Null
    };
    let result = json!({
        "note": note,
        "status": "done", "channel": ch, "best_mA": bma, "best_score_sweep": bs, "final_score": fs,
        "gain": gain_choice, "seconds": t0.elapsed().as_secs_f64(), "steps": log,
    });
    progress(&a, result.clone());
    Ok(result)
}

#[allow(clippy::too_many_arguments)]
async fn step(a: &Arc<App>, li: usize, ma: f64, p: &TuneParams, ch: u8, phase: &str, log: &mut Vec<Value>, t0: Instant) -> Result<f64, Fail> {
    if TUNE_CANCEL.load(Ordering::SeqCst) {
        return Err(fail("tuning stopped", &[]));
    }
    set(a, li, 0, ma).await?;
    wait_settled(a).await?;
    let centred = auto_centre(a, ch).await;
    let (st, fr) = measure(a, li, ma, p, ch).await?;
    let sc = score(&st);
    let meas = a.engine.lock().unwrap().board_state().map(|s| s.isense_ma).unwrap_or(f32::NAN);
    let row = json!({
        "phase": phase, "set_mA": ma, "measured_mA": meas, "score": (sc * 10.0).round() / 10.0,
        "swing": st.swing.round(), "noise": (st.noise * 100.0).round() / 100.0, "clip": st.clip, "fringes": fr,
        "centred": centred.is_ok(), "t_s": t0.elapsed().as_secs_f64(),
    });
    log.push(row.clone());
    progress(a, json!({"status": "running", "phase": phase, "step": log.len(), "last": row, "steps": log}));
    Ok(sc)
}

/// Start the tuner in the background (one at a time).
pub fn spawn_tune(a: Arc<App>, p: TuneParams) -> Result<(), Fail> {
    if TUNE_RUNNING.swap(true, Ordering::SeqCst) {
        return Err(fail("a tune is already running", &["Watch it with `smi-dash tune --status`, stop it with `smi-dash tune --stop`"]));
    }
    TUNE_CANCEL.store(false, Ordering::SeqCst);
    progress(&a, json!({"status": "running", "phase": "start", "step": 0, "steps": []}));
    tokio::spawn(async move {
        let r = tune(a.clone(), p).await;
        if let Err((m, h)) = r {
            let prev = a.engine.lock().unwrap().tune.clone();
            progress(&a, json!({"status": "failed", "error": m, "hints": h, "steps": prev["steps"]}));
            a.broadcast("toast", json!({"text": format!("Tuning: {m}"), "kind": "error"}));
        } else {
            a.broadcast("toast", json!({"text": "Tuning finished", "kind": "success"}));
        }
        TUNE_RUNNING.store(false, Ordering::SeqCst);
    });
    Ok(())
}