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
//! Decoder for the Pico firmware's framed stream (see firmware/src/smi_frame.h).

pub const T_DATA: u8 = 1;
pub const T_SYNC: u8 = 2;
pub const T_STATUS: u8 = 3;
pub const T_INFO: u8 = 4;
pub const T_CMD: u8 = 0x10;
pub const T_ACK: u8 = 0x11;
pub const T_STATE: u8 = 0x12;
/// Test-stage state (firmware 1.3.1): 24-byte block (stage::StageState) + u64 pair index.
pub const T_STAGE: u8 = 0x13;
const HDR: usize = 8;
const BLOCK: usize = 64;

pub fn crc16(p: &[u8]) -> u16 {
    let mut crc: u16 = 0xFFFF;
    for &b in p {
        crc ^= (b as u16) << 8;
        for _ in 0..8 {
            crc = if crc & 0x8000 != 0 { (crc << 1) ^ 0x1021 } else { crc << 1 };
        }
    }
    crc
}

#[derive(Debug, Clone, PartialEq)]
pub enum Frame {
    Data { seq: u16, first_pair: u64, t_us: u32, ch1: Vec<u16>, ch2: Vec<u16> },
    Sync { seq: u16, pair: u64, t_us: u32, level: u8 },
    Status { seq: u16, pairs: u64, dropped_bufs: u32, sync_lost: u32, total_sps: u32, t_us: u32, isense_pauses: Option<u32>, rail_mv: Option<u16> },
    Info { seq: u16, text: String },
    /// Host-to-Pico command (decoded here for tests and replays).
    Cmd { seq: u16, payload: Vec<u8> },
    /// The Pico's answer to one command: controls::Ack::parse(payload).
    Ack { seq: u16, payload: Vec<u8> },
    /// Board control state, four times a second: controls::BoardState::parse(payload).
    State { seq: u16, payload: Vec<u8> },
    /// Test-stage state, every 50 ms while the driver is enabled, else every 500 ms.
    Stage { seq: u16, payload: Vec<u8> },
}

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]])
}
fn u64le(b: &[u8]) -> u64 {
    let mut a = [0u8; 8];
    a.copy_from_slice(&b[..8]);
    u64::from_le_bytes(a)
}

/// Unpack one 64-sample block. Returns bytes consumed.
pub fn unpack_block(src: &[u8], out: &mut [u16; BLOCK]) -> Option<usize> {
    if src.len() < 2 {
        return None;
    }
    let head = u16le(src);
    let code = (head >> 12) as usize;
    out[0] = head & 0x0FFF;
    if code > 12 && code != 15 {
        return None;
    }
    let w = if code == 15 { 12 } else { code };
    let need = 2 + (63 * w + 7) / 8;
    if src.len() < need {
        return None;
    }
    let mut acc: u32 = 0;
    let mut nb = 0usize;
    let mut o = 2usize;
    let mut prev = out[0] as i32;
    for i in 1..BLOCK {
        let mut z = 0u32;
        if w > 0 {
            while nb < w {
                acc |= (src[o] as u32) << nb;
                o += 1;
                nb += 8;
            }
            z = acc & ((1u32 << w) - 1);
            acc >>= w;
            nb -= w;
        }
        if code == 15 {
            out[i] = z as u16;
        } else {
            prev += ((z >> 1) as i32) ^ -((z & 1) as i32);
            if !(0..=4095).contains(&prev) {
                return None;
            }
            out[i] = prev as u16;
        }
    }
    Some(need)
}

#[derive(Default, Debug, Clone)]
pub struct DecodeStats {
    pub frames: u64,
    pub crc_errors: u64,
    pub resync_bytes: u64,
    pub gaps: u64,
}

/// Incremental decoder: feed bytes, get frames. Resynchronises on the 0xA5 0x5A
/// sync word and drops any frame whose CRC fails.
#[derive(Default)]
pub struct Decoder {
    buf: Vec<u8>,
    pub stats: DecodeStats,
    next_pair: Option<u64>,
}

impl Decoder {
    pub fn push(&mut self, bytes: &[u8], out: &mut Vec<Frame>) {
        self.buf.extend_from_slice(bytes);
        let mut i = 0usize;
        loop {
            // Find the sync word.
            while i + 1 < self.buf.len() && !(self.buf[i] == 0xA5 && self.buf[i + 1] == 0x5A) {
                i += 1;
                self.stats.resync_bytes += 1;
            }
            if i + HDR > self.buf.len() {
                break;
            }
            let len = u16le(&self.buf[i + 4..]) as usize;
            if len > 8192 {
                i += 1;
                self.stats.resync_bytes += 1;
                continue;
            }
            let total = HDR + len + 2;
            if i + total > self.buf.len() {
                break;
            }
            let f = &self.buf[i..i + total];
            let crc = u16le(&f[HDR + len..]);
            if crc16(&f[2..HDR + len]) != crc {
                self.stats.crc_errors += 1;
                i += 1;
                continue;
            }
            if let Some(fr) = parse(f[2], u16le(&f[6..]), &f[HDR..HDR + len]) {
                if let Frame::Data { first_pair, ch1, .. } = &fr {
                    if let Some(np) = self.next_pair {
                        if *first_pair != np {
                            self.stats.gaps += 1;
                        }
                    }
                    self.next_pair = Some(first_pair + ch1.len() as u64);
                }
                self.stats.frames += 1;
                out.push(fr);
            } else {
                self.stats.crc_errors += 1;
            }
            i += total;
        }
        self.buf.drain(..i);
    }
}

fn parse(ty: u8, seq: u16, p: &[u8]) -> Option<Frame> {
    match ty {
        T_DATA => {
            if p.len() < 13 {
                return None;
            }
            let first_pair = u64le(p);
            let t_us = u32le(&p[8..]);
            let groups = p[12] as usize;
            let mut ch1 = Vec::with_capacity(groups * BLOCK);
            let mut ch2 = Vec::with_capacity(groups * BLOCK);
            let mut o = 13;
            let mut blk = [0u16; BLOCK];
            for _ in 0..groups {
                o += unpack_block(&p[o..], &mut blk)?;
                ch1.extend_from_slice(&blk);
                o += unpack_block(&p[o..], &mut blk)?;
                ch2.extend_from_slice(&blk);
            }
            Some(Frame::Data { seq, first_pair, t_us, ch1, ch2 })
        }
        T_SYNC if p.len() >= 13 => Some(Frame::Sync { seq, pair: u64le(p), t_us: u32le(&p[8..]), level: p[12] }),
        T_STATUS if p.len() >= 24 => Some(Frame::Status {
            seq,
            pairs: u64le(p),
            dropped_bufs: u32le(&p[8..]),
            sync_lost: u32le(&p[12..]),
            total_sps: u32le(&p[16..]),
            t_us: u32le(&p[20..]),
            isense_pauses: (p.len() >= 28).then(|| u32le(&p[24..])),
            rail_mv: (p.len() >= 30).then(|| u16le(&p[28..])),
        }),
        T_CMD => Some(Frame::Cmd { seq, payload: p.to_vec() }),
        T_ACK if p.len() >= 4 => Some(Frame::Ack { seq, payload: p.to_vec() }),
        T_STATE if p.len() >= 28 => Some(Frame::State { seq, payload: p.to_vec() }),
        T_STAGE if p.len() >= 24 => Some(Frame::Stage { seq, payload: p.to_vec() }),
        T_INFO => Some(Frame::Info { seq, text: String::from_utf8_lossy(p).into_owned() }),
        _ => None,
    }
}

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

    #[test]
    fn crc_check_value() {
        assert_eq!(crc16(b"123456789"), 0x29B1);
    }

    /// vectors.bin is written by the firmware's own C packer (firmware/test/test_pack.c).
    #[test]
    fn decodes_firmware_vectors() {
        let bytes = include_bytes!("../../firmware/test/vectors.bin");
        let mut d = Decoder::default();
        let mut out = vec![];
        // Feed in awkward slices, with garbage in front, to exercise resync.
        let mut junk = vec![0x5A, 0xA5, 0x00, 0x13];
        junk.extend_from_slice(bytes);
        for ch in junk.chunks(37) {
            d.push(ch, &mut out);
        }
        assert_eq!(out.len(), 4);
        assert_eq!(d.stats.crc_errors, 0);
        for (fr, f) in out.iter().enumerate() {
            let Frame::Data { first_pair, ch1, ch2, .. } = f else { panic!("not data") };
            assert_eq!(*first_pair, fr as u64 * 1024);
            for i in 0..1024 {
                let n = fr as f64 * 1024.0 + i as f64;
                assert_eq!(ch1[i], (2048.0 + 1200.0 * (n * 0.05).sin()) as u16);
                assert_eq!(ch2[i] as u64, ((fr * 1024 + i) as u64 * 7) % 4096);
            }
        }
    }

    #[test]
    fn corrupt_frame_is_dropped() {
        let mut bytes = include_bytes!("../../firmware/test/vectors.bin").to_vec();
        let first_len = 8 + u16le(&bytes[4..]) as usize + 2;
        bytes[first_len + 100] ^= 0x40; // corrupt the second frame
        let mut d = Decoder::default();
        let mut out = vec![];
        d.push(&bytes, &mut out);
        assert_eq!(out.len(), 3);
        assert!(d.stats.crc_errors >= 1);
        assert_eq!(d.stats.gaps, 1);
    }
}