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(
155 probes: &[Probe],
156 trace: &[(Tick, u16, Level)],
157 analog: &[(Tick, u16, f64)],
158 initial: &[Level],
159 start: Option<Tick>,
160) -> Vec<Channel> {
161 probes
162 .iter()
163 .map(|probe| {
164 let mut series = Series::default();
165 let level = initial
170 .get(usize::from(probe.net))
171 .copied()
172 .unwrap_or(Level::HighZ);
173 if let Some(start) = start {
174 series.digital.push((start, level));
175 }
176 for &(tick, net, level) in trace {
177 if net == probe.net {
178 series.digital.push((tick, level));
179 }
180 }
181 for &(tick, net, volts) in analog {
182 if net == probe.net {
183 series.volts.push((tick, volts));
184 }
185 }
186 let measured = measure(&series);
187 Channel {
188 probe: probe.clone(),
189 series,
190 measured,
191 }
192 })
193 .collect()
194}
195
196fn held_level(points: &[(Tick, Level)], at: Tick) -> Option<Level> {
198 let count = points.partition_point(|&(tick, _)| tick <= at);
199 count.checked_sub(1).map(|index| points[index].1)
200}
201
202fn held_volts(points: &[(Tick, f64)], at: Tick) -> Option<f64> {
204 let count = points.partition_point(|&(tick, _)| tick <= at);
205 count.checked_sub(1).map(|index| points[index].1)
206}
207
208pub fn to_csv(channels: &[Channel]) -> String {
214 let mut csv = String::from("time_ns");
215 for channel in channels {
216 csv.push(',');
217 csv.push_str(&channel.probe.name);
218 if !channel.series.volts.is_empty() {
219 csv.push(',');
220 csv.push_str(&channel.probe.name);
221 csv.push_str("_volts");
222 }
223 }
224 csv.push('\n');
225
226 let mut times = Vec::new();
229 for channel in channels {
230 times.extend(channel.series.digital.iter().map(|&(tick, _)| tick));
231 times.extend(channel.series.volts.iter().map(|&(tick, _)| tick));
232 }
233 times.sort_unstable();
234 times.dedup();
235
236 for tick in times {
237 csv.push_str(&tick.to_string());
238 for channel in channels {
239 csv.push(',');
240 if let Some(level) = held_level(&channel.series.digital, tick) {
241 csv.push(match level {
242 Level::High => '1',
243 Level::Low => '0',
244 Level::HighZ => 'z',
245 });
246 }
247 if !channel.series.volts.is_empty() {
248 csv.push(',');
249 if let Some(volts) = held_volts(&channel.series.volts, tick) {
250 csv.push_str(&format!("{volts:.6}"));
251 }
252 }
253 }
254 csv.push('\n');
255 }
256
257 csv
258}
259
260pub fn summary(channel: &Channel) -> String {
263 let name = &channel.probe.name;
264 let measured = &channel.measured;
265
266 if measured.edges == 0 {
267 let level = channel
268 .series
269 .digital
270 .last()
271 .map_or(Level::HighZ, |&(_, level)| level);
272 return format!("{name}: no edges (level {})", level_char(level));
273 }
274
275 let mut parts = Vec::new();
276 if let Some(hz) = measured.frequency_hz {
277 parts.push(human_hz(hz));
278 }
279 if let Some(duty) = measured.duty {
280 parts.push(format!("duty {:.1}%", duty * 100.0));
281 }
282 parts.push(format!("{} edges", measured.edges));
283 if let (Some(shortest), Some(longest)) = (measured.min_pulse_ns, measured.max_pulse_ns) {
284 parts.push(format!(
285 "pulse {}..{}",
286 human_duration(shortest),
287 human_duration(longest)
288 ));
289 }
290 if let (Some(min), Some(max)) = (measured.min_volts, measured.max_volts)
291 && !channel.series.volts.is_empty()
292 {
293 parts.push(format!("{min:.3}..{max:.3} V"));
294 }
295 format!("{name}: {}", parts.join(", "))
296}
297
298fn level_char(level: Level) -> char {
299 match level {
300 Level::High => '1',
301 Level::Low => '0',
302 Level::HighZ => 'z',
303 }
304}
305
306fn human_hz(hz: f64) -> String {
307 if hz >= 1_000_000.0 {
308 format!("{:.3} MHz", hz / 1_000_000.0)
309 } else if hz >= 1_000.0 {
310 format!("{:.3} kHz", hz / 1_000.0)
311 } else {
312 format!("{hz:.3} Hz")
313 }
314}
315
316fn human_duration(ns: u64) -> String {
317 if ns >= 1_000_000 {
318 trimmed(ns as f64 / 1_000_000.0, "ms")
319 } else if ns >= 1_000 {
320 trimmed(ns as f64 / 1_000.0, "us")
321 } else {
322 format!("{ns}ns")
323 }
324}
325
326#[derive(Clone, Debug, PartialEq, Eq)]
330pub struct Trigger {
331 pub channel: String,
332 pub level: Level,
333 pub pre_ticks: Tick,
334 pub post_ticks: Tick,
335}
336
337impl Trigger {
338 pub fn find(&self, channels: &[Channel]) -> Option<Tick> {
343 let channel = channels.iter().find(|c| c.probe.name == self.channel)?;
344 let mut previous = None;
345 for &(at, level) in &channel.series.digital {
346 if level == self.level && previous.is_some_and(|p| p != level) {
347 return Some(at);
348 }
349 previous = Some(level);
350 }
351 channel
352 .series
353 .digital
354 .iter()
355 .find(|(_, level)| *level == self.level)
356 .map(|(at, _)| *at)
357 }
358}
359
360pub fn triggered(channels: &[Channel], trigger: &Trigger) -> Result<Vec<Channel>, String> {
365 let at = trigger.find(channels).ok_or_else(|| {
366 format!(
367 "trigger channel {:?} never reached {}",
368 trigger.channel,
369 level_char(trigger.level)
370 )
371 })?;
372 let start = at.saturating_sub(trigger.pre_ticks);
373 let end = if trigger.post_ticks == 0 {
374 u64::MAX
375 } else {
376 at.saturating_add(trigger.post_ticks)
377 };
378 Ok(channels
379 .iter()
380 .map(|channel| {
381 let mut digital: Vec<(Tick, Level)> = Vec::new();
382 let mut volts: Vec<(Tick, f64)> = Vec::new();
383 for &(tick, level) in &channel.series.digital {
384 if tick < start {
385 digital.clear();
386 digital.push((tick, level));
387 } else if tick <= end {
388 digital.push((tick, level));
389 }
390 }
391 for &(tick, value) in &channel.series.volts {
392 if tick < start {
393 volts.clear();
394 volts.push((tick, value));
395 } else if tick <= end {
396 volts.push((tick, value));
397 }
398 }
399 let series = Series { digital, volts };
400 Channel {
401 probe: channel.probe.clone(),
402 measured: measure(&series),
403 series,
404 }
405 })
406 .collect())
407}
408
409fn trimmed(value: f64, unit: &str) -> String {
412 let mut text = format!("{value:.3}");
413 while text.ends_with('0') {
414 text.pop();
415 }
416 if text.ends_with('.') {
417 text.pop();
418 }
419 format!("{text}{unit}")
420}
421
422#[cfg(test)]
423mod tests {
424 use super::*;
425
426 fn channel_with(name: &str, digital: &[(Tick, Level)], volts: &[(Tick, f64)]) -> Channel {
427 let series = Series {
428 digital: digital.to_vec(),
429 volts: volts.to_vec(),
430 };
431 Channel {
432 probe: Probe {
433 name: name.into(),
434 point: name.into(),
435 net: 0,
436 },
437 measured: measure(&series),
438 series,
439 }
440 }
441
442 fn channel(name: &str, digital: &[(Tick, Level)]) -> Channel {
443 channel_with(name, digital, &[])
444 }
445
446 #[test]
447 fn a_square_wave_reports_its_period_and_duty() {
448 let wave = [
449 (0, Level::Low),
450 (100, Level::High),
451 (200, Level::Low),
452 (300, Level::High),
453 (400, Level::Low),
454 ];
455 let measured = channel("pwm", &wave).measured;
456 assert_eq!(measured.edges, 4);
457 assert_eq!(measured.high_ns, 200);
458 assert_eq!(measured.low_ns, 200);
459 assert_eq!(measured.frequency_hz, Some(5_000_000.0));
460 assert_eq!(measured.duty, Some(0.5));
461 assert_eq!(measured.min_pulse_ns, Some(100));
462 assert_eq!(measured.max_pulse_ns, Some(100));
463 }
464
465 #[test]
466 fn a_short_pulse_sets_the_pulse_range() {
467 let wave = [
468 (0, Level::Low),
469 (100, Level::High),
470 (120, Level::Low),
471 (220, Level::High),
472 (320, Level::Low),
473 ];
474 let measured = channel("narrow", &wave).measured;
475 assert_eq!(measured.min_pulse_ns, Some(20));
476 assert_eq!(measured.max_pulse_ns, Some(100));
477 }
478
479 #[test]
480 fn a_high_z_excursion_is_not_an_edge() {
481 let wave = [
482 (0, Level::Low),
483 (100, Level::High),
484 (200, Level::HighZ),
485 (300, Level::High),
486 (400, Level::Low),
487 ];
488 let measured = channel("released", &wave).measured;
489 assert_eq!(measured.edges, 2);
490 assert_eq!(measured.high_ns, 200);
491 assert_eq!(measured.low_ns, 100);
492 assert_eq!(measured.duty, Some(200.0 / 300.0));
494 }
495
496 #[test]
497 fn channels_seed_initial_state_and_filter_by_net() {
498 let probes = [
499 Probe {
500 name: "a".into(),
501 point: "a:GPIO1".into(),
502 net: 0,
503 },
504 Probe {
505 name: "b".into(),
506 point: "b:GPIO2".into(),
507 net: 1,
508 },
509 ];
510 let trace = [
511 (10, 0, Level::High),
512 (20, 1, Level::High),
513 (30, 0, Level::Low),
514 (40, 1, Level::Low),
515 (50, 0, Level::High),
516 ];
517 let analog = [(5, 0, 1.5), (6, 1, 2.5)];
518 let initial = [Level::Low, Level::Low];
519 let built = channels(&probes, &trace, &analog, &initial, Some(0));
520
521 assert_eq!(built.len(), 2);
522 assert_eq!(
523 built[0].series.digital,
524 vec![
525 (0, Level::Low),
526 (10, Level::High),
527 (30, Level::Low),
528 (50, Level::High)
529 ]
530 );
531 assert_eq!(built[0].series.volts, vec![(5, 1.5)]);
532 assert_eq!(
533 built[1].series.digital,
534 vec![(0, Level::Low), (20, Level::High), (40, Level::Low)]
535 );
536 assert_eq!(built[1].series.volts, vec![(6, 2.5)]);
537 }
538
539 #[test]
540 fn csv_holds_values_between_changes() {
541 let pwm = channel(
542 "pwm",
543 &[(0, Level::Low), (100, Level::High), (200, Level::Low)],
544 );
545 let aout = channel_with("aout", &[(300, Level::High)], &[(0, 1.5), (150, 3.3)]);
546 let csv = to_csv(&[pwm, aout]);
547 let expected = "\
548time_ns,pwm,aout,aout_volts
5490,0,,1.500000
550100,1,,1.500000
551150,1,,3.300000
552200,0,,3.300000
553300,0,1,3.300000
554";
555 assert_eq!(csv, expected);
556 }
557
558 #[test]
559 fn csv_adds_a_volts_column_only_where_needed() {
560 let pwm = channel("pwm", &[(0, Level::Low), (100, Level::High)]);
561 assert_eq!(to_csv(&[pwm]), "time_ns,pwm\n0,0\n100,1\n");
562 }
563
564 #[test]
565 fn summary_reports_frequency_duty_pulses_and_volts() {
566 let wave = [
567 (0, Level::Low),
568 (500_000, Level::High),
569 (1_000_000, Level::Low),
570 (1_500_000, Level::High),
571 (2_000_000, Level::Low),
572 ];
573 let pwm = channel_with("pwm", &wave, &[(0, 0.0), (1_000_000, 3.3)]);
574 assert_eq!(
575 summary(&pwm),
576 "pwm: 1.000 kHz, duty 50.0%, 4 edges, pulse 500us..500us, 0.000..3.300 V"
577 );
578 }
579
580 #[test]
581 fn summary_reports_the_idle_level_without_edges() {
582 let idle = channel("idle", &[(0, Level::High)]);
583 assert_eq!(summary(&idle), "idle: no edges (level 1)");
584 let floating = channel("floating", &[(0, Level::HighZ)]);
585 assert_eq!(summary(&floating), "floating: no edges (level z)");
586 }
587
588 #[test]
589 fn a_trigger_keeps_the_history_before_its_edge() {
590 let clock = channel(
591 "sck",
592 &[
593 (0, Level::Low),
594 (100, Level::High),
595 (200, Level::Low),
596 (300, Level::High),
597 (400, Level::Low),
598 ],
599 );
600 let trigger = Trigger {
601 channel: "sck".into(),
602 level: Level::High,
603 pre_ticks: 250,
604 post_ticks: 100,
605 };
606 assert_eq!(trigger.find(std::slice::from_ref(&clock)), Some(100));
607
608 let window = triggered(&[clock], &trigger).unwrap();
609 let ticks: Vec<Tick> = window[0].series.digital.iter().map(|(t, _)| *t).collect();
610 assert_eq!(ticks, vec![0, 100, 200]);
613 assert_eq!(window[0].measured.edges, 2);
614 }
615
616 #[test]
617 fn a_trigger_that_never_fires_is_an_error() {
618 let clock = channel("sck", &[(0, Level::Low), (100, Level::High)]);
619 let trigger = Trigger {
620 channel: "sck".into(),
621 level: Level::High,
622 pre_ticks: 0,
623 post_ticks: 0,
624 };
625 assert_eq!(trigger.find(std::slice::from_ref(&clock)), Some(100));
626 let wrong = Trigger {
627 channel: "missing".into(),
628 ..trigger
629 };
630 assert!(triggered(&[clock], &wrong).is_err());
631 }
632}