1use litz_core::{Level, TICKS_PER_SEC, Tick};
11
12#[derive(Clone, Debug, PartialEq, Eq)]
14pub struct Probe {
15 pub name: String,
17 pub point: String,
19 pub net: u16,
21}
22
23#[derive(Clone, Debug, Default, PartialEq)]
25pub struct Series {
26 pub digital: Vec<(Tick, Level)>,
28 pub volts: Vec<(Tick, f64)>,
30}
31
32#[derive(Clone, Copy, Debug, Default, PartialEq)]
34pub struct Measurements {
35 pub edges: u64,
38 pub high_ns: u64,
39 pub low_ns: u64,
40 pub min_pulse_ns: Option<u64>,
42 pub max_pulse_ns: Option<u64>,
43 pub frequency_hz: Option<f64>,
45 pub duty: Option<f64>,
47 pub min_volts: Option<f64>,
48 pub max_volts: Option<f64>,
49}
50
51#[derive(Clone, Debug)]
53pub struct Channel {
54 pub probe: Probe,
55 pub series: Series,
56 pub measured: Measurements,
57}
58
59pub fn measure(series: &Series) -> Measurements {
61 let mut measured = Measurements::default();
62 let digital = &series.digital;
63
64 let mut risings = 0u64;
65 let mut first_rising = None;
66 let mut last_rising = None;
67 for pair in digital.windows(2) {
68 let (earlier, before) = pair[0];
69 let (later, after) = pair[1];
70
71 if is_driven(before) && is_driven(after) && before != after {
74 measured.edges += 1;
75 }
76 match before {
77 Level::High => measured.high_ns += later.saturating_sub(earlier),
78 Level::Low => measured.low_ns += later.saturating_sub(earlier),
79 Level::HighZ => {}
80 }
81 if before == Level::Low && after == Level::High {
82 risings += 1;
83 first_rising.get_or_insert(later);
84 last_rising = Some(later);
85 }
86 }
87
88 let mut index = 0;
92 while index < digital.len() {
93 let level = digital[index].1;
94 let mut end = index + 1;
95 while end < digital.len() && digital[end].1 == level {
96 end += 1;
97 }
98 if index > 0 && end < digital.len() && is_driven(level) {
99 let width = digital[end].0.saturating_sub(digital[index].0);
100 measured.min_pulse_ns = Some(
101 measured
102 .min_pulse_ns
103 .map_or(width, |shortest| shortest.min(width)),
104 );
105 measured.max_pulse_ns = Some(
106 measured
107 .max_pulse_ns
108 .map_or(width, |longest| longest.max(width)),
109 );
110 }
111 index = end;
112 }
113
114 if risings >= 2
115 && let (Some(first), Some(last)) = (first_rising, last_rising)
116 {
117 let span = last.saturating_sub(first);
118 if span > 0 {
119 let seconds = span as f64 / TICKS_PER_SEC as f64;
120 measured.frequency_hz = Some((risings - 1) as f64 / seconds);
121 }
122 }
123
124 let driven = measured.high_ns + measured.low_ns;
125 if driven > 0 {
126 measured.duty = Some(measured.high_ns as f64 / driven as f64);
127 }
128
129 if let Some(&(_, first)) = series.volts.first() {
130 let mut min = first;
131 let mut max = first;
132 for &(_, volts) in &series.volts[1..] {
133 min = min.min(volts);
134 max = max.max(volts);
135 }
136 measured.min_volts = Some(min);
137 measured.max_volts = Some(max);
138 }
139
140 measured
141}
142
143fn is_driven(level: Level) -> bool {
144 matches!(level, Level::High | Level::Low)
145}
146
147pub fn channels(
151 probes: &[Probe],
152 trace: &[(Tick, u16, Level)],
153 analog: &[(Tick, u16, f64)],
154 initial: &[Level],
155 start: Tick,
156) -> Vec<Channel> {
157 probes
158 .iter()
159 .map(|probe| {
160 let mut series = Series::default();
161 if let Some(&level) = initial.get(usize::from(probe.net)) {
162 series.digital.push((start, level));
163 }
164 for &(tick, net, level) in trace {
165 if net == probe.net {
166 series.digital.push((tick, level));
167 }
168 }
169 for &(tick, net, volts) in analog {
170 if net == probe.net {
171 series.volts.push((tick, volts));
172 }
173 }
174 let measured = measure(&series);
175 Channel {
176 probe: probe.clone(),
177 series,
178 measured,
179 }
180 })
181 .collect()
182}
183
184fn held_level(points: &[(Tick, Level)], at: Tick) -> Option<Level> {
186 let count = points.partition_point(|&(tick, _)| tick <= at);
187 count.checked_sub(1).map(|index| points[index].1)
188}
189
190fn held_volts(points: &[(Tick, f64)], at: Tick) -> Option<f64> {
192 let count = points.partition_point(|&(tick, _)| tick <= at);
193 count.checked_sub(1).map(|index| points[index].1)
194}
195
196pub fn to_csv(channels: &[Channel]) -> String {
202 let mut csv = String::from("time_ns");
203 for channel in channels {
204 csv.push(',');
205 csv.push_str(&channel.probe.name);
206 if !channel.series.volts.is_empty() {
207 csv.push(',');
208 csv.push_str(&channel.probe.name);
209 csv.push_str("_volts");
210 }
211 }
212 csv.push('\n');
213
214 let mut times = Vec::new();
217 for channel in channels {
218 times.extend(channel.series.digital.iter().map(|&(tick, _)| tick));
219 times.extend(channel.series.volts.iter().map(|&(tick, _)| tick));
220 }
221 times.sort_unstable();
222 times.dedup();
223
224 for tick in times {
225 csv.push_str(&tick.to_string());
226 for channel in channels {
227 csv.push(',');
228 if let Some(level) = held_level(&channel.series.digital, tick) {
229 csv.push(match level {
230 Level::High => '1',
231 Level::Low => '0',
232 Level::HighZ => 'z',
233 });
234 }
235 if !channel.series.volts.is_empty() {
236 csv.push(',');
237 if let Some(volts) = held_volts(&channel.series.volts, tick) {
238 csv.push_str(&format!("{volts:.6}"));
239 }
240 }
241 }
242 csv.push('\n');
243 }
244
245 csv
246}
247
248pub fn summary(channel: &Channel) -> String {
251 let name = &channel.probe.name;
252 let measured = &channel.measured;
253
254 if measured.edges == 0 {
255 let level = channel
256 .series
257 .digital
258 .last()
259 .map_or(Level::HighZ, |&(_, level)| level);
260 return format!("{name}: no edges (level {})", level_char(level));
261 }
262
263 let mut parts = Vec::new();
264 if let Some(hz) = measured.frequency_hz {
265 parts.push(human_hz(hz));
266 }
267 if let Some(duty) = measured.duty {
268 parts.push(format!("duty {:.1}%", duty * 100.0));
269 }
270 parts.push(format!("{} edges", measured.edges));
271 if let (Some(shortest), Some(longest)) = (measured.min_pulse_ns, measured.max_pulse_ns) {
272 parts.push(format!(
273 "pulse {}..{}",
274 human_duration(shortest),
275 human_duration(longest)
276 ));
277 }
278 if let (Some(min), Some(max)) = (measured.min_volts, measured.max_volts)
279 && !channel.series.volts.is_empty()
280 {
281 parts.push(format!("{min:.3}..{max:.3} V"));
282 }
283 format!("{name}: {}", parts.join(", "))
284}
285
286fn level_char(level: Level) -> char {
287 match level {
288 Level::High => '1',
289 Level::Low => '0',
290 Level::HighZ => 'z',
291 }
292}
293
294fn human_hz(hz: f64) -> String {
295 if hz >= 1_000_000.0 {
296 format!("{:.3} MHz", hz / 1_000_000.0)
297 } else if hz >= 1_000.0 {
298 format!("{:.3} kHz", hz / 1_000.0)
299 } else {
300 format!("{hz:.3} Hz")
301 }
302}
303
304fn human_duration(ns: u64) -> String {
305 if ns >= 1_000_000 {
306 trimmed(ns as f64 / 1_000_000.0, "ms")
307 } else if ns >= 1_000 {
308 trimmed(ns as f64 / 1_000.0, "us")
309 } else {
310 format!("{ns}ns")
311 }
312}
313
314#[derive(Clone, Debug, PartialEq, Eq)]
318pub struct Trigger {
319 pub channel: String,
320 pub level: Level,
321 pub pre_ticks: Tick,
322 pub post_ticks: Tick,
323}
324
325impl Trigger {
326 pub fn find(&self, channels: &[Channel]) -> Option<Tick> {
331 let channel = channels.iter().find(|c| c.probe.name == self.channel)?;
332 let mut previous = None;
333 for &(at, level) in &channel.series.digital {
334 if level == self.level && previous.is_some_and(|p| p != level) {
335 return Some(at);
336 }
337 previous = Some(level);
338 }
339 channel
340 .series
341 .digital
342 .iter()
343 .find(|(_, level)| *level == self.level)
344 .map(|(at, _)| *at)
345 }
346}
347
348pub fn triggered(channels: &[Channel], trigger: &Trigger) -> Result<Vec<Channel>, String> {
353 let at = trigger.find(channels).ok_or_else(|| {
354 format!(
355 "trigger channel {:?} never reached {}",
356 trigger.channel,
357 level_char(trigger.level)
358 )
359 })?;
360 let start = at.saturating_sub(trigger.pre_ticks);
361 let end = if trigger.post_ticks == 0 {
362 u64::MAX
363 } else {
364 at.saturating_add(trigger.post_ticks)
365 };
366 Ok(channels
367 .iter()
368 .map(|channel| {
369 let mut digital: Vec<(Tick, Level)> = Vec::new();
370 let mut volts: Vec<(Tick, f64)> = Vec::new();
371 for &(tick, level) in &channel.series.digital {
372 if tick < start {
373 digital.clear();
374 digital.push((tick, level));
375 } else if tick <= end {
376 digital.push((tick, level));
377 }
378 }
379 for &(tick, value) in &channel.series.volts {
380 if tick < start {
381 volts.clear();
382 volts.push((tick, value));
383 } else if tick <= end {
384 volts.push((tick, value));
385 }
386 }
387 let series = Series { digital, volts };
388 Channel {
389 probe: channel.probe.clone(),
390 measured: measure(&series),
391 series,
392 }
393 })
394 .collect())
395}
396
397fn trimmed(value: f64, unit: &str) -> String {
400 let mut text = format!("{value:.3}");
401 while text.ends_with('0') {
402 text.pop();
403 }
404 if text.ends_with('.') {
405 text.pop();
406 }
407 format!("{text}{unit}")
408}
409
410#[cfg(test)]
411mod tests {
412 use super::*;
413
414 fn channel_with(name: &str, digital: &[(Tick, Level)], volts: &[(Tick, f64)]) -> Channel {
415 let series = Series {
416 digital: digital.to_vec(),
417 volts: volts.to_vec(),
418 };
419 Channel {
420 probe: Probe {
421 name: name.into(),
422 point: name.into(),
423 net: 0,
424 },
425 measured: measure(&series),
426 series,
427 }
428 }
429
430 fn channel(name: &str, digital: &[(Tick, Level)]) -> Channel {
431 channel_with(name, digital, &[])
432 }
433
434 #[test]
435 fn a_square_wave_reports_its_period_and_duty() {
436 let wave = [
437 (0, Level::Low),
438 (100, Level::High),
439 (200, Level::Low),
440 (300, Level::High),
441 (400, Level::Low),
442 ];
443 let measured = channel("pwm", &wave).measured;
444 assert_eq!(measured.edges, 4);
445 assert_eq!(measured.high_ns, 200);
446 assert_eq!(measured.low_ns, 200);
447 assert_eq!(measured.frequency_hz, Some(5_000_000.0));
448 assert_eq!(measured.duty, Some(0.5));
449 assert_eq!(measured.min_pulse_ns, Some(100));
450 assert_eq!(measured.max_pulse_ns, Some(100));
451 }
452
453 #[test]
454 fn a_short_pulse_sets_the_pulse_range() {
455 let wave = [
456 (0, Level::Low),
457 (100, Level::High),
458 (120, Level::Low),
459 (220, Level::High),
460 (320, Level::Low),
461 ];
462 let measured = channel("narrow", &wave).measured;
463 assert_eq!(measured.min_pulse_ns, Some(20));
464 assert_eq!(measured.max_pulse_ns, Some(100));
465 }
466
467 #[test]
468 fn a_high_z_excursion_is_not_an_edge() {
469 let wave = [
470 (0, Level::Low),
471 (100, Level::High),
472 (200, Level::HighZ),
473 (300, Level::High),
474 (400, Level::Low),
475 ];
476 let measured = channel("released", &wave).measured;
477 assert_eq!(measured.edges, 2);
478 assert_eq!(measured.high_ns, 200);
479 assert_eq!(measured.low_ns, 100);
480 assert_eq!(measured.duty, Some(200.0 / 300.0));
482 }
483
484 #[test]
485 fn channels_seed_initial_state_and_filter_by_net() {
486 let probes = [
487 Probe {
488 name: "a".into(),
489 point: "a:GPIO1".into(),
490 net: 0,
491 },
492 Probe {
493 name: "b".into(),
494 point: "b:GPIO2".into(),
495 net: 1,
496 },
497 ];
498 let trace = [
499 (10, 0, Level::High),
500 (20, 1, Level::High),
501 (30, 0, Level::Low),
502 (40, 1, Level::Low),
503 (50, 0, Level::High),
504 ];
505 let analog = [(5, 0, 1.5), (6, 1, 2.5)];
506 let initial = [Level::Low, Level::Low];
507 let built = channels(&probes, &trace, &analog, &initial, 0);
508
509 assert_eq!(built.len(), 2);
510 assert_eq!(
511 built[0].series.digital,
512 vec![
513 (0, Level::Low),
514 (10, Level::High),
515 (30, Level::Low),
516 (50, Level::High)
517 ]
518 );
519 assert_eq!(built[0].series.volts, vec![(5, 1.5)]);
520 assert_eq!(
521 built[1].series.digital,
522 vec![(0, Level::Low), (20, Level::High), (40, Level::Low)]
523 );
524 assert_eq!(built[1].series.volts, vec![(6, 2.5)]);
525 }
526
527 #[test]
528 fn csv_holds_values_between_changes() {
529 let pwm = channel(
530 "pwm",
531 &[(0, Level::Low), (100, Level::High), (200, Level::Low)],
532 );
533 let aout = channel_with("aout", &[(300, Level::High)], &[(0, 1.5), (150, 3.3)]);
534 let csv = to_csv(&[pwm, aout]);
535 let expected = "\
536time_ns,pwm,aout,aout_volts
5370,0,,1.500000
538100,1,,1.500000
539150,1,,3.300000
540200,0,,3.300000
541300,0,1,3.300000
542";
543 assert_eq!(csv, expected);
544 }
545
546 #[test]
547 fn csv_adds_a_volts_column_only_where_needed() {
548 let pwm = channel("pwm", &[(0, Level::Low), (100, Level::High)]);
549 assert_eq!(to_csv(&[pwm]), "time_ns,pwm\n0,0\n100,1\n");
550 }
551
552 #[test]
553 fn summary_reports_frequency_duty_pulses_and_volts() {
554 let wave = [
555 (0, Level::Low),
556 (500_000, Level::High),
557 (1_000_000, Level::Low),
558 (1_500_000, Level::High),
559 (2_000_000, Level::Low),
560 ];
561 let pwm = channel_with("pwm", &wave, &[(0, 0.0), (1_000_000, 3.3)]);
562 assert_eq!(
563 summary(&pwm),
564 "pwm: 1.000 kHz, duty 50.0%, 4 edges, pulse 500us..500us, 0.000..3.300 V"
565 );
566 }
567
568 #[test]
569 fn summary_reports_the_idle_level_without_edges() {
570 let idle = channel("idle", &[(0, Level::High)]);
571 assert_eq!(summary(&idle), "idle: no edges (level 1)");
572 let floating = channel("floating", &[(0, Level::HighZ)]);
573 assert_eq!(summary(&floating), "floating: no edges (level z)");
574 }
575
576 #[test]
577 fn a_trigger_keeps_the_history_before_its_edge() {
578 let clock = channel(
579 "sck",
580 &[
581 (0, Level::Low),
582 (100, Level::High),
583 (200, Level::Low),
584 (300, Level::High),
585 (400, Level::Low),
586 ],
587 );
588 let trigger = Trigger {
589 channel: "sck".into(),
590 level: Level::High,
591 pre_ticks: 250,
592 post_ticks: 100,
593 };
594 assert_eq!(trigger.find(std::slice::from_ref(&clock)), Some(100));
595
596 let window = triggered(&[clock], &trigger).unwrap();
597 let ticks: Vec<Tick> = window[0].series.digital.iter().map(|(t, _)| *t).collect();
598 assert_eq!(ticks, vec![0, 100, 200]);
601 assert_eq!(window[0].measured.edges, 2);
602 }
603
604 #[test]
605 fn a_trigger_that_never_fires_is_an_error() {
606 let clock = channel("sck", &[(0, Level::Low), (100, Level::High)]);
607 let trigger = Trigger {
608 channel: "sck".into(),
609 level: Level::High,
610 pre_ticks: 0,
611 post_ticks: 0,
612 };
613 assert_eq!(trigger.find(std::slice::from_ref(&clock)), Some(100));
614 let wrong = Trigger {
615 channel: "missing".into(),
616 ..trigger
617 };
618 assert!(triggered(&[clock], &wrong).is_err());
619 }
620}