Skip to main content

litz_engine/
decode.rs

1//! Reading protocols off the channels a run already recorded.
2//!
3//! A decoder is not a part and does not listen to the circuit: it takes the
4//! digital series of named probes — exactly what the scope draws — and turns
5//! level changes back into bytes. That keeps decoding zero-load and lets a
6//! host decode the same record differently (one UART at 9600, another at
7//! 115200) without running the simulation again.
8//!
9//! A `[[decode]]` entry names probe channels, not points. The probe block says
10//! where to watch; the decode block says what to read there.
11
12use crate::config::DecodeSection;
13use litz_board::probe::{Channel, Probe};
14use litz_core::{Level, Tick};
15use litz_decode::{Frame, SpiMode};
16
17/// Every channel a decoder names must be a probe, so a typo is a configuration
18/// error at boot rather than a decoder that silently reads nothing.
19pub fn check(spec: &DecodeSection, probes: &[Probe]) -> Result<(), String> {
20    spec.validate()?;
21    for name in channels(spec) {
22        if !probes.iter().any(|probe| probe.name == name) {
23            return Err(format!(
24                "decode {:?}: no probe named {name:?}; add [[probe]] \
25                 name = {name:?} point = \"<board>:<GPIO>\" or pass --probe",
26                spec.label()
27            ));
28        }
29    }
30    Ok(())
31}
32
33/// The channels a decoder reads, in the order the kind names them.
34fn channels(spec: &DecodeSection) -> Vec<&str> {
35    match spec.kind.as_str() {
36        "i2c" => vec![
37            spec.sda.as_deref().unwrap_or(""),
38            spec.scl.as_deref().unwrap_or(""),
39        ],
40        "spi" => {
41            let mut names = vec![
42                spec.sck.as_deref().unwrap_or(""),
43                spec.mosi.as_deref().unwrap_or(""),
44            ];
45            if let Some(miso) = spec.miso.as_deref() {
46                names.push(miso);
47            }
48            names.push(spec.cs.as_deref().unwrap_or(""));
49            names
50        }
51        _ => vec![spec.rx.as_deref().unwrap_or("")],
52    }
53}
54
55/// The record of one channel, by probe name.
56fn series<'a>(channels: &'a [Channel], name: &str) -> Result<&'a [(Tick, Level)], String> {
57    channels
58        .iter()
59        .find(|channel| channel.probe.name == name)
60        .map(|channel| channel.series.digital.as_slice())
61        .ok_or_else(|| format!("decode: no recorded channel named {name:?}"))
62}
63
64/// Run one decoder over a finished scope record.
65pub fn frames(spec: &DecodeSection, channels: &[Channel]) -> Result<Vec<Frame>, String> {
66    spec.validate()?;
67    match spec.kind.as_str() {
68        "i2c" => {
69            let sda = series(channels, spec.sda.as_deref().unwrap_or(""))?;
70            let scl = series(channels, spec.scl.as_deref().unwrap_or(""))?;
71            Ok(litz_decode::i2c(sda, scl))
72        }
73        "spi" => {
74            let sck = series(channels, spec.sck.as_deref().unwrap_or(""))?;
75            let mosi = series(channels, spec.mosi.as_deref().unwrap_or(""))?;
76            let miso = spec
77                .miso
78                .as_deref()
79                .map(|name| series(channels, name))
80                .transpose()?;
81            let cs = series(channels, spec.cs.as_deref().unwrap_or(""))?;
82            let mode = match spec.mode.unwrap_or(0) {
83                1 => SpiMode::Mode1,
84                2 => SpiMode::Mode2,
85                3 => SpiMode::Mode3,
86                _ => SpiMode::Mode0,
87            };
88            Ok(litz_decode::spi(sck, mosi, miso, cs, mode))
89        }
90        _ => {
91            let rx = series(channels, spec.rx.as_deref().unwrap_or(""))?;
92            Ok(litz_decode::uart(rx, spec.baud))
93        }
94    }
95}
96
97/// One report line per decoded frame, ready for the `litz: ` prefix.
98pub fn report<'a>(
99    specs: impl IntoIterator<Item = &'a DecodeSection>,
100    channels: &[Channel],
101) -> Result<Vec<String>, String> {
102    let mut lines = Vec::new();
103    for spec in specs {
104        let decoded = frames(spec, channels)?;
105        if decoded.is_empty() {
106            lines.push(format!("{}: no frames", spec.label()));
107        }
108        for frame in decoded {
109            let mut line = format!("{}: {}", spec.label(), frame.text);
110            if let Some(error) = &frame.error {
111                line.push_str(&format!(" ({error})"));
112            }
113            lines.push(line);
114        }
115    }
116    Ok(lines)
117}