Skip to main content

litz_decode/
spi.rs

1//! SPI decoding: MSB first, chip select active low.
2//!
3//! The clock edge that samples data follows from the mode: modes 0 and 3
4//! sample on a rising SCK edge, modes 1 and 2 on a falling one. A trailing
5//! group of fewer than eight bits is dropped rather than reported as an error.
6
7use litz_core::{Level, Tick};
8
9use crate::{Frame, Wave, merge_events};
10
11const CS: u8 = 0;
12const SCK: u8 = 1;
13
14#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
15pub enum SpiMode {
16    #[default]
17    Mode0,
18    Mode1,
19    Mode2,
20    Mode3,
21}
22
23impl SpiMode {
24    /// CPOL == CPHA: the sampling edge is a rising one.
25    fn samples_rising(self) -> bool {
26        matches!(self, SpiMode::Mode0 | SpiMode::Mode3)
27    }
28}
29
30/// Decode SPI frames from SCK, MOSI, optional MISO and CS recordings.
31///
32/// A frame opens when CS falls and closes when it rises. If the record starts
33/// with CS already low, the frame opens at the first SCK change and is dated
34/// from its first sample.
35pub fn spi(
36    sck: &[(Tick, Level)],
37    mosi: &[(Tick, Level)],
38    miso: Option<&[(Tick, Level)]>,
39    cs: &[(Tick, Level)],
40    mode: SpiMode,
41) -> Vec<Frame> {
42    if sck.is_empty() || cs.is_empty() {
43        return Vec::new();
44    }
45
46    let mosi_wave = Wave::new(mosi);
47    let miso_wave = miso.map(Wave::new);
48    let has_miso = miso.is_some();
49    let sample_level = if mode.samples_rising() {
50        Level::High
51    } else {
52        Level::Low
53    };
54
55    // CS first on ties so a falling chip select enables the same-tick clock
56    // edge for sampling.
57    let events = merge_events(cs, CS, sck, SCK);
58    let mut cs_level = cs.first().map(|&(_, level)| level);
59    let mut open: Option<Partial> = None;
60    let mut frames = Vec::new();
61
62    for &(tick, channel, level) in &events {
63        if channel == CS {
64            let was = cs_level;
65            cs_level = Some(level);
66            if level == Level::Low && was != Some(Level::Low) {
67                open = Some(Partial::new(Some(tick), has_miso));
68            } else if level == Level::High
69                && was == Some(Level::Low)
70                && let Some(partial) = open.take()
71            {
72                partial.finish(tick, &mut frames);
73            }
74        } else {
75            // CS already low without a recorded falling edge: the capture
76            // started mid-transaction, so date the frame from its first bit.
77            if open.is_none() && cs_level == Some(Level::Low) {
78                open = Some(Partial::new(None, has_miso));
79            }
80            if level == sample_level
81                && let Some(partial) = open.as_mut()
82            {
83                partial.sample(tick, &mosi_wave, miso_wave.as_ref());
84            }
85        }
86    }
87
88    if let Some(partial) = open {
89        // Close an unterminated frame at the last clock or data change.
90        let end = last_tick(sck)
91            .max(last_tick(mosi))
92            .max(miso.map_or(0, last_tick))
93            .max(partial.last_sample.unwrap_or(0));
94        partial.finish(end, &mut frames);
95    }
96
97    frames
98}
99
100struct Partial {
101    at: Option<Tick>,
102    last_sample: Option<Tick>,
103    mosi: Vec<u8>,
104    miso: Vec<u8>,
105    mosi_byte: u8,
106    miso_byte: u8,
107    bits: u8,
108    has_miso: bool,
109}
110
111impl Partial {
112    fn new(at: Option<Tick>, has_miso: bool) -> Self {
113        Self {
114            at,
115            last_sample: None,
116            mosi: Vec::new(),
117            miso: Vec::new(),
118            mosi_byte: 0,
119            miso_byte: 0,
120            bits: 0,
121            has_miso,
122        }
123    }
124
125    fn sample(&mut self, tick: Tick, mosi: &Wave<'_>, miso: Option<&Wave<'_>>) {
126        self.at.get_or_insert(tick);
127        self.last_sample = Some(tick);
128        self.mosi_byte = (self.mosi_byte << 1) | u8::from(mosi.at(tick) == Some(Level::High));
129        if let Some(miso) = miso {
130            self.miso_byte = (self.miso_byte << 1) | u8::from(miso.at(tick) == Some(Level::High));
131        }
132        self.bits += 1;
133        if self.bits == 8 {
134            self.mosi.push(self.mosi_byte);
135            if self.has_miso {
136                self.miso.push(self.miso_byte);
137            }
138            self.mosi_byte = 0;
139            self.miso_byte = 0;
140            self.bits = 0;
141        }
142    }
143
144    fn finish(self, end: Tick, frames: &mut Vec<Frame>) {
145        if self.mosi.is_empty() {
146            return;
147        }
148        let has_miso = self.has_miso;
149        let miso = if has_miso { self.miso } else { Vec::new() };
150        let text = frame_text(&self.mosi, has_miso.then_some(miso.as_slice()));
151        frames.push(Frame {
152            at: self.at.unwrap_or(end),
153            end,
154            bytes: self.mosi,
155            miso,
156            text,
157            error: None,
158        });
159    }
160}
161
162fn last_tick(points: &[(Tick, Level)]) -> Tick {
163    points.last().map_or(0, |&(tick, _)| tick)
164}
165
166fn frame_text(mosi: &[u8], miso: Option<&[u8]>) -> String {
167    let mut text = hex_list(mosi);
168    if let Some(miso) = miso {
169        text.push_str(" -> ");
170        text.push_str(&hex_list(miso));
171    }
172    text
173}
174
175fn hex_list(bytes: &[u8]) -> String {
176    bytes
177        .iter()
178        .map(|byte| format!("0x{byte:02x}"))
179        .collect::<Vec<_>>()
180        .join(" ")
181}
182
183#[cfg(test)]
184mod tests {
185    use super::*;
186
187    const H: Tick = 10;
188
189    struct Bus {
190        sck: Vec<(Tick, Level)>,
191        mosi: Vec<(Tick, Level)>,
192        miso: Vec<(Tick, Level)>,
193        cs: Vec<(Tick, Level)>,
194        tick: Tick,
195    }
196
197    impl Bus {
198        fn new(clock_idle: Level) -> Self {
199            Self {
200                sck: vec![(0, clock_idle)],
201                mosi: vec![(0, Level::Low)],
202                miso: vec![(0, Level::Low)],
203                cs: vec![(0, Level::High)],
204                tick: H,
205            }
206        }
207
208        fn set(line: &mut Vec<(Tick, Level)>, tick: Tick, level: Level) {
209            if line.last().map(|&(_, last)| last) != Some(level) {
210                line.push((tick, level));
211            }
212        }
213
214        fn data(&mut self, mosi: Level, miso: Level) {
215            Self::set(&mut self.mosi, self.tick, mosi);
216            Self::set(&mut self.miso, self.tick, miso);
217            self.tick += H;
218        }
219
220        fn clock(&mut self, level: Level) {
221            Self::set(&mut self.sck, self.tick, level);
222            self.tick += H;
223        }
224
225        fn chip(&mut self, level: Level) {
226            Self::set(&mut self.cs, self.tick, level);
227            self.tick += H;
228        }
229
230        /// Clock out the top `count` bits of `mosi`/`miso` in the given mode.
231        fn bits(&mut self, mosi: u8, miso: u8, mode: SpiMode, count: u32) {
232            for n in (0..count).rev() {
233                let m = bit_level(mosi, n);
234                let s = bit_level(miso, n);
235                match mode {
236                    // Leading edge is the sample edge for CPHA == 0.
237                    SpiMode::Mode0 => {
238                        self.data(m, s);
239                        self.clock(Level::High);
240                        self.clock(Level::Low);
241                    }
242                    // Leading edge shifts, trailing edge samples.
243                    SpiMode::Mode1 => {
244                        self.data(m, s);
245                        self.clock(Level::High);
246                        self.clock(Level::Low);
247                    }
248                    SpiMode::Mode2 => {
249                        self.data(m, s);
250                        self.clock(Level::Low);
251                        self.clock(Level::High);
252                    }
253                    SpiMode::Mode3 => {
254                        self.clock(Level::Low);
255                        self.data(m, s);
256                        self.clock(Level::High);
257                    }
258                }
259            }
260        }
261    }
262
263    fn bit_level(byte: u8, n: u32) -> Level {
264        if byte >> n & 1 == 1 {
265            Level::High
266        } else {
267            Level::Low
268        }
269    }
270
271    #[test]
272    fn mode0_decodes_mosi_and_miso() {
273        let mut bus = Bus::new(Level::Low);
274        let at = bus.tick;
275        bus.chip(Level::Low);
276        bus.bits(0x9f, 0x12, SpiMode::Mode0, 8);
277        bus.bits(0x00, 0x34, SpiMode::Mode0, 8);
278        bus.bits(0x00, 0x56, SpiMode::Mode0, 8);
279        let end = bus.tick;
280        bus.chip(Level::High);
281
282        let frames = spi(
283            &bus.sck,
284            &bus.mosi,
285            Some(&bus.miso),
286            &bus.cs,
287            SpiMode::Mode0,
288        );
289        assert_eq!(frames.len(), 1);
290        assert_eq!(frames[0].at, at);
291        assert_eq!(frames[0].end, end);
292        assert_eq!(frames[0].bytes, vec![0x9f, 0x00, 0x00]);
293        assert_eq!(frames[0].miso, vec![0x12, 0x34, 0x56]);
294        assert_eq!(frames[0].text, "0x9f 0x00 0x00 -> 0x12 0x34 0x56");
295        assert_eq!(frames[0].error, None);
296    }
297
298    #[test]
299    fn mode3_samples_on_the_rising_edge() {
300        let mut bus = Bus::new(Level::High);
301        bus.chip(Level::Low);
302        bus.bits(0xa5, 0x5a, SpiMode::Mode3, 8);
303        bus.chip(Level::High);
304
305        let frames = spi(
306            &bus.sck,
307            &bus.mosi,
308            Some(&bus.miso),
309            &bus.cs,
310            SpiMode::Mode3,
311        );
312        assert_eq!(frames.len(), 1);
313        assert_eq!(frames[0].bytes, vec![0xa5]);
314        assert_eq!(frames[0].miso, vec![0x5a]);
315    }
316
317    #[test]
318    fn mode1_samples_on_the_falling_edge() {
319        let mut bus = Bus::new(Level::Low);
320        bus.chip(Level::Low);
321        bus.bits(0x81, 0, SpiMode::Mode1, 8);
322        bus.chip(Level::High);
323
324        let frames = spi(&bus.sck, &bus.mosi, None, &bus.cs, SpiMode::Mode1);
325        assert_eq!(frames.len(), 1);
326        assert_eq!(frames[0].bytes, vec![0x81]);
327        assert!(frames[0].miso.is_empty());
328        assert_eq!(frames[0].text, "0x81");
329    }
330
331    #[test]
332    fn cs_held_low_opens_at_the_first_clock_change() {
333        let mut bus = Bus::new(Level::Low);
334        bus.cs = vec![(0, Level::Low)];
335        bus.bits(0x55, 0, SpiMode::Mode0, 8);
336
337        let frames = spi(&bus.sck, &bus.mosi, None, &bus.cs, SpiMode::Mode0);
338        assert_eq!(frames.len(), 1);
339        assert_eq!(frames[0].bytes, vec![0x55]);
340        // First sample is the first rising edge, one half period after data.
341        assert_eq!(frames[0].at, 2 * H);
342    }
343
344    #[test]
345    fn trailing_partial_byte_is_dropped() {
346        let mut bus = Bus::new(Level::Low);
347        bus.chip(Level::Low);
348        bus.bits(0x9f, 0, SpiMode::Mode0, 8);
349        bus.bits(0b1010, 0, SpiMode::Mode0, 4);
350        bus.chip(Level::High);
351
352        let frames = spi(&bus.sck, &bus.mosi, None, &bus.cs, SpiMode::Mode0);
353        assert_eq!(frames.len(), 1);
354        assert_eq!(frames[0].bytes, vec![0x9f]);
355        assert_eq!(frames[0].error, None);
356    }
357
358    #[test]
359    fn unterminated_cs_closes_at_the_last_change() {
360        let mut bus = Bus::new(Level::Low);
361        bus.chip(Level::Low);
362        bus.bits(0x3c, 0, SpiMode::Mode0, 8);
363
364        let frames = spi(&bus.sck, &bus.mosi, None, &bus.cs, SpiMode::Mode0);
365        assert_eq!(frames.len(), 1);
366        assert_eq!(frames[0].bytes, vec![0x3c]);
367        assert_eq!(frames[0].end, bus.sck.last().unwrap().0);
368    }
369
370    #[test]
371    fn missing_channels_yield_nothing() {
372        assert!(spi(&[], &[], None, &[], SpiMode::Mode0).is_empty());
373        assert!(spi(&[(0, Level::Low)], &[], None, &[], SpiMode::Mode0).is_empty());
374        assert!(spi(&[], &[], None, &[(0, Level::High)], SpiMode::Mode0).is_empty());
375    }
376}