Skip to main content

litz_decode/
i2c.rs

1//! I2C decoding for 7-bit addressed buses.
2//!
3//! Ten-bit addressing is not decoded: the first byte is always treated as
4//! `address << 1 | direction`, which misreads a 10-bit address as a 7-bit one.
5
6use litz_core::{Level, Tick};
7
8use crate::{Frame, merge_events};
9
10const SCL: u8 = 0;
11const SDA: u8 = 1;
12
13/// Decode complete I2C transactions from SDA and SCL recordings.
14///
15/// START and STOP are SDA transitions while SCL is high. Data changes while
16/// SCL is low are ignored. A repeated START closes the open transaction (with
17/// no error) and opens the next one at the same tick.
18pub fn i2c(sda: &[(Tick, Level)], scl: &[(Tick, Level)]) -> Vec<Frame> {
19    if sda.is_empty() || scl.is_empty() {
20        return Vec::new();
21    }
22
23    // SCL has priority on ties so a simultaneous clock rise and data change
24    // is seen as an enabled bus, matching how a device latches the bit.
25    let events = merge_events(scl, SCL, sda, SDA);
26
27    let mut sda_level = sda.first().map(|&(_, level)| level);
28    let mut scl_level = scl.first().map(|&(_, level)| level);
29    let mut open: Option<Transaction> = None;
30    let mut frames = Vec::new();
31    let mut last_tick = 0;
32
33    for (index, &(tick, channel, level)) in events.iter().enumerate() {
34        last_tick = tick;
35        if channel == SCL {
36            scl_level = Some(level);
37            if level == Level::High
38                && let Some(tx) = open.as_mut()
39            {
40                // A data change at this same tick has not been visited yet,
41                // but the device sees the settled levels, so fold it in.
42                let sampled = events[index + 1..]
43                    .iter()
44                    .take_while(|event| event.0 == tick)
45                    .find(|event| event.1 == SDA)
46                    .map(|event| event.2)
47                    .or(sda_level);
48                tx.push_bit(sampled);
49            }
50        } else {
51            let was = sda_level;
52            sda_level = Some(level);
53            if scl_level != Some(Level::High) {
54                continue;
55            }
56            if was == Some(Level::High) && level == Level::Low {
57                // START, possibly repeated: end the previous transaction here.
58                if let Some(tx) = open.take() {
59                    frames.push(tx.finish(tick, false, None));
60                }
61                open = Some(Transaction::new(tick));
62            } else if was == Some(Level::Low)
63                && level == Level::High
64                && let Some(tx) = open.take()
65            {
66                frames.push(tx.finish(tick, true, None));
67            }
68        }
69    }
70
71    if let Some(tx) = open {
72        frames.push(tx.finish(last_tick, false, Some("no stop condition")));
73    }
74    frames
75}
76
77struct Transaction {
78    start: Tick,
79    groups: Vec<(u8, bool)>,
80    current: u8,
81    bits: u8,
82}
83
84impl Transaction {
85    fn new(start: Tick) -> Self {
86        Self {
87            start,
88            groups: Vec::new(),
89            current: 0,
90            bits: 0,
91        }
92    }
93
94    /// Feed one sampled SCL-high level. Bits are MSB first; every ninth bit
95    /// is the acknowledge, low when the receiver acknowledged.
96    fn push_bit(&mut self, level: Option<Level>) {
97        if self.bits < 8 {
98            if level == Some(Level::High) {
99                self.current |= 1 << (7 - self.bits);
100            }
101            self.bits += 1;
102        } else {
103            let ack = level == Some(Level::Low);
104            self.groups.push((self.current, ack));
105            self.current = 0;
106            self.bits = 0;
107        }
108    }
109
110    fn finish(self, end: Tick, stopped: bool, error: Option<&str>) -> Frame {
111        let mut bytes = Vec::new();
112        let mut items = Vec::new();
113        if let Some(&(address_byte, _)) = self.groups.first() {
114            let address = address_byte >> 1;
115            let direction = if address_byte & 1 == 0 {
116                "write"
117            } else {
118                "read"
119            };
120            items.push(format!("start 0x{address:02x} {direction}"));
121            for &(byte, ack) in &self.groups[1..] {
122                bytes.push(byte);
123                items.push(format!("0x{byte:02x} {}", if ack { "ack" } else { "nack" }));
124            }
125        } else {
126            // A START without a complete address byte: report what is known.
127            items.push("start".to_string());
128        }
129        if stopped {
130            items.push("stop".to_string());
131        }
132        Frame {
133            at: self.start,
134            end,
135            bytes,
136            miso: Vec::new(),
137            text: items.join(", "),
138            error: error.map(|message| message.to_string()),
139        }
140    }
141}
142
143#[cfg(test)]
144mod tests {
145    use super::*;
146
147    const HALF: Tick = 10;
148
149    struct Bus {
150        sda: Vec<(Tick, Level)>,
151        scl: Vec<(Tick, Level)>,
152        tick: Tick,
153    }
154
155    impl Bus {
156        fn idle() -> Self {
157            Self {
158                sda: vec![(0, Level::High)],
159                scl: vec![(0, Level::High)],
160                tick: HALF,
161            }
162        }
163
164        fn set(line: &mut Vec<(Tick, Level)>, tick: Tick, level: Level) {
165            if line.last().map(|&(_, last)| last) != Some(level) {
166                line.push((tick, level));
167            }
168        }
169
170        fn both(&mut self, sda: Option<Level>, scl: Option<Level>) {
171            if let Some(level) = scl {
172                Self::set(&mut self.scl, self.tick, level);
173            }
174            if let Some(level) = sda {
175                Self::set(&mut self.sda, self.tick, level);
176            }
177            self.tick += HALF;
178        }
179
180        fn start(&mut self) -> Tick {
181            let at = self.tick;
182            self.both(Some(Level::Low), None);
183            self.both(None, Some(Level::Low));
184            at
185        }
186
187        fn repeated_start(&mut self) -> Tick {
188            self.both(Some(Level::High), None);
189            self.both(None, Some(Level::High));
190            let at = self.tick;
191            self.both(Some(Level::Low), None);
192            self.both(None, Some(Level::Low));
193            at
194        }
195
196        fn bit(&mut self, value: bool) {
197            let level = if value { Level::High } else { Level::Low };
198            self.both(Some(level), None);
199            self.both(None, Some(Level::High));
200            self.both(None, Some(Level::Low));
201        }
202
203        fn write_byte(&mut self, byte: u8) {
204            for n in (0..8).rev() {
205                self.bit(byte >> n & 1 == 1);
206            }
207        }
208
209        fn ack(&mut self, ack: bool) {
210            let level = if ack { Level::Low } else { Level::High };
211            self.both(Some(level), None);
212            self.both(None, Some(Level::High));
213            self.both(None, Some(Level::Low));
214        }
215
216        fn stop(&mut self) -> Tick {
217            self.both(Some(Level::Low), None);
218            self.both(None, Some(Level::High));
219            let at = self.tick;
220            self.both(Some(Level::High), None);
221            at
222        }
223
224        fn decode(&self) -> Vec<Frame> {
225            i2c(&self.sda, &self.scl)
226        }
227    }
228
229    #[test]
230    fn decodes_write_with_ack() {
231        let mut bus = Bus::idle();
232        let start = bus.start();
233        bus.write_byte(0x3c << 1);
234        bus.ack(true);
235        bus.write_byte(0x00);
236        bus.ack(true);
237        bus.write_byte(0xaf);
238        bus.ack(false);
239        let stop = bus.stop();
240
241        let frames = bus.decode();
242        assert_eq!(frames.len(), 1);
243        assert_eq!(frames[0].at, start);
244        assert_eq!(frames[0].end, stop);
245        assert_eq!(frames[0].bytes, vec![0x00, 0xaf]);
246        assert_eq!(
247            frames[0].text,
248            "start 0x3c write, 0x00 ack, 0xaf nack, stop"
249        );
250        assert_eq!(frames[0].error, None);
251    }
252
253    #[test]
254    fn decodes_read_with_nack() {
255        let mut bus = Bus::idle();
256        bus.start();
257        bus.write_byte(0x50 << 1 | 1);
258        bus.ack(true);
259        bus.write_byte(0x42);
260        bus.ack(false);
261        bus.stop();
262
263        let frames = bus.decode();
264        assert_eq!(frames.len(), 1);
265        assert_eq!(frames[0].bytes, vec![0x42]);
266        assert_eq!(frames[0].text, "start 0x50 read, 0x42 nack, stop");
267    }
268
269    #[test]
270    fn repeated_start_closes_the_previous_transaction() {
271        let mut bus = Bus::idle();
272        bus.start();
273        bus.write_byte(0x3c << 1);
274        bus.ack(true);
275        let restart = bus.repeated_start();
276        bus.write_byte(0x50 << 1 | 1);
277        bus.ack(true);
278        bus.write_byte(0x42);
279        bus.ack(false);
280        let stop = bus.stop();
281
282        let frames = bus.decode();
283        assert_eq!(frames.len(), 2);
284        assert_eq!(frames[0].end, restart);
285        assert_eq!(frames[0].text, "start 0x3c write");
286        assert_eq!(frames[0].error, None);
287        assert_eq!(frames[1].at, restart);
288        assert_eq!(frames[1].end, stop);
289        assert_eq!(frames[1].text, "start 0x50 read, 0x42 nack, stop");
290    }
291
292    #[test]
293    fn transaction_without_stop_is_reported() {
294        let mut bus = Bus::idle();
295        bus.start();
296        bus.write_byte(0x3c << 1);
297        bus.ack(true);
298        bus.write_byte(0x55);
299        bus.ack(true);
300
301        let frames = bus.decode();
302        assert_eq!(frames.len(), 1);
303        assert_eq!(frames[0].bytes, vec![0x55]);
304        assert_eq!(frames[0].error.as_deref(), Some("no stop condition"));
305        assert_eq!(frames[0].text, "start 0x3c write, 0x55 ack");
306        assert_eq!(frames[0].end, bus.scl.last().unwrap().0);
307    }
308
309    #[test]
310    fn empty_or_one_sided_input_yields_nothing() {
311        assert!(i2c(&[], &[]).is_empty());
312        assert!(i2c(&[(0, Level::High)], &[]).is_empty());
313        assert!(i2c(&[], &[(0, Level::High)]).is_empty());
314    }
315}