main
John Lauer software/: Pico firmware (500 ksps two-channel ADC over DMA, SYNC on GPIO15, framed delta-packed USB stream), smi-dash… e09b832
// SPDX-License-Identifier: MIT
//! Recording to CSV (streamed) or HDF5 (buffered, written on stop).

use serde::Serialize;
use std::fs::File;
use std::io::{BufWriter, Write};
use std::path::PathBuf;

#[derive(Clone, Copy, Debug, Serialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum Format {
    Csv,
    H5,
}

impl Format {
    pub fn parse(s: &str) -> Option<Self> {
        match s {
            "csv" => Some(Self::Csv),
            "h5" | "hdf5" => Some(Self::H5),
            _ => None,
        }
    }
}

/// HDF5 recordings are held in memory until stop; cap them.
pub const H5_MAX_SECONDS: f64 = 120.0;

pub struct Meta {
    pub source: String,
    pub wavelength_nm: f64,
    pub lp_hz: f64,
    pub threshold: f64,
}

pub struct Recorder {
    pub format: Format,
    pub path: PathBuf,
    pub start_pair: u64,
    pub pairs: u64,
    pub limit_pairs: Option<u64>,
    pub fringes: u64,
    pub syncs: u64,
    csv: Option<BufWriter<File>>,
    ch1: Vec<u16>,
    ch2: Vec<u16>,
    disp: Vec<f32>,
    truth: Vec<f32>,
    fr: Vec<(u64, i8)>,
    sy: Vec<(u64, u8)>,
    meta: Meta,
    pub started: chrono::DateTime<chrono::Local>,
}

#[derive(Serialize, Clone)]
pub struct RecStatus {
    pub active: bool,
    pub format: Format,
    pub path: String,
    pub seconds: f64,
    pub limit_seconds: Option<f64>,
    pub fringes: u64,
    pub syncs: u64,
}

impl Recorder {
    pub fn start(dir: &std::path::Path, format: Format, seconds: Option<f64>, start_pair: u64, meta: Meta) -> std::io::Result<Self> {
        std::fs::create_dir_all(dir)?;
        let started = chrono::Local::now();
        let ext = match format {
            Format::Csv => "csv",
            Format::H5 => "h5",
        };
        let path = dir.join(format!("smi-{}.{}", started.format("%Y%m%d-%H%M%S"), ext));
        let mut limit = seconds.map(|s| (s * 250_000.0) as u64);
        if format == Format::H5 {
            let cap = (H5_MAX_SECONDS * 250_000.0) as u64;
            limit = Some(limit.map_or(cap, |l| l.min(cap)));
        }
        let csv = if format == Format::Csv {
            let mut w = BufWriter::with_capacity(1 << 20, File::create(&path)?);
            writeln!(w, "# smi-dash recording, {}", started.to_rfc3339())?;
            writeln!(w, "# source: {}", meta.source)?;
            writeln!(w, "# per-channel rate 250000 Hz; ch2 is sampled 2 us after ch1 in each pair; 12-bit codes, 3.3 V full scale")?;
            writeln!(w, "# wavelength_nm {}; one fringe = {} nm; detector lp_hz {}; threshold {}", meta.wavelength_nm, meta.wavelength_nm / 2.0, meta.lp_hz, meta.threshold)?;
            writeln!(w, "# fringe: +1 away, -1 towards, at the pair where the edge was steepest; disp_nm: running fringe count x lambda/2")?;
            writeln!(w, "pair,t_s,ch1,ch2,ch1_v,ch2_v,sync,fringe,disp_nm,truth_nm")?;
            Some(w)
        } else {
            None
        };
        Ok(Self {
            format,
            path,
            start_pair,
            pairs: 0,
            limit_pairs: limit,
            fringes: 0,
            syncs: 0,
            csv,
            ch1: vec![],
            ch2: vec![],
            disp: vec![],
            truth: vec![],
            fr: vec![],
            sy: vec![],
            meta,
            started,
        })
    }

    pub fn done(&self) -> bool {
        self.limit_pairs.is_some_and(|l| self.pairs >= l)
    }

    /// Append a contiguous chunk starting at absolute pair `first`.
    #[allow(clippy::too_many_arguments)]
    pub fn write(
        &mut self,
        first: u64,
        ch1: &[u16],
        ch2: &[u16],
        disp_nm: &[f32],
        truth_nm: Option<&[f64]>,
        sync: &[(u64, u8)],
        fringes: &[(u64, i8)],
        sync_level_at_start: u8,
    ) -> std::io::Result<()> {
        let mut n = ch1.len();
        if let Some(l) = self.limit_pairs {
            n = n.min((l - self.pairs) as usize);
        }
        if n == 0 {
            return Ok(());
        }
        let last = first + n as u64;
        let fr: Vec<(u64, i8)> = fringes.iter().copied().filter(|f| f.0 < last).map(|(p, d)| (p.max(first), d)).collect();
        let sy: Vec<(u64, u8)> = sync.iter().copied().filter(|s| s.0 >= first && s.0 < last).collect();
        self.fringes += fr.len() as u64;
        self.syncs += sy.len() as u64;
        let lsb = 3.3 / 4096.0;
        if let Some(w) = self.csv.as_mut() {
            let mut level = sync_level_at_start;
            let (mut fi, mut si) = (0usize, 0usize);
            for i in 0..n {
                let p = first + i as u64;
                while si < sy.len() && sy[si].0 <= p {
                    level = sy[si].1;
                    si += 1;
                }
                let mut f = 0i8;
                while fi < fr.len() && fr[fi].0 <= p {
                    f = fr[fi].1;
                    fi += 1;
                }
                let t = (p - self.start_pair) as f64 / 250_000.0;
                match truth_nm {
                    Some(tr) => writeln!(w, "{},{:.6},{},{},{:.4},{:.4},{},{},{:.1},{:.1}", p, t, ch1[i], ch2[i], ch1[i] as f64 * lsb, ch2[i] as f64 * lsb, level, f, disp_nm[i], tr[i])?,
                    None => writeln!(w, "{},{:.6},{},{},{:.4},{:.4},{},{},{:.1},", p, t, ch1[i], ch2[i], ch1[i] as f64 * lsb, ch2[i] as f64 * lsb, level, f, disp_nm[i])?,
                }
            }
        } else {
            self.ch1.extend_from_slice(&ch1[..n]);
            self.ch2.extend_from_slice(&ch2[..n]);
            self.disp.extend_from_slice(&disp_nm[..n]);
            if let Some(tr) = truth_nm {
                self.truth.extend(tr[..n].iter().map(|&v| v as f32));
            }
            self.fr.extend(fr);
            self.sy.extend(sy);
        }
        self.pairs += n as u64;
        Ok(())
    }

    pub fn status(&self) -> RecStatus {
        RecStatus {
            active: true,
            format: self.format,
            path: self.path.display().to_string(),
            seconds: self.pairs as f64 / 250_000.0,
            limit_seconds: self.limit_pairs.map(|l| l as f64 / 250_000.0),
            fringes: self.fringes,
            syncs: self.syncs,
        }
    }

    pub fn finish(mut self) -> Result<RecStatus, String> {
        let st = self.status();
        match self.format {
            Format::Csv => {
                if let Some(mut w) = self.csv.take() {
                    w.flush().map_err(|e| e.to_string())?;
                }
            }
            Format::H5 => self.write_h5()?,
        }
        Ok(RecStatus { active: false, ..st })
    }

    #[cfg(feature = "h5")]
    fn write_h5(&self) -> Result<(), String> {
        use hdf5::types::VarLenUnicode;
        let e = |x: hdf5::Error| x.to_string();
        let f = hdf5::File::create(&self.path).map_err(e)?;
        f.new_dataset_builder().deflate(4).with_data(&self.ch1).create("ch1").map_err(e)?;
        f.new_dataset_builder().deflate(4).with_data(&self.ch2).create("ch2").map_err(e)?;
        f.new_dataset_builder().deflate(4).with_data(&self.disp).create("disp_nm").map_err(e)?;
        if !self.truth.is_empty() {
            f.new_dataset_builder().deflate(4).with_data(&self.truth).create("truth_nm").map_err(e)?;
        }
        let fp: Vec<u64> = self.fr.iter().map(|x| x.0).collect();
        let fd: Vec<i8> = self.fr.iter().map(|x| x.1).collect();
        let sp: Vec<u64> = self.sy.iter().map(|x| x.0).collect();
        let sl: Vec<u8> = self.sy.iter().map(|x| x.1).collect();
        let g = f.create_group("fringes").map_err(e)?;
        g.new_dataset_builder().with_data(&fp).create("pair").map_err(e)?;
        g.new_dataset_builder().with_data(&fd).create("dir").map_err(e)?;
        let g = f.create_group("sync").map_err(e)?;
        g.new_dataset_builder().with_data(&sp).create("pair").map_err(e)?;
        g.new_dataset_builder().with_data(&sl).create("level").map_err(e)?;
        let attr_f = |name: &str, v: f64| -> Result<(), String> {
            f.new_attr::<f64>().create(name).map_err(e)?.write_scalar(&v).map_err(e)
        };
        attr_f("sample_rate_hz", 250_000.0)?;
        attr_f("ch2_delay_s", 2e-6)?;
        attr_f("lsb_volts", 3.3 / 4096.0)?;
        attr_f("wavelength_nm", self.meta.wavelength_nm)?;
        attr_f("detector_lp_hz", self.meta.lp_hz)?;
        attr_f("detector_threshold", self.meta.threshold)?;
        f.new_attr::<u64>().create("start_pair").map_err(e)?.write_scalar(&self.start_pair).map_err(e)?;
        let s: VarLenUnicode = self.meta.source.parse().map_err(|_| "bad source string".to_string())?;
        f.new_attr::<VarLenUnicode>().create("source").map_err(e)?.write_scalar(&s).map_err(e)?;
        let s: VarLenUnicode = self.started.to_rfc3339().parse().map_err(|_| "bad time".to_string())?;
        f.new_attr::<VarLenUnicode>().create("created").map_err(e)?.write_scalar(&s).map_err(e)?;
        Ok(())
    }

    #[cfg(not(feature = "h5"))]
    fn write_h5(&self) -> Result<(), String> {
        Err("this build has no HDF5 support; record with --format csv".into())
    }
}