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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
// SPDX-License-Identifier: MIT
//! Board v1.2 controls: the control map (shared with the firmware through
//! controls/gen_controls.py), the command protocol (firmware/src/smi_ctl.h),
//! and the simulated board, which runs the firmware's own control core over FFI
//! and models the laser driver, the current sense, the DAC and the switches.

#![allow(non_snake_case)] // field names follow the board map (mA_per_code, full_scale_V)

use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::os::raw::c_void;

pub const MAP_JSON: &str = include_str!("../assets/controls.json");

#[allow(dead_code)] // protocol constant, used by other hosts
pub const OP_GET_STATE: u8 = 0x01;
pub const OP_LASER_ENABLE: u8 = 0x02;
pub const OP_SET: u8 = 0x03;
pub const OP_READ_ISENSE: u8 = 0x04;
pub const OP_HEARTBEAT: u8 = 0x05;
pub const OP_CLEAR_FAULT: u8 = 0x06;
#[allow(dead_code)]
pub const OP_GET_MAP: u8 = 0x07;
pub const OP_CONFIG: u8 = 0x08;
pub const LASER_KEY: u32 = 0x4C41_5345;

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Setting {
    pub label: String,
    pub value: f64,
    pub code: u32,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Control {
    pub id: String,
    pub label: String,
    pub kind: String,
    pub unit: String,
    pub role: String,
    #[serde(default)]
    pub channel: Option<u8>,
    #[serde(default)]
    pub stage: Option<String>,
    #[serde(default)]
    pub adc_V_per_unit: Option<f64>,
    /// Offsets: the gain switch whose |K| sets the offset's gain, 1 + |K| (board v1.2).
    #[serde(default)]
    pub gain_link: Option<String>,
    #[serde(default)]
    pub hw_cutoff_mA: Option<f64>,
    #[serde(default)]
    pub requires_laser_off: bool,
    /// Laser on the head DAC: the ramp writes at most this often (each write
    /// drops the enable carrier for its write-and-readback).
    #[serde(default)]
    pub min_write_ms: Option<u32>,
    /// Command-code guard band (1.2.1: DAC code = max(command - guard, 0)) and the top DAC code.
    #[serde(default)]
    pub guard: Option<u32>,
    #[serde(default)]
    pub max_code: Option<u32>,
    #[serde(default)]
    pub safety: Option<String>,
    pub min: f64,
    pub max: f64,
    pub default: f64,
    #[serde(default)]
    pub dac: Option<u8>,
    #[serde(default)]
    pub ch: Option<u8>,
    #[serde(default)]
    pub bits: Option<u32>,
    #[serde(default)]
    pub per_code: Option<f64>,
    #[serde(default)]
    pub at_zero: Option<f64>,
    #[serde(default)]
    pub ramp_per_s: Option<f64>,
    #[serde(default)]
    pub rated: Option<f64>,
    #[serde(default)]
    pub gpios: Vec<u8>,
    #[serde(default)]
    pub settings: Vec<Setting>,
}

impl Control {
    pub fn value_of(&self, code: u32) -> f64 {
        self.at_zero.unwrap_or(0.0) + code as f64 * self.per_code.unwrap_or(1.0)
    }
    pub fn limit(&self) -> f64 {
        self.rated.map(|r| r.min(self.max)).unwrap_or(self.max)
    }
    pub fn setting_label(&self, v: f64) -> Option<String> {
        self.settings.iter().find(|s| (s.value - v).abs() <= s.value.abs() * 1e-3).map(|s| s.label.clone())
    }
}

/// Laser current readback: an ADS1115 on the laser head across the 2 ohm shunt.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Isense {
    pub device: String,
    pub i2c_addr: u8,
    /// ADS1115 input multiplexer code (0 = AIN0 - AIN1 differential).
    pub mux: u8,
    #[serde(default)]
    pub input: String,
    pub full_scale_V: f64,
    pub data_rate_sps: u32,
    pub mA_per_code: f64,
    pub offset_mA: f64,
    pub trip_mA: f64,
    pub rate_hz: u32,
    #[serde(default)]
    pub zero_calibrated: bool,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ControlMap {
    pub map_version: String,
    pub controls: Vec<Control>,
    pub isense: Isense,
    pub laser_enable: Value,
    pub i2c: Value,
    pub dacs: Value,
    #[serde(default)]
    pub expander: Option<Value>,
    /// Head DAC readback polling and write gating (board decision 8).
    #[serde(default)]
    pub laser_watch: Option<Value>,
    /// Main-board analog rail on ADC2 (GPIO28).
    #[serde(default)]
    pub rail: Option<Value>,
}

pub fn fnv1a(b: &[u8]) -> u32 {
    let mut h: u32 = 0x811C_9DC5;
    for &x in b {
        h ^= x as u32;
        h = h.wrapping_mul(0x0100_0193);
    }
    h
}

impl ControlMap {
    pub fn load() -> Self {
        serde_json::from_str(MAP_JSON).expect("assets/controls.json is generated by gen_controls.py")
    }
    pub fn hash() -> u32 {
        fnv1a(MAP_JSON.as_bytes())
    }
    pub fn index(&self, id: &str) -> Option<usize> {
        self.controls.iter().position(|c| c.id == id)
    }
    pub fn laser(&self) -> usize {
        self.controls.iter().position(|c| c.role == "laser").unwrap_or(0)
    }
    /// The control with this role on this channel (offset ch1, gain stage amp on ch2, ...).
    pub fn find(&self, role: &str, channel: Option<u8>, stage: Option<&str>) -> Option<usize> {
        self.controls.iter().position(|c| c.role == role && (channel.is_none() || c.channel == channel) && (stage.is_none() || c.stage.as_deref() == stage))
    }
}

// ------------------------------------------------------------------ protocol --

pub fn status_text(s: u8) -> &'static str {
    match s {
        0 => "ok",
        1 => "command too short",
        2 => "unknown command",
        3 => "no such control",
        4 => "value out of range",
        5 => "laser interlock key missing",
        6 => "a fault is latched; clear it first",
        7 => "the DAC did not respond",
        8 => "that unit does not apply to this control",
        9 => "current readback not yet validated at zero; wait a second with the laser off",
        10 => "the board map says change this only with the laser off",
        _ => "unknown status",
    }
}

pub fn off_reason_text(r: u8) -> &'static str {
    match r {
        0 => "on",
        1 => "off since power-up",
        2 => "turned off by the host",
        3 => "off: USB disconnected or port closed",
        4 => "off: watchdog reset",
        5 => "off: host heartbeat timed out",
        6 => "off: overcurrent trip",
        7 => "off: DAC write failed",
        _ => "off",
    }
}

pub fn fault_text(f: u8) -> &'static str {
    match f {
        0 => "none",
        1 => "overcurrent",
        2 => "DAC not responding",
        3 => "current flowing with the laser disabled",
        4 => "laser current readback (head ADS1115) not answering",
        5 => "laser DAC readback mismatch (head DAC121C085)",
        _ => "unknown",
    }
}

fn f32le(b: &[u8]) -> f32 {
    f32::from_le_bytes([b[0], b[1], b[2], b[3]])
}
fn u16le(b: &[u8]) -> u16 {
    u16::from_le_bytes([b[0], b[1]])
}
fn u32le(b: &[u8]) -> u32 {
    u32::from_le_bytes([b[0], b[1], b[2], b[3]])
}

pub fn cmd_laser(on: bool) -> Vec<u8> {
    let mut p = vec![OP_LASER_ENABLE, on as u8];
    p.extend_from_slice(&(if on { LASER_KEY } else { 0 }).to_le_bytes());
    p
}
/// mode 0 = physical units, 1 = DAC counts, 2 = setting index.
pub fn cmd_set(idx: usize, mode: u8, v: f32) -> Vec<u8> {
    let mut p = vec![OP_SET, idx as u8, mode];
    p.extend_from_slice(&v.to_le_bytes());
    p
}
pub fn cmd_config(isense_hz: u8, hb_ms: u16) -> Vec<u8> {
    let mut p = vec![OP_CONFIG, isense_hz];
    p.extend_from_slice(&hb_ms.to_le_bytes());
    p
}

/// Frame a host-to-Pico command (same frame as the stream, type CMD).
pub fn frame_cmd(seq: u16, payload: &[u8]) -> Vec<u8> {
    let mut f = vec![0xA5, 0x5A, 0x10, 0];
    f.extend_from_slice(&(payload.len() as u16).to_le_bytes());
    f.extend_from_slice(&seq.to_le_bytes());
    f.extend_from_slice(payload);
    let crc = crate::proto::crc16(&f[2..]);
    f.extend_from_slice(&crc.to_le_bytes());
    f
}

#[derive(Clone, Debug, Serialize)]
pub struct Ack {
    pub cmd_seq: u16,
    pub op: u8,
    pub status: u8,
    pub data: Vec<u8>,
}

impl Ack {
    pub fn parse(p: &[u8]) -> Option<Ack> {
        if p.len() < 4 {
            return None;
        }
        Some(Ack { cmd_seq: u16le(p), op: p[2], status: p[3], data: p[4..].to_vec() })
    }
    pub fn ok(&self) -> bool {
        self.status == 0
    }
    /// For SMI_E_RANGE: the allowed min and max.
    pub fn range(&self) -> Option<(f32, f32)> {
        (self.status == 4 && self.data.len() >= 8).then(|| (f32le(&self.data), f32le(&self.data[4..])))
    }
}

#[derive(Clone, Debug, Serialize, Default)]
pub struct BoardState {
    pub map_hash: u32,
    pub laser_on: bool,
    pub ramping: bool,
    pub fault: u8,
    pub isense_valid: bool,
    pub track_warn: bool,
    pub boot_reason: u8,
    pub off_reason: u8,
    pub laser_target_ma: f32,
    pub laser_now_ma: f32,
    pub isense_ma: f32,
    pub isense_raw: i16,
    pub isense_age_ms: u16,
    pub hb_timeout_ms: u16,
    pub isense_hz: u8,
    pub codes: Vec<u16>,
    pub targets: Vec<f32>,
    /// Calibrated zero code of the current sense (None until calibrated).
    pub zero_code: Option<f32>,
}

impl BoardState {
    pub fn parse(p: &[u8]) -> Option<BoardState> {
        if p.len() < 28 {
            return None;
        }
        let n = p[27] as usize;
        if p.len() < 28 + 6 * n {
            return None;
        }
        let f = p[4];
        let mut s = BoardState {
            map_hash: u32le(p),
            laser_on: f & 1 != 0,
            ramping: f & 2 != 0,
            fault: p[5],
            isense_valid: f & 8 != 0,
            track_warn: f & 16 != 0,
            boot_reason: p[6],
            off_reason: p[7],
            laser_target_ma: f32le(&p[8..]),
            laser_now_ma: f32le(&p[12..]),
            isense_ma: f32le(&p[16..]),
            isense_raw: u16le(&p[20..]) as i16,
            isense_age_ms: u16le(&p[22..]),
            hb_timeout_ms: u16le(&p[24..]),
            isense_hz: p[26],
            codes: vec![],
            targets: vec![],
            zero_code: None,
        };
        for i in 0..n {
            let o = 28 + 6 * i;
            s.codes.push(u16le(&p[o..]));
            s.targets.push(f32le(&p[o + 2..]));
        }
        let z = 28 + 6 * n;
        if p.len() >= z + 2 {
            let v = u16le(&p[z..]) as i16;
            s.zero_code = (v != i16::MIN).then(|| v as f32 / 16.0);
        }
        Some(s)
    }

    /// A readable view, joined with the map.
    pub fn view(&self, map: &ControlMap) -> Value {
        let ctrls: Vec<Value> = map
            .controls
            .iter()
            .enumerate()
            .map(|(i, c)| {
                let code = self.codes.get(i).copied().unwrap_or(0) as u32;
                let target = self.targets.get(i).copied().unwrap_or(0.0) as f64;
                let applied = if c.kind == "dac" { if c.role == "laser" { self.laser_now_ma as f64 } else { c.value_of(code) } } else { target };
                json!({"id": c.id, "code": code, "target": target, "applied": applied, "label": c.setting_label(target)})
            })
            .collect();
        json!({
            "map_hash": format!("{:08X}", self.map_hash),
            "map_match": self.map_hash == ControlMap::hash(),
            "laser": {
                "on": self.laser_on, "ramping": self.ramping,
                "target_mA": self.laser_target_ma, "setpoint_mA": self.laser_now_ma,
                "measured_mA": if self.isense_valid { json!(self.isense_ma) } else { Value::Null },
                "isense_code": self.isense_raw, "isense_age_ms": self.isense_age_ms,
                "tracking_warning": self.track_warn,
                "state": off_reason_text(if self.laser_on { 0 } else { self.off_reason }),
            },
            "fault": self.fault, "fault_text": fault_text(self.fault),
            "boot": if self.boot_reason == 4 { "watchdog reset" } else { "power-on" },
            "hb_timeout_ms": self.hb_timeout_ms, "isense_hz": self.isense_hz, "isense_zero_code": self.zero_code,
            "controls": ctrls,
        })
    }
}

// ------------------------------------------------------------- serial link --

/// Commands to a real Pico: the serial thread writes the frames and hands
/// every ACK back to the caller waiting on its sequence number.
#[derive(Default)]
pub struct CmdLink {
    pub tx: std::sync::Mutex<Option<std::sync::mpsc::Sender<Vec<u8>>>>,
    pending: std::sync::Mutex<std::collections::HashMap<u16, std::sync::mpsc::Sender<Vec<u8>>>>,
    seq: std::sync::atomic::AtomicU16,
}

impl CmdLink {
    /// Never 0: the firmware caches the answer to a nonzero sequence number.
    pub fn next_seq(&self) -> u16 {
        loop {
            let s = self.seq.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            if s != 0 {
                return s;
            }
        }
    }
    /// Called by the serial thread for each ACK frame.
    pub fn deliver(&self, payload: Vec<u8>) {
        if let Some(a) = Ack::parse(&payload) {
            if let Some(tx) = self.pending.lock().unwrap().remove(&a.cmd_seq) {
                let _ = tx.send(payload);
            }
        }
    }
    /// Send one command and wait for its ACK: 400 ms per try, three tries.
    /// A retry resends the same sequence number, so the firmware answers it
    /// from its cache instead of running it twice (a relative stage step is
    /// not idempotent).
    pub fn call(&self, payload: &[u8]) -> Result<Ack, String> {
        let seq = self.next_seq();
        for _ in 0..3 {
            let (tx, rx) = std::sync::mpsc::channel();
            self.pending.lock().unwrap().insert(seq, tx);
            let sent = match self.tx.lock().unwrap().as_ref() {
                Some(t) => t.send(frame_cmd(seq, payload)).is_ok(),
                None => false,
            };
            if !sent {
                self.pending.lock().unwrap().remove(&seq);
                return Err("the Pico is not connected".into());
            }
            match rx.recv_timeout(std::time::Duration::from_millis(400)) {
                Ok(p) => return Ack::parse(&p).ok_or_else(|| "malformed ACK".to_string()),
                Err(_) => {
                    self.pending.lock().unwrap().remove(&seq);
                }
            }
        }
        Err("the Pico did not answer the command (3 tries)".into())
    }
}

// ----------------------------------------------------------- simulated board --

extern "C" {
    fn smi_shim_size() -> usize;
    fn smi_shim_hash() -> u32;
    fn smi_shim_init(
        c: *mut c_void,
        ctx: *mut c_void,
        dac: extern "C" fn(*mut c_void, u8, u8, u16) -> bool,
        gp: extern "C" fn(*mut c_void, u8, bool) -> bool,
        wait: extern "C" fn(*mut c_void, u32),
        rd: extern "C" fn(*mut c_void, u8, *mut u16) -> bool,
        reason: u8,
        now_us: u32,
    );
    fn smi_ctl_command(c: *mut c_void, p: *const u8, n: usize, seq: u16, now_us: u32, resp: *mut u8) -> usize;
    fn smi_ctl_tick(c: *mut c_void, now_us: u32);
    fn smi_ctl_isense(c: *mut c_void, raw: i32, now_us: u32);
    fn smi_ctl_laser_readback(c: *mut c_void, ok: bool, reg: u16, now_us: u32);
    fn smi_ctl_state(c: *const c_void, now_us: u32, resp: *mut u8) -> usize;
}

/// What the firmware core has written to the (simulated) hardware.
pub struct Pins {
    pub dac: [[u16; 8]; 4],
    /// Pico GPIOs 0..31, then the head's MCP23008 bits at 32..39.
    pub gpio: [bool; 64],
    pub writes: u64,
}

impl Default for Pins {
    fn default() -> Self {
        Self { dac: [[0; 8]; 4], gpio: [false; 64], writes: 0 }
    }
}

extern "C" fn hal_dac(ctx: *mut c_void, dev: u8, ch: u8, code: u16) -> bool {
    // SAFETY: ctx is the Box<Pins> owned by the SimBoard that registered it.
    let p = unsafe { &mut *(ctx as *mut Pins) };
    if dev as usize >= 4 || ch as usize >= 8 {
        return false;
    }
    p.dac[dev as usize][ch as usize] = code;
    p.writes += 1;
    true
}
/// Simulated time does not advance inside a command, so the disarm wait is a no-op.
extern "C" fn hal_wait(_ctx: *mut c_void, _us: u32) {}

/// The simulated head DAC reads back exactly what was written.
extern "C" fn hal_read(ctx: *mut c_void, dev: u8, reg: *mut u16) -> bool {
    // SAFETY: ctx is the Box<Pins> owned by the SimBoard; reg points at a u16 in the core.
    let p = unsafe { &*(ctx as *const Pins) };
    if dev as usize >= 4 {
        return false;
    }
    unsafe { *reg = p.dac[dev as usize][0] & 0x0FFF };
    true
}

extern "C" fn hal_gpio(ctx: *mut c_void, g: u8, v: bool) -> bool {
    // SAFETY: as above.
    let p = unsafe { &mut *(ctx as *mut Pins) };
    if (g as usize) < 64 {
        p.gpio[g as usize] = v;
    }
    true
}

/// The analog state of the simulated board for one chunk of samples, in the
/// board map's terms: each channel's stage output is
///     Vstage = (1 + K) * Voffset - K * Vbuffer,   Vbuffer = Vref + Iphoto * Rf
/// with K the second-stage gain magnitude (5 or 20).
#[derive(Clone, Debug, Serialize)]
pub struct BoardAnalog {
    /// Actual laser current at the start and end of the chunk, mA.
    pub i0_ma: f64,
    pub i1_ma: f64,
    pub rf1: f64,
    pub rf2: f64,
    pub k1: f64,
    pub k2: f64,
    pub off1_v: f64,
    pub off2_v: f64,
    /// Monitor TIA reference (the head's bias selector), V.
    pub bias_v: f64,
}

/// Simulated v1.2 board: the firmware's control core plus the analog parts it drives.
pub struct SimBoard {
    core: Vec<u64>,
    pins: Box<Pins>,
    pub map: ControlMap,
    /// Laser current actually flowing, mA (the driver loop lags the DAC).
    pub i_act: f64,
    next_isense_us: u64,
    next_conv_us: u64,
    was_on: bool,
    soft_start_us: u64,
    next_poll_us: u64,
    /// Readback polls made (simulated head watchdog traffic).
    pub polls: u64,
    ads_code: i32,
    rng: u64,
    /// Driver model: gain error and offset of the current loop.
    gain_err: f64,
    offset_ma: f64,
}

impl SimBoard {
    pub fn new(now_us: u64) -> Self {
        // SAFETY: plain C struct sizes; the buffer is u64-aligned.
        let n = unsafe { smi_shim_size() };
        let mut b = SimBoard { core: vec![0u64; n.div_ceil(8) + 1], pins: Box::new(Pins::default()), map: ControlMap::load(), i_act: 0.0, next_isense_us: 0, next_conv_us: 0, was_on: false, soft_start_us: 0, next_poll_us: 0, polls: 0, ads_code: 0, rng: 0x9E37_79B9_7F4A_7C15, gain_err: 1.012, offset_ma: 0.35 };
        let ctx = &mut *b.pins as *mut Pins as *mut c_void;
        // SAFETY: core is large enough for smi_ctl_t; ctx outlives the core (both owned here).
        unsafe { smi_shim_init(b.core.as_mut_ptr() as *mut c_void, ctx, hal_dac, hal_gpio, hal_wait, hal_read, 1, now_us as u32) };
        b
    }

    pub fn firmware_hash() -> u32 {
        // SAFETY: returns a constant.
        unsafe { smi_shim_hash() }
    }

    pub fn command(&mut self, payload: &[u8], seq: u16, now_us: u64) -> Vec<u8> {
        let mut r = vec![0u8; 256];
        // SAFETY: r has room for the largest ACK (4 + 28 + 6 * 12 bytes).
        let n = unsafe { smi_ctl_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, now_us: u64) -> BoardState {
        let mut r = vec![0u8; 256];
        // SAFETY: as above.
        let n = unsafe { smi_ctl_state(self.core.as_ptr() as *const c_void, now_us as u32, r.as_mut_ptr()) };
        BoardState::parse(&r[..n]).unwrap_or_default()
    }

    fn noise(&mut self) -> f64 {
        // xorshift, two uniforms summed: cheap, roughly normal, sigma 0.41.
        let mut u = || {
            self.rng ^= self.rng << 13;
            self.rng ^= self.rng >> 7;
            self.rng ^= self.rng << 17;
            (self.rng >> 11) as f64 / (1u64 << 53) as f64 - 0.5
        };
        u() + u()
    }

    fn value(&self, i: usize) -> f64 {
        let c = &self.map.controls[i];
        if c.kind == "dac" {
            let d = self.pins.dac[c.dac.unwrap_or(0) as usize][c.ch.unwrap_or(0) as usize];
            c.value_of(d as u32)
        } else {
            let mut code = 0u32;
            for (b, g) in c.gpios.iter().enumerate() {
                if self.pins.gpio[*g as usize] {
                    code |= 1 << b;
                }
            }
            c.settings.iter().find(|s| s.code == code).map(|s| s.value).unwrap_or(c.default)
        }
    }

    fn laser_enabled(&self) -> bool {
        let g = self.map.laser_enable["gpio"].as_u64().unwrap_or(0) as usize;
        let hi = self.map.laser_enable["active_high"].as_bool().unwrap_or(true);
        self.pins.gpio[g] == hi
    }

    /// Advance the board by `dt_us` of simulated time ending at `now_us`: run the
    /// firmware core, move the laser current through the driver's lag, feed the
    /// current sense back, and return the analog state for the samples.
    pub fn advance(&mut self, now_us: u64, dt_us: u64) -> BoardAnalog {
        let core = self.core.as_mut_ptr() as *mut c_void;
        // SAFETY: core initialised in new().
        unsafe { smi_ctl_tick(core, now_us as u32) };
        let li = self.map.laser();
        let cmd_ma = if self.laser_enabled() { (self.value(li) * self.gain_err + self.offset_ma).max(0.0) } else { 0.0 };
        // Head driver: every arm restarts the head's soft-start, modelled as a
        // 25 ms rise; a disarm cuts the current within about half a millisecond;
        // changes while armed follow a 2 ms loop. The head's shunt cutoff caps
        // the current at its nominal 123.9 mA whatever the DAC says.
        let i0 = self.i_act;
        let on = self.laser_enabled();
        if on && !self.was_on {
            self.soft_start_us = 0;
        }
        self.was_on = on;
        self.soft_start_us = self.soft_start_us.saturating_add(dt_us);
        let tau = if !on { 500.0 } else if self.soft_start_us < 150_000 { 25_000.0 } else { 2_000.0 };
        let a = 1.0 - (-(dt_us as f64) / tau).exp();
        let cutoff = self.map.controls[li].hw_cutoff_mA.unwrap_or(151.0);
        self.i_act = (self.i_act + (cmd_ma - self.i_act) * a).min(cutoff);
        // Current sense: the head's ADS1115 converts the shunt voltage at its
        // data rate (the firmware reads the latest conversion at isense_hz).
        // 2 codes rms of noise, a zero code of +6 (offset of the input), signed
        // 16-bit at the map's full scale.
        let s = self.map.isense.clone();
        let conv_us = 1_000_000 / s.data_rate_sps.max(1) as u64;
        if now_us >= self.next_conv_us {
            self.next_conv_us = now_us + conv_us;
            let nz = self.noise();
            self.ads_code = ((self.i_act - s.offset_mA) / s.mA_per_code + 6.0 + 2.0 * nz / 0.41).round().clamp(-32768.0, 32767.0) as i32;
        }
        // Armed: poll the laser DAC's register like the firmware does (every
        // readback_poll_ms), through the same core check. The simulated DAC
        // always reads back what was written.
        let poll_ms = self.map.laser_watch.as_ref().and_then(|w| w["readback_poll_ms"].as_u64()).unwrap_or(0);
        let st0 = self.state(now_us);
        if poll_ms > 0 && st0.laser_on {
            while self.next_poll_us <= now_us {
                self.next_poll_us += poll_ms * 1000;
                let lc = &self.map.controls[li];
                let reg = self.pins.dac[lc.dac.unwrap_or(0) as usize][lc.ch.unwrap_or(0) as usize] & 0x0FFF;
                self.polls += 1;
                // SAFETY: as above.
                unsafe { smi_ctl_laser_readback(core, true, reg, now_us as u32) };
            }
        } else {
            self.next_poll_us = now_us;
        }
        let hz = st0.isense_hz.max(1) as u64;
        if now_us >= self.next_isense_us {
            self.next_isense_us = now_us + 1_000_000 / hz;
            // SAFETY: as above.
            unsafe { smi_ctl_isense(core, self.ads_code, now_us as u32) };
        }
        let get = |role: &str, ch: u8, stage: Option<&str>, dflt: f64| self.map.find(role, Some(ch), stage).map(|i| self.value(i)).unwrap_or(dflt);
        BoardAnalog {
            i0_ma: i0,
            i1_ma: self.i_act,
            rf1: get("gain", 1, Some("tia"), 1000.0),
            rf2: get("gain", 2, Some("tia"), 46800.0),
            k1: get("gain", 1, Some("amp"), -5.0).abs(),
            k2: get("gain", 2, Some("amp"), -5.0).abs(),
            off1_v: get("offset", 1, None, 0.0),
            off2_v: get("offset", 2, None, 0.0),
            bias_v: self.map.find("bias", None, None).map(|i| self.value(i)).unwrap_or(0.252),
        }
    }
}

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

    #[test]
    fn map_hash_matches_firmware_table() {
        assert_eq!(ControlMap::hash(), SimBoard::firmware_hash(), "regenerate with controls/gen_controls.py");
    }

    #[test]
    fn sim_board_runs_the_firmware_core() {
        let mut b = SimBoard::new(0);
        let li = b.map.laser();
        let lim = b.map.controls[li].limit() as f32;
        let st = b.state(0);
        assert!(!st.laser_on && st.off_reason == 1);
        // No key: refused. With key: on.
        let mut p = cmd_laser(true);
        p[2] = 0;
        assert_eq!(Ack::parse(&b.command(&p, 1, 0)).unwrap().status, 5);
        assert_eq!(Ack::parse(&b.command(&cmd_laser(true), 2, 0)).unwrap().status, 9, "refused before the zero check");
        for ms in 1..=1500u64 {
            b.advance(ms * 1000, 1000);
        }
        let t0 = 1_500_000u64;
        b.command(&[OP_HEARTBEAT], 9, t0);
        assert!(b.state(t0).zero_code.is_some_and(|z| (z - 6.0).abs() < 1.5), "zero {:?}", b.state(t0).zero_code);
        assert!(Ack::parse(&b.command(&cmd_laser(true), 2, t0)).unwrap().ok());
        let a = Ack::parse(&b.command(&cmd_set(li, 0, lim + 5.0), 3, t0)).unwrap();
        assert_eq!(a.status, 4);
        assert!((a.range().unwrap().1 - lim).abs() < 1e-3);
        assert!(Ack::parse(&b.command(&cmd_set(li, 0, 100.0), 4, t0)).unwrap().ok());
        // 1 s with heartbeats: a stepped ramp moves at its rate; a gated head DAC
        // (1.2.1) is written in one step and its soft-start does the ramping.
        let rate = match b.map.controls[li].ramp_per_s.unwrap_or(0.0) { r if r > 0.0 => r, _ => f64::INFINITY };
        for ms in 1..=1000u64 {
            b.advance(t0 + ms * 1000, 1000);
            if ms % 500 == 0 {
                b.command(&[OP_HEARTBEAT], 10, t0 + ms * 1000);
            }
        }
        let st = b.state(t0 + 1_000_000);
        assert!((st.laser_now_ma as f64 - rate.min(100.0)).abs() < 0.01, "set-point {}", st.laser_now_ma);
        if b.map.laser_watch.as_ref().and_then(|w| w["readback_poll_ms"].as_u64()).unwrap_or(0) == 2 {
            assert!(b.polls >= 490, "readback polls in 1 s: {}", b.polls);
        }
        // Hold there; the measured current (driver gain error 1.2 %, offset 0.35 mA) follows.
        b.command(&cmd_set(li, 0, st.laser_now_ma), 11, t0 + 1_000_000);
        for ms in 1001..=1400u64 {
            b.advance(t0 + ms * 1000, 1000);
        }
        let st = b.state(t0 + 1_400_000);
        assert!(st.isense_valid);
        assert!((st.isense_ma - st.laser_now_ma).abs() < 2.0, "measured {} vs {}", st.isense_ma, st.laser_now_ma);
        // Heartbeat stops: off after the timeout.
        for ms in 1401..=5000u64 {
            b.advance(t0 + ms * 1000, 1000);
        }
        let st = b.state(t0 + 5_000_000);
        assert!(!st.laser_on && st.off_reason == 5);
        assert!(b.i_act < 1.0);
    }

    #[test]
    fn command_frame_round_trips_through_the_decoder() {
        let f = frame_cmd(77, &cmd_set(2, 1, 1234.0));
        let mut d = crate::proto::Decoder::default();
        let mut out = vec![];
        d.push(&f, &mut out);
        assert_eq!(out.len(), 1);
        let crate::proto::Frame::Cmd { seq, payload } = &out[0] else { panic!() };
        assert_eq!(*seq, 77);
        assert_eq!(payload[0], OP_SET);
    }
}