Skip to main content

litz_decode/
lib.rs

1//! Decode UART, I2C and SPI from probed digital waveforms.
2//!
3//! A waveform is a record of level changes, not a sampled grid: each entry is
4//! the level *after* a change, held until the next entry. The first entry is
5//! the level when recording started. All times are ticks (1 ns).
6//!
7//! Decoders are deliberately tolerant: empty, short or out-of-order records
8//! yield no frames or best-effort frames rather than a panic. Where the
9//! protocol leaves room for interpretation the choice is documented on the
10//! decoder.
11
12use litz_core::{Level, TICKS_PER_SEC, Tick};
13
14mod i2c;
15mod spi;
16mod uart;
17
18pub use i2c::i2c;
19pub use spi::{SpiMode, spi};
20pub use uart::uart;
21
22/// A read-only view over a recorded waveform.
23#[derive(Clone, Copy)]
24pub struct Wave<'a> {
25    points: &'a [(Tick, Level)],
26}
27
28impl<'a> Wave<'a> {
29    pub fn new(points: &'a [(Tick, Level)]) -> Self {
30        Self { points }
31    }
32
33    /// The level held at `at`: the last point at or before it.
34    pub fn at(&self, at: Tick) -> Option<Level> {
35        let idx = self.points.partition_point(|&(tick, _)| tick <= at);
36        self.points
37            .get(idx.checked_sub(1)?)
38            .map(|&(_, level)| level)
39    }
40
41    /// Change points: (tick, level after the change), in order.
42    pub fn edges(&self) -> impl Iterator<Item = (Tick, Level)> + '_ {
43        self.points.iter().copied()
44    }
45
46    /// Shortest run between consecutive changes, in ticks.
47    ///
48    /// The first entry is the level held when recording started, not a change,
49    /// so the segment before the first change is open on the left: how long
50    /// the line had already been idle is not part of the record. It is
51    /// skipped, which matters when a capture begins just before the first
52    /// byte and that idle looks shorter than one bit. Repeated ticks (a
53    /// malformed record) are skipped too: they describe no run.
54    pub fn shortest_run(&self) -> Option<u64> {
55        self.points
56            .windows(2)
57            .skip(1)
58            .map(|pair| pair[1].0.saturating_sub(pair[0].0))
59            .filter(|&run| run > 0)
60            .min()
61    }
62
63    /// Ticks of the first and last change points.
64    pub fn span(&self) -> Option<(Tick, Tick)> {
65        let first = self.points.first()?.0;
66        let last = self.points.last()?.0;
67        Some((first, last))
68    }
69}
70
71/// One decoded frame or bus transaction.
72#[derive(Clone, Debug, PartialEq)]
73pub struct Frame {
74    /// When the frame or transaction began.
75    pub at: Tick,
76    /// When it ended.
77    pub end: Tick,
78    /// Payload bytes (UART: the byte; I2C: data bytes after the address;
79    /// SPI: MOSI bytes).
80    pub bytes: Vec<u8>,
81    /// SPI MISO bytes; empty for every other protocol.
82    pub miso: Vec<u8>,
83    /// One-line human summary.
84    pub text: String,
85    /// Framing or protocol problem, if any.
86    pub error: Option<String>,
87}
88
89/// Bit period from the shortest run, rounded to the nearest integer baud.
90///
91/// The shortest run is assumed to be one bit wide, which holds for any
92/// recording containing a transition between adjacent bits.
93pub fn infer_baud(points: &[(Tick, Level)]) -> Option<u32> {
94    let run = Wave::new(points).shortest_run()? as u128;
95    if run == 0 {
96        return None;
97    }
98    // Round half up without floating point so the result is exact.
99    let baud = (TICKS_PER_SEC as u128 + run / 2) / run;
100    if baud == 0 || baud > u32::MAX as u128 {
101        return None;
102    }
103    Some(baud as u32)
104}
105
106/// Merge two channel recordings into one time-ordered event list.
107///
108/// `priority` decides ties: the channel with the lower value is processed
109/// first, so the caller can encode bus rules such as "clock before data".
110pub(crate) fn merge_events(
111    a: &[(Tick, Level)],
112    a_priority: u8,
113    b: &[(Tick, Level)],
114    b_priority: u8,
115) -> Vec<(Tick, u8, Level)> {
116    let mut events = Vec::with_capacity(a.len() + b.len());
117    events.extend(a.iter().map(|&(tick, level)| (tick, a_priority, level)));
118    events.extend(b.iter().map(|&(tick, level)| (tick, b_priority, level)));
119    events.sort_by_key(|&(tick, priority, _)| (tick, priority));
120    events
121}
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126
127    const POINTS: &[(Tick, Level)] = &[
128        (0, Level::High),
129        (100, Level::Low),
130        (250, Level::High),
131        (400, Level::Low),
132    ];
133
134    #[test]
135    fn at_returns_the_level_held_at_a_tick() {
136        let wave = Wave::new(POINTS);
137        assert_eq!(wave.at(0), Some(Level::High));
138        assert_eq!(wave.at(99), Some(Level::High));
139        assert_eq!(wave.at(100), Some(Level::Low));
140        assert_eq!(wave.at(399), Some(Level::High));
141        assert_eq!(wave.at(1_000), Some(Level::Low));
142    }
143
144    #[test]
145    fn at_before_the_recording_is_none() {
146        let wave = Wave::new(&POINTS[1..]);
147        assert_eq!(wave.at(50), None);
148    }
149
150    #[test]
151    fn edges_span_and_shortest_run() {
152        let wave = Wave::new(POINTS);
153        assert_eq!(wave.edges().count(), 4);
154        assert_eq!(wave.edges().last(), Some((400, Level::Low)));
155        assert_eq!(wave.span(), Some((0, 400)));
156        // The first segment starts at the recording's first entry rather than
157        // at a change, so the shortest bounded run is 150, not 100.
158        assert_eq!(wave.shortest_run(), Some(150));
159    }
160
161    #[test]
162    fn empty_wave_has_no_span_or_run() {
163        let wave = Wave::new(&[]);
164        assert_eq!(wave.at(0), None);
165        assert_eq!(wave.span(), None);
166        assert_eq!(wave.shortest_run(), None);
167        assert_eq!(wave.edges().count(), 0);
168    }
169}