From 74f9d986e7f9738e666fd285729169f24b5c8b9e Mon Sep 17 00:00:00 2001 From: HalfSweet Date: Sun, 29 Nov 2026 22:07:41 +0800 Subject: [PATCH 01/32] build(tooling): allow cli scope in commitlint Add the cli scope to commitlint.config.js for the standalone hsync-cli crate. --- commitlint.config.js | 1 + 1 file changed, 1 insertion(+) diff --git a/commitlint.config.js b/commitlint.config.js index ba1e0036..b60932f1 100644 --- a/commitlint.config.js +++ b/commitlint.config.js @@ -21,6 +21,7 @@ export default { 'decode', 'fileio', 'session', + 'cli', 'app', // The uiharu decode engine (uiharu/) 'uiharu', From 4b5f387a90c9f6516eda005a584c5111be9f7313 Mon Sep 17 00:00:00 2001 From: HalfSweet Date: Sun, 29 Nov 2026 22:08:24 +0800 Subject: [PATCH 02/32] feat(capture): add channel profiling, transitions and timing queries Add structured signal profiling, lossless multi-channel transitions, glitch scanning and cross-channel edge-delta measurement primitives to hsync-capture. --- crates/hsync-capture/src/lib.rs | 6 + crates/hsync-capture/src/profile.rs | 843 ++++++++++++++++++++++++++++ 2 files changed, 849 insertions(+) create mode 100644 crates/hsync-capture/src/profile.rs diff --git a/crates/hsync-capture/src/lib.rs b/crates/hsync-capture/src/lib.rs index 7d738e68..e9162910 100644 --- a/crates/hsync-capture/src/lib.rs +++ b/crates/hsync-capture/src/lib.rs @@ -9,6 +9,7 @@ mod capture; mod channel; mod ingest; mod pattern; +mod profile; mod summary; mod words; @@ -17,4 +18,9 @@ pub use capture::{CaptureInfo, LogicCapture}; pub use channel::{ChannelData, EdgeCount, Pulse, cell}; pub use ingest::CrossDeinterleaver; pub use pattern::{PatternCondition, PatternLevel}; +pub use profile::{ + AnalogProfile, BurstInterval, ChannelActivity, ChannelProfile, DEFAULT_MAX_BURSTS, + DEFAULT_PROFILE_EDGE_LIMIT, EdgeDeltaHit, EdgeDeltaSummary, EdgeKind, GlitchHit, + ProfileOptions, PulseDistribution, TransitionRow, +}; pub use words::{CHUNK_SAMPLES, CHUNK_WORDS, ChunkView}; diff --git a/crates/hsync-capture/src/profile.rs b/crates/hsync-capture/src/profile.rs new file mode 100644 index 00000000..e5f09065 --- /dev/null +++ b/crates/hsync-capture/src/profile.rs @@ -0,0 +1,843 @@ +//! Signal profiling, lossless transition extraction, glitch scanning and cross-channel timing +//! queries over a [`LogicCapture`]. +//! +//! Every function here returns structured measurements without natural-language text so that +//! both graphical tools and command-line or agent clients can build on the same primitives. + +use std::ops::Range; + +use hsync_core::{ChannelIndex, SampleIndex}; +use serde::Serialize; + +use crate::capture::LogicCapture; +use crate::channel::ChannelData; + +/// Default maximum number of edges inspected per channel when building pulse statistics. +pub const DEFAULT_PROFILE_EDGE_LIMIT: usize = 65_536; + +/// Default maximum number of activity bursts reported per channel. +pub const DEFAULT_MAX_BURSTS: usize = 32; + +/// High-level state of a logic channel over an inspected range. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum ChannelActivity { + /// The inspected range holds no samples. + Empty, + /// Every sample in the range is low (`0`). + ConstantLow, + /// Every sample in the range is high (`1`). + ConstantHigh, + /// The channel transitions at least once in the range. + Active, +} + +/// Summary statistics for a set of pulse widths or periods, measured in samples. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PulseDistribution { + /// Number of intervals included in the distribution. + pub count: u64, + pub min: SampleIndex, + pub p5: SampleIndex, + pub median: SampleIndex, + pub p95: SampleIndex, + pub max: SampleIndex, + pub mean: f64, + /// Whether the channel had more edges than the profiling limit allowed. + pub sampled: bool, +} + +/// A contiguous stretch of transitions separated from neighbouring bursts by an idle gap. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct BurstInterval { + /// Sample of the first edge in the burst. + pub start: SampleIndex, + /// Sample of the last edge in the burst. + pub end: SampleIndex, + /// Number of edges inside the burst. + pub edges: u64, +} + +/// Profiling summary of one logic channel over a sample range. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ChannelProfile { + pub channel: ChannelIndex, + pub activity: ChannelActivity, + pub initial_level: Option, + pub final_level: Option, + pub rising: u64, + pub falling: u64, + pub first_edge: Option, + pub last_edge: Option, + /// Fraction of samples in the inspected range that are high (`0.0..=1.0`). + pub duty_cycle_high: Option, + pub high_pulses: Option, + pub low_pulses: Option, + pub periods: Option, + /// Estimated clock or repeat frequency in Hz from the median rising-to-rising period. + pub estimated_frequency_hz: Option, + /// Estimated bit rate in Hz from the short-pulse width (p5 of all complete pulses). + pub estimated_min_bit_hz: Option, + /// Idle gap threshold in samples used to split activity bursts. + pub burst_gap_samples: Option, + pub bursts: Vec, + /// Whether more bursts existed beyond the configured burst or edge limit. + pub bursts_truncated: bool, +} + +/// Profiling summary of one analog channel over a sample range. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AnalogProfile { + pub channel: ChannelIndex, + pub sample_count: u64, + pub min_volts: f32, + pub max_volts: f32, + pub mean_volts: f64, +} + +/// One row of a lossless multi-channel transition listing. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct TransitionRow { + pub sample: SampleIndex, + /// Samples elapsed since the previous row; `None` for the initial state row at `from`. + pub delta: Option, + /// Levels of the requested channels at `sample`, in the caller's channel order. + pub levels: Vec, + /// Channels among the requested set that changed at `sample` (empty for the initial row). + pub changed: Vec, +} + +/// A narrow pulse whose width does not exceed a configured glitch threshold. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct GlitchHit { + pub start: SampleIndex, + pub end: SampleIndex, + pub width: SampleIndex, + pub high: bool, +} + +/// Direction of an edge matched by cross-channel timing measurements. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum EdgeKind { + Rise, + Fall, + Both, +} + +/// One measured delay from a reference edge on channel A to the next matching edge on channel B. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct EdgeDeltaHit { + pub from_sample: SampleIndex, + pub to_sample: SampleIndex, + pub delta: SampleIndex, +} + +/// Summary statistics and sample hits for cross-channel edge-to-edge timing measurements. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct EdgeDeltaSummary { + pub count: u64, + pub min: Option, + pub p5: Option, + pub median: Option, + pub p95: Option, + pub max: Option, + pub mean: Option, + pub hits: Vec, + pub truncated: bool, +} + +/// Options controlling channel profiling cost and burst grouping. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ProfileOptions { + /// Maximum edges sampled for pulse distributions and burst splitting. + pub max_edges: usize, + /// Explicit idle gap in samples to split bursts; `None` picks an adaptive gap. + pub burst_gap: Option, + /// Maximum number of burst intervals returned. + pub max_bursts: usize, +} + +impl Default for ProfileOptions { + fn default() -> Self { + Self { + max_edges: DEFAULT_PROFILE_EDGE_LIMIT, + burst_gap: None, + max_bursts: DEFAULT_MAX_BURSTS, + } + } +} + +fn summarize_distribution( + mut values: Vec, + sampled: bool, +) -> Option { + if values.is_empty() { + return None; + } + values.sort_unstable(); + let count = values.len() as u64; + let sum: u128 = values.iter().map(|&v| u128::from(v)).sum(); + let mean = sum as f64 / count as f64; + let at = |num: usize, den: usize| -> SampleIndex { + let index = ((values.len() - 1) * num) / den; + values[index] + }; + Some(PulseDistribution { + count, + min: values[0], + p5: at(5, 100), + median: at(50, 100), + p95: at(95, 100), + max: *values.last().expect("non-empty"), + mean, + sampled, + }) +} + +fn count_ones_range(data: &ChannelData, from: SampleIndex, to: SampleIndex) -> u64 { + let to = to.min(data.len()); + if from >= to { + return 0; + } + let first_word = (from / 64) as usize; + let last_word = ((to - 1) / 64) as usize; + let start_mask = !0u64 << (from % 64); + let end_bits = to % 64; + let end_mask = if end_bits == 0 { + !0u64 + } else { + (1u64 << end_bits) - 1 + }; + if first_word == last_word { + return u64::from((data.word(first_word) & start_mask & end_mask).count_ones()); + } + let mut ones = u64::from((data.word(first_word) & start_mask).count_ones()); + for word in (first_word + 1)..last_word { + ones += u64::from(data.word(word).count_ones()); + } + ones += u64::from((data.word(last_word) & end_mask).count_ones()); + ones +} + +fn matches_edge(kind: EdgeKind, rising: bool) -> bool { + match kind { + EdgeKind::Rise => rising, + EdgeKind::Fall => !rising, + EdgeKind::Both => true, + } +} + +fn next_matching_edge( + data: &ChannelData, + from: SampleIndex, + to: SampleIndex, + kind: EdgeKind, +) -> Option { + let to = to.min(data.len()); + if from >= to { + return None; + } + let mut cursor = from; + while let Some(edge) = data.next_change(cursor) { + if edge >= to { + return None; + } + let rising = data.sample(edge); + if matches_edge(kind, rising) { + return Some(edge); + } + cursor = edge; + } + None +} + +impl ChannelData { + /// Profiles this channel over `range`, clamped to its length. + pub fn profile( + &self, + channel: ChannelIndex, + samplerate: u64, + range: Range, + options: ProfileOptions, + ) -> ChannelProfile { + let to = range.end.min(self.len()); + let from = range.start.min(to); + if from >= to { + return ChannelProfile { + channel, + activity: ChannelActivity::Empty, + initial_level: None, + final_level: None, + rising: 0, + falling: 0, + first_edge: None, + last_edge: None, + duty_cycle_high: None, + high_pulses: None, + low_pulses: None, + periods: None, + estimated_frequency_hz: None, + estimated_min_bit_hz: None, + burst_gap_samples: None, + bursts: Vec::new(), + bursts_truncated: false, + }; + } + + let initial = self.sample(from); + let final_level = self.sample(to - 1); + let counts = self.count_edges(from, to); + let total_edges = counts.rising + counts.falling; + let ones = count_ones_range(self, from, to); + let duty_cycle_high = Some(ones as f64 / (to - from) as f64); + + if total_edges == 0 { + return ChannelProfile { + channel, + activity: if initial { + ChannelActivity::ConstantHigh + } else { + ChannelActivity::ConstantLow + }, + initial_level: Some(initial), + final_level: Some(final_level), + rising: 0, + falling: 0, + first_edge: None, + last_edge: None, + duty_cycle_high, + high_pulses: None, + low_pulses: None, + periods: None, + estimated_frequency_hz: None, + estimated_min_bit_hz: None, + burst_gap_samples: None, + bursts: Vec::new(), + bursts_truncated: false, + }; + } + + let first_edge = self.next_change(from).filter(|&edge| edge < to); + let last_edge = self + .prev_change(to - 1) + .map(|at| at + 1) + .filter(|&edge| edge > from && edge < to); + + let cap = options.max_edges.max(2); + let mut edges: Vec<(SampleIndex, bool)> = Vec::with_capacity(cap.min(total_edges as usize)); + let mut cursor = from; + let mut sampled = false; + while let Some(edge) = self.next_change(cursor) { + if edge >= to { + break; + } + if edges.len() >= cap { + sampled = true; + break; + } + edges.push((edge, self.sample(edge))); + cursor = edge; + } + + let mut high_widths = Vec::new(); + let mut low_widths = Vec::new(); + let mut all_widths = Vec::new(); + let mut periods = Vec::new(); + let mut prev_rise: Option = None; + + for (index, &(edge, level)) in edges.iter().enumerate() { + if level { + if let Some(prev) = prev_rise { + periods.push(edge - prev); + } + prev_rise = Some(edge); + } + if index + 1 < edges.len() { + let width = edges[index + 1].0 - edge; + all_widths.push(width); + if level { + high_widths.push(width); + } else { + low_widths.push(width); + } + } + } + + let high_pulses = summarize_distribution(high_widths, sampled); + let low_pulses = summarize_distribution(low_widths, sampled); + let period_dist = summarize_distribution(periods, sampled); + let all_dist = summarize_distribution(all_widths, sampled); + + let estimated_frequency_hz = (samplerate > 0) + .then_some(period_dist.as_ref()) + .flatten() + .filter(|dist| dist.median > 0) + .map(|dist| samplerate as f64 / dist.median as f64); + + let estimated_min_bit_hz = (samplerate > 0) + .then_some(all_dist.as_ref()) + .flatten() + .filter(|dist| dist.p5 > 0) + .map(|dist| samplerate as f64 / dist.p5 as f64); + + let burst_gap = options.burst_gap.or_else(|| { + let base = period_dist + .as_ref() + .map(|dist| dist.median) + .or_else(|| all_dist.as_ref().map(|dist| dist.median)) + .unwrap_or(1); + Some(base.saturating_mul(16).max(16)) + }); + + let mut bursts = Vec::new(); + let mut bursts_truncated = sampled; + if let (Some(gap), Some(&(first, _))) = (burst_gap, edges.first()) { + let mut current = BurstInterval { + start: first, + end: first, + edges: 1, + }; + for &(edge, _) in edges.iter().skip(1) { + if edge.saturating_sub(current.end) > gap { + if bursts.len() + 1 >= options.max_bursts.max(1) { + bursts.push(current); + bursts_truncated = true; + current.edges = 0; + break; + } + bursts.push(current); + current = BurstInterval { + start: edge, + end: edge, + edges: 1, + }; + } else { + current.end = edge; + current.edges += 1; + } + } + if current.edges > 0 { + bursts.push(current); + } + } + + ChannelProfile { + channel, + activity: ChannelActivity::Active, + initial_level: Some(initial), + final_level: Some(final_level), + rising: counts.rising, + falling: counts.falling, + first_edge, + last_edge, + duty_cycle_high, + high_pulses, + low_pulses, + periods: period_dist, + estimated_frequency_hz, + estimated_min_bit_hz, + burst_gap_samples: burst_gap, + bursts, + bursts_truncated, + } + } + + /// Finds complete pulses inside `range` whose width is at most `max_width` samples. + /// Returns the matching hits (at most `limit`) and whether more exist. + pub fn find_glitches( + &self, + range: Range, + max_width: SampleIndex, + limit: usize, + ) -> (Vec, bool) { + let to = range.end.min(self.len()); + let from = range.start.min(to); + if from >= to || max_width == 0 || limit == 0 { + return (Vec::new(), false); + } + let Some(mut start) = self.next_change(from).filter(|&edge| edge < to) else { + return (Vec::new(), false); + }; + let mut hits = Vec::new(); + while let Some(end) = self.next_change(start) { + if end >= to { + break; + } + let width = end - start; + if width <= max_width { + if hits.len() >= limit { + return (hits, true); + } + hits.push(GlitchHit { + start, + end, + width, + high: self.sample(start), + }); + } + start = end; + } + (hits, false) + } +} + +impl LogicCapture { + /// Profiles logic channel `channel` over `range`. + pub fn profile_channel( + &self, + channel: ChannelIndex, + range: Range, + options: ProfileOptions, + ) -> Option { + let data = self.channel(channel)?; + Some(data.profile(channel, self.samplerate(), range, options)) + } + + /// Profiles analog channel `channel` over `range`. + pub fn profile_analog( + &self, + channel: ChannelIndex, + range: Range, + ) -> Option { + let data = self.analog_channel(channel)?; + let to = range.end.min(data.len()); + let from = range.start.min(to); + if from >= to { + return Some(AnalogProfile { + channel, + sample_count: 0, + min_volts: 0.0, + max_volts: 0.0, + mean_volts: 0.0, + }); + } + let (min_volts, max_volts) = data.volt_extent(from, to)?; + let count = to - from; + // Sample at most 65_536 evenly spaced points for the mean so multi-million-sample captures + // stay instantaneous while min/max remain exact via AnalogData's block summaries. + let step = (count / 65_536).max(1); + let mut sum = 0.0f64; + let mut taken = 0u64; + let mut at = from; + while at < to { + sum += f64::from(data.volts(at)); + taken += 1; + at += step; + } + Some(AnalogProfile { + channel, + sample_count: count, + min_volts, + max_volts, + mean_volts: if taken > 0 { sum / taken as f64 } else { 0.0 }, + }) + } + + /// Extracts lossless multi-channel transitions over `range` for `channels`, starting with the + /// initial state at `range.start` and then every sample where any listed channel changes. + /// + /// Returns at most `limit` rows and whether more transitions occur before `range.end`. + pub fn transitions( + &self, + channels: &[ChannelIndex], + range: Range, + limit: usize, + ) -> Option<(Vec, bool)> { + let to = range.end.min(self.len()); + let from = range.start.min(to); + let data: Vec<(ChannelIndex, &ChannelData)> = channels + .iter() + .map(|&ch| Some((ch, self.channel(ch)?))) + .collect::>>()?; + if from >= to || data.is_empty() || limit == 0 { + return Some((Vec::new(), false)); + } + + let mut levels: Vec = data.iter().map(|(_, ch)| ch.sample(from)).collect(); + let mut next: Vec> = data + .iter() + .map(|(_, ch)| ch.next_change(from).filter(|&at| at < to)) + .collect(); + + let mut rows = Vec::with_capacity(limit.min(256)); + rows.push(TransitionRow { + sample: from, + delta: None, + levels: levels.clone(), + changed: Vec::new(), + }); + + let mut prev_sample = from; + while let Some(at) = next.iter().flatten().copied().min() { + if rows.len() >= limit { + return Some((rows, true)); + } + let mut changed = Vec::new(); + for i in 0..data.len() { + if next[i] == Some(at) { + levels[i] = !levels[i]; + changed.push(data[i].0); + next[i] = data[i].1.next_change(at).filter(|&t| t < to); + } + } + rows.push(TransitionRow { + sample: at, + delta: Some(at - prev_sample), + levels: levels.clone(), + changed, + }); + prev_sample = at; + } + + Some((rows, false)) + } + + /// Measures delays from each `from_edge` on `from_edge.0` inside `range` to the first + /// subsequent `to_edge` on `to_edge.0` (at or after the reference edge, within `range` and + /// optional `max_delta`). + pub fn measure_edge_deltas( + &self, + from_edge: (ChannelIndex, EdgeKind), + to_edge: (ChannelIndex, EdgeKind), + range: Range, + max_delta: Option, + limit: usize, + ) -> Option { + let (ch_a, edge_a) = from_edge; + let (ch_b, edge_b) = to_edge; + let data_a = self.channel(ch_a)?; + let data_b = self.channel(ch_b)?; + let to = range.end.min(self.len()); + let from = range.start.min(to); + if from >= to { + return Some(EdgeDeltaSummary { + count: 0, + min: None, + p5: None, + median: None, + p95: None, + max: None, + mean: None, + hits: Vec::new(), + truncated: false, + }); + } + + let mut deltas = Vec::new(); + let mut hits = Vec::new(); + let mut truncated = false; + let mut cursor = from; + let cap = DEFAULT_PROFILE_EDGE_LIMIT; + + while let Some(sample_a) = next_matching_edge(data_a, cursor, to, edge_a) { + cursor = sample_a; + let search_end = max_delta + .map(|max| sample_a.saturating_add(max).saturating_add(1).min(to)) + .unwrap_or(to); + // Check whether `ch_b` also has a matching edge at `sample_a` itself (0-sample delta). + let same_sample = sample_a > 0 && { + let now = data_b.sample(sample_a); + let prev = data_b.sample(sample_a - 1); + now != prev && matches_edge(edge_b, now) + }; + let target = if same_sample && ch_a != ch_b { + Some(sample_a) + } else { + next_matching_edge(data_b, sample_a, search_end, edge_b) + }; + if let Some(sample_b) = target { + let delta = sample_b - sample_a; + if deltas.len() >= cap { + truncated = true; + break; + } + deltas.push(delta); + if hits.len() < limit { + hits.push(EdgeDeltaHit { + from_sample: sample_a, + to_sample: sample_b, + delta, + }); + } else { + truncated = true; + } + } + } + + let dist = summarize_distribution(deltas, truncated); + Some(EdgeDeltaSummary { + count: dist.as_ref().map_or(0, |d| d.count), + min: dist.as_ref().map(|d| d.min), + p5: dist.as_ref().map(|d| d.p5), + median: dist.as_ref().map(|d| d.median), + p95: dist.as_ref().map(|d| d.p95), + max: dist.as_ref().map(|d| d.max), + mean: dist.as_ref().map(|d| d.mean), + hits, + truncated, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn capture_from_bits(samplerate: u64, signals: &[&str]) -> LogicCapture { + let mut capture = LogicCapture::new(samplerate, 0..signals.len() as ChannelIndex); + for (index, bits) in signals.iter().enumerate() { + let bools: Vec = bits.bytes().map(|b| b == b'1').collect(); + let words: Vec = bools + .chunks(64) + .map(|chunk| { + chunk + .iter() + .enumerate() + .fold(0u64, |word, (bit, &high)| word | (u64::from(high) << bit)) + }) + .collect(); + let ch = capture + .channel_mut(index as ChannelIndex) + .expect("channel exists"); + ch.append_words(&words); + ch.truncate(bools.len() as SampleIndex); + } + capture + } + + #[test] + fn profiles_constant_and_clock_channels() { + // Channel 0: constant low, Channel 1: constant high, Channel 2: 50% square wave period 10 + let clock = "0000011111".repeat(10); + let zeros = "0".repeat(100); + let ones = "1".repeat(100); + let capture = capture_from_bits(1_000_000, &[&zeros, &ones, &clock]); + + let p0 = capture + .profile_channel(0, 0..100, ProfileOptions::default()) + .expect("ch0"); + assert_eq!(p0.activity, ChannelActivity::ConstantLow); + assert_eq!(p0.duty_cycle_high, Some(0.0)); + assert_eq!(p0.rising, 0); + + let p1 = capture + .profile_channel(1, 0..100, ProfileOptions::default()) + .expect("ch1"); + assert_eq!(p1.activity, ChannelActivity::ConstantHigh); + assert_eq!(p1.duty_cycle_high, Some(1.0)); + + let p2 = capture + .profile_channel(2, 0..100, ProfileOptions::default()) + .expect("ch2"); + assert_eq!(p2.activity, ChannelActivity::Active); + assert_eq!(p2.rising, 10); + assert_eq!(p2.falling, 9); + assert_eq!(p2.first_edge, Some(5)); + assert_eq!(p2.last_edge, Some(95)); + assert_eq!(p2.duty_cycle_high, Some(0.5)); + assert_eq!(p2.high_pulses.as_ref().expect("high").median, 5); + assert_eq!(p2.low_pulses.as_ref().expect("low").median, 5); + assert_eq!(p2.periods.as_ref().expect("periods").median, 10); + assert_eq!(p2.estimated_frequency_hz, Some(100_000.0)); + assert_eq!(p2.bursts.len(), 1); + } + + #[test] + fn splits_activity_bursts_across_idle_gaps() { + // Two short bursts separated by 60 idle samples + let mut bits = String::new(); + bits.push_str("0000"); + bits.push_str("101010"); + bits.push_str(&"0".repeat(60)); + bits.push_str("101010"); + bits.push_str("0000"); + let capture = capture_from_bits(1_000_000, &[&bits]); + let profile = capture + .profile_channel( + 0, + 0..capture.len(), + ProfileOptions { + burst_gap: Some(10), + ..ProfileOptions::default() + }, + ) + .expect("profile"); + assert_eq!(profile.bursts.len(), 2); + assert_eq!(profile.bursts[0].start, 4); + assert_eq!(profile.bursts[0].end, 9); + assert_eq!(profile.bursts[1].start, 70); + assert_eq!(profile.bursts[1].end, 75); + } + + #[test] + fn extracts_transitions_glitches_and_cross_channel_deltas() { + // Ch0: CS falls at 2, rises at 15; Ch1: CLK rises at 5, 9, glitch pulse of width 1 at 12..13 + let ch0 = "110000000000000111"; + let ch1 = "000001100110100000"; + let capture = capture_from_bits(1_000_000, &[ch0, ch1]); + + let (rows, truncated) = capture + .transitions(&[0, 1], 0..capture.len(), 20) + .expect("transitions"); + assert!(!truncated); + assert_eq!(rows[0].sample, 0); + assert_eq!(rows[0].delta, None); + assert_eq!(rows[0].levels, vec![true, false]); + assert_eq!(rows[1].sample, 2); + assert_eq!(rows[1].delta, Some(2)); + assert_eq!(rows[1].changed, vec![0]); + + let (glitches, more) = + capture + .channel(1) + .expect("ch1") + .find_glitches(0..capture.len(), 1, 10); + assert!(!more); + assert_eq!( + glitches, + vec![ + GlitchHit { + start: 11, + end: 12, + width: 1, + high: false + }, + GlitchHit { + start: 12, + end: 13, + width: 1, + high: true + }, + ] + ); + + let deltas = capture + .measure_edge_deltas( + (0, EdgeKind::Fall), + (1, EdgeKind::Rise), + 0..capture.len(), + None, + 10, + ) + .expect("deltas"); + assert_eq!(deltas.count, 1); + assert_eq!(deltas.min, Some(3)); + assert_eq!( + deltas.hits, + vec![EdgeDeltaHit { + from_sample: 2, + to_sample: 5, + delta: 3 + }] + ); + } +} From 2b95203cacfabfe223b738ee08b5dbd3fc1c8ca0 Mon Sep 17 00:00:00 2001 From: HalfSweet Date: Sun, 29 Nov 2026 22:08:40 +0800 Subject: [PATCH 03/32] feat(decode): add stream summaries and structured filters in hsync-uiharu Add StreamSummary, EventFilter and FieldFilter over decoded event stores so callers can aggregate kind/role/error counts and filter by range, kind, role, needle query or payload field predicates. --- crates/hsync-uiharu/src/filter.rs | 325 ++++++++++++++++++++++++++++++ crates/hsync-uiharu/src/lib.rs | 2 + crates/hsync-uiharu/src/query.rs | 41 ++++ crates/hsync-uiharu/src/roles.rs | 6 +- crates/hsync-uiharu/src/store.rs | 18 ++ 5 files changed, 390 insertions(+), 2 deletions(-) create mode 100644 crates/hsync-uiharu/src/filter.rs diff --git a/crates/hsync-uiharu/src/filter.rs b/crates/hsync-uiharu/src/filter.rs new file mode 100644 index 00000000..3784c823 --- /dev/null +++ b/crates/hsync-uiharu/src/filter.rs @@ -0,0 +1,325 @@ +//! Structured filtering and summarization over a decoded stream's [`Store`]. + +use std::collections::BTreeMap; +use std::ops::Range; + +use hsync_core::SampleIndex; +use serde::Serialize; +use serde_json::Value; +use uiharu_core::TickRange; + +use crate::roles::EventRole; +use crate::search::Needle; +use crate::store::{EventPage, EventRow, Store}; + +/// Comparison operator for a structured field filter on an event payload. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FieldOp { + Eq, + Ne, + Gt, + Ge, + Lt, + Le, + /// Case-insensitive substring match against string values (or JSON text representation). + Contains, +} + +/// A predicate tested against one field of a decoded event's JSON payload. +#[derive(Debug, Clone, PartialEq)] +pub struct FieldFilter { + /// Dot-separated field path inside the event payload (e.g. `address` or `header.id`). + pub field: String, + pub op: FieldOp, + pub value: Value, +} + +impl FieldFilter { + /// Evaluates this predicate against `payload`. + pub fn matches(&self, payload: &Value) -> bool { + let mut current = payload; + for segment in self.field.split('.') { + let Some(next) = current.get(segment) else { + return false; + }; + current = next; + } + match self.op { + FieldOp::Eq => values_equal(current, &self.value), + FieldOp::Ne => !values_equal(current, &self.value), + FieldOp::Gt => compare_numbers(current, &self.value).is_some_and(|ord| ord.is_gt()), + FieldOp::Ge => compare_numbers(current, &self.value).is_some_and(|ord| ord.is_ge()), + FieldOp::Lt => compare_numbers(current, &self.value).is_some_and(|ord| ord.is_lt()), + FieldOp::Le => compare_numbers(current, &self.value).is_some_and(|ord| ord.is_le()), + FieldOp::Contains => { + let needle = match &self.value { + Value::String(s) => s.to_lowercase(), + other => other.to_string().to_lowercase(), + }; + match current { + Value::String(s) => s.to_lowercase().contains(&needle), + other => other.to_string().to_lowercase().contains(&needle), + } + } + } + } +} + +fn as_number(value: &Value) -> Option { + value.as_f64() +} + +fn values_equal(a: &Value, b: &Value) -> bool { + if a == b { + return true; + } + if let (Some(x), Some(y)) = (as_number(a), as_number(b)) { + return x == y; + } + if let (Value::String(x), Value::String(y)) = (a, b) { + return x.eq_ignore_ascii_case(y); + } + false +} + +fn compare_numbers(a: &Value, b: &Value) -> Option { + let x = as_number(a)?; + let y = as_number(b)?; + x.partial_cmp(&y) +} + +/// Structured filter over events of a decoded stream. +#[derive(Debug, Clone, Default)] +pub struct EventFilter { + /// Only consider events overlapping this sample range. + pub range: Option>, + /// Keep events whose `kind` matches any of these (case-insensitive); empty keeps all. + pub kinds: Vec, + /// Keep events whose [`EventRole`] is in this list; empty keeps all. + pub roles: Vec, + /// Optional free-text / byte-sequence [`Needle`] query. + pub needle: Option, + /// Field-level predicates; every predicate must match. + pub fields: Vec, +} + +impl EventFilter { + /// Whether no filtering criterion is active. + pub fn is_empty(&self) -> bool { + self.range.is_none() + && self.kinds.is_empty() + && self.roles.is_empty() + && self.needle.is_none() + && self.fields.is_empty() + } +} + +/// Compact summary of a decoded stream: counts by kind and role, activity span, gaps and +/// leading error events. +#[derive(Debug, Clone, PartialEq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct StreamSummary { + pub total: u64, + pub settled: SampleIndex, + pub ended: bool, + pub first_sample: Option, + pub last_sample: Option, + pub gaps: Vec<(SampleIndex, SampleIndex)>, + pub by_kind: BTreeMap, + pub by_role: BTreeMap, + pub error_count: u64, + pub sample_errors: Vec, +} + +impl Store { + /// Summarizes all events held in this store, collecting up to `error_limit` leading error rows. + pub fn summary(&self, error_limit: usize) -> StreamSummary { + let mut by_kind: BTreeMap = BTreeMap::new(); + let mut by_role: BTreeMap = BTreeMap::new(); + let mut error_count = 0u64; + let mut sample_errors = Vec::new(); + let mut first_sample: Option = None; + let mut last_sample: Option = None; + + for index in 0..self.len() { + let Some((start, end, kind, role)) = self.entry_meta(index) else { + continue; + }; + first_sample = Some(first_sample.map_or(start, |cur| cur.min(start))); + last_sample = Some(last_sample.map_or(end, |cur| cur.max(end))); + *by_kind.entry(kind.to_owned()).or_insert(0) += 1; + *by_role.entry(role).or_insert(0) += 1; + if role == EventRole::Error { + error_count += 1; + if sample_errors.len() < error_limit + && let Some(row) = self.row(index) + { + sample_errors.push(row); + } + } + } + + StreamSummary { + total: self.len() as u64, + settled: self.settled().0, + ended: self.ended().is_some(), + first_sample, + last_sample, + gaps: self.gaps().iter().map(|g| (g.start.0, g.end.0)).collect(), + by_kind, + by_role, + error_count, + sample_errors, + } + } + + /// Returns a page of events matching `filter` over `scope` (already shifted into store ticks). + pub fn filter( + &self, + scope: Option, + filter: &EventFilter, + offset: usize, + limit: usize, + ) -> EventPage { + let mut total = 0usize; + let mut rows = Vec::with_capacity(limit.min(256)); + let check_index = |index: usize, total: &mut usize, rows: &mut Vec| { + let Some((_, _, kind, role)) = self.entry_meta(index) else { + return; + }; + if !filter.roles.is_empty() && !filter.roles.contains(&role) { + return; + } + if !filter.kinds.is_empty() + && !filter.kinds.iter().any(|k| k.eq_ignore_ascii_case(kind)) + { + return; + } + if let Some(needle) = &filter.needle + && !self.entry_matches_needle(index, needle) + { + return; + } + let row_opt = if !filter.fields.is_empty() { + let Some(row) = self.row(index) else { + return; + }; + if !filter.fields.iter().all(|f| f.matches(&row.payload)) { + return; + } + Some(row) + } else { + None + }; + let matched = *total; + *total += 1; + if matched >= offset + && rows.len() < limit + && let Some(row) = row_opt.or_else(|| self.row(index)) + { + rows.push(row); + } + }; + + match scope { + Some(range) => { + for index in self.overlapping(range) { + check_index(index, &mut total, &mut rows); + } + } + None => { + for index in 0..self.len() { + check_index(index, &mut total, &mut rows); + } + } + } + + EventPage { + total: total as u32, + offset: offset.min(total) as u32, + rows, + } + } +} + +#[cfg(test)] +mod tests { + use serde_json::json; + use uiharu_core::{SchemaId, Tick, TickRange}; + use uiharu_registry::{EventKind, Role}; + + use super::*; + + fn range(start: u64, end: u64) -> TickRange { + TickRange::new(Tick(start), Tick(end)) + } + + #[test] + fn summarizes_and_filters_events_by_role_kind_and_fields() { + let events = vec![ + EventKind { + kind: "address".into(), + role: Role::Address, + fields: vec!["address".into(), "acked".into()], + error_when: vec![], + }, + EventKind { + kind: "data".into(), + role: Role::Data, + fields: vec!["byte".into()], + error_when: vec![], + }, + EventKind { + kind: "error".into(), + role: Role::Error, + fields: vec!["reason".into()], + error_when: vec![], + }, + ]; + let mut store = Store::for_stream(SchemaId::new("i2c.events", 1), events); + store.push_event( + range(10, 20), + &json!({ "kind": "address", "address": 80, "acked": true }), + ); + store.push_event(range(20, 30), &json!({ "kind": "data", "byte": 0x4f })); + store.push_event( + range(30, 40), + &json!({ "kind": "error", "reason": "nack-address" }), + ); + store.push_end(Tick(50)); + + let summary = store.summary(5); + assert_eq!(summary.total, 3); + assert_eq!(summary.error_count, 1); + assert_eq!(summary.sample_errors.len(), 1); + assert_eq!(summary.first_sample, Some(10)); + assert_eq!(summary.last_sample, Some(40)); + assert_eq!(summary.by_kind.get("address"), Some(&1)); + assert_eq!(summary.by_role.get(&EventRole::Error), Some(&1)); + + let filter = EventFilter { + fields: vec![FieldFilter { + field: "address".into(), + op: FieldOp::Eq, + value: json!(80), + }], + ..EventFilter::default() + }; + let page = store.filter(None, &filter, 0, 10); + assert_eq!(page.total, 1); + assert_eq!(page.rows[0].kind, "address"); + + let err_filter = EventFilter { + roles: vec![EventRole::Error], + fields: vec![FieldFilter { + field: "reason".into(), + op: FieldOp::Contains, + value: json!("nack"), + }], + ..EventFilter::default() + }; + let page = store.filter(None, &err_filter, 0, 10); + assert_eq!(page.total, 1); + assert_eq!(page.rows[0].index, 2); + } +} diff --git a/crates/hsync-uiharu/src/lib.rs b/crates/hsync-uiharu/src/lib.rs index 7374a6ad..7a04f027 100644 --- a/crates/hsync-uiharu/src/lib.rs +++ b/crates/hsync-uiharu/src/lib.rs @@ -10,6 +10,7 @@ #![forbid(unsafe_code)] mod feed; +mod filter; mod query; mod roles; mod run; @@ -18,6 +19,7 @@ mod states; mod store; pub use feed::{FeedError, Feeder}; +pub use filter::{EventFilter, FieldFilter, FieldOp, StreamSummary}; pub use query::{Hit, StreamProgress}; pub use roles::{EventRole, RolePart}; pub use run::{DecodeError, Decoder, Position, Stream, Update, channels_read}; diff --git a/crates/hsync-uiharu/src/query.rs b/crates/hsync-uiharu/src/query.rs index e004c455..11a0eb32 100644 --- a/crates/hsync-uiharu/src/query.rs +++ b/crates/hsync-uiharu/src/query.rs @@ -9,6 +9,7 @@ use serde::Serialize; use ts_rs::TS; use uiharu_core::{Tick, TickRange}; +use crate::filter::{EventFilter, StreamSummary}; use crate::roles::RolePart; use crate::run::Decoder; use crate::search::Needle; @@ -178,6 +179,46 @@ impl Decoder { .collect() }) } + + /// Summary of stream `stream`, shifted to the capture's sample positions. + pub fn summary(&self, stream: usize, error_limit: usize) -> Option { + self.with_store(stream, |store, dropped| { + let mut summary = store.summary(error_limit); + summary.settled = summary.settled.saturating_sub(dropped); + summary.first_sample = summary.first_sample.map(|s| s.saturating_sub(dropped)); + summary.last_sample = summary.last_sample.map(|s| s.saturating_sub(dropped)); + for (start, end) in &mut summary.gaps { + *start = start.saturating_sub(dropped); + *end = end.saturating_sub(dropped); + } + for row in &mut summary.sample_errors { + shift_row(row, dropped); + } + summary + }) + } + + /// Paginated events of stream `stream` matching `filter`, shifted to the capture's sample + /// positions. + pub fn filter( + &self, + stream: usize, + filter: &EventFilter, + offset: usize, + limit: usize, + ) -> Option { + self.with_store(stream, |store, dropped| { + let scope = filter + .range + .clone() + .map(|range| Self::absolute(range, dropped)); + let mut page = store.filter(scope, filter, offset, limit); + for row in &mut page.rows { + shift_row(row, dropped); + } + page + }) + } } #[cfg(test)] diff --git a/crates/hsync-uiharu/src/roles.rs b/crates/hsync-uiharu/src/roles.rs index 0d784764..12b6c0fd 100644 --- a/crates/hsync-uiharu/src/roles.rs +++ b/crates/hsync-uiharu/src/roles.rs @@ -4,13 +4,15 @@ use std::collections::VecDeque; -use serde::Serialize; +use serde::{Deserialize, Serialize}; use serde_json::Value; use ts_rs::TS; use uiharu_registry::{EventKind, Role}; /// What an event is to someone reading the bus, whatever the protocol (uiharu's [`Role`]). -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, TS)] +#[derive( + Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, TS, +)] #[serde(rename_all = "kebab-case")] #[ts(export)] pub enum EventRole { diff --git a/crates/hsync-uiharu/src/store.rs b/crates/hsync-uiharu/src/store.rs index 691f28a3..846e685d 100644 --- a/crates/hsync-uiharu/src/store.rs +++ b/crates/hsync-uiharu/src/store.rs @@ -381,6 +381,24 @@ impl Store { &self.text[entry.offset..entry.offset + entry.len as usize] } + /// Lightweight metadata of event `index` without JSON parsing. + pub(crate) fn entry_meta(&self, index: usize) -> Option<(u64, u64, &str, EventRole)> { + let entry = self.entries.get(index)?; + Some(( + entry.start, + entry.end, + self.kinds[usize::from(entry.kind)].as_str(), + entry.role, + )) + } + + /// Whether the compact JSON payload of event `index` matches `needle`. + pub(crate) fn entry_matches_needle(&self, index: usize, needle: &Needle) -> bool { + self.entries + .get(index) + .is_some_and(|entry| needle.matches(self.payload_text(entry))) + } + /// The positions of the events overlapping `range`, in time order. pub fn overlapping(&self, range: TickRange) -> impl Iterator + '_ { let first = self From b4c1eb8c10a49cf765300851d24be0b1f02c3f01 Mon Sep 17 00:00:00 2001 From: HalfSweet Date: Sun, 29 Nov 2026 22:08:56 +0800 Subject: [PATCH 04/32] feat(session): expose decoder wait, summary and filter queries Add DecodeSet::wait, DecodeSet::summary and DecodeSet::filter and re-export capture profiling and decoded filter types from hsync-session. --- crates/hsync-session/src/decoding.rs | 45 ++++++++++++++++++++++++++-- crates/hsync-session/src/lib.rs | 9 ++++-- 2 files changed, 50 insertions(+), 4 deletions(-) diff --git a/crates/hsync-session/src/decoding.rs b/crates/hsync-session/src/decoding.rs index e0431ba8..1c604020 100644 --- a/crates/hsync-session/src/decoding.rs +++ b/crates/hsync-session/src/decoding.rs @@ -8,8 +8,8 @@ use std::sync::Arc; use hsync_capture::LogicCapture; use hsync_core::{SampleIndex, UiError}; use hsync_uiharu::{ - DecodeError, Decoder, EventRole, EventRow, Needle, Position, RolePart, StreamProgress, - StreamView, Update, + DecodeError, Decoder, EventFilter, EventRole, EventRow, Needle, Position, RolePart, + StreamProgress, StreamSummary, StreamView, Update, }; use parking_lot::{Mutex, RwLock}; use serde::Serialize; @@ -344,6 +344,47 @@ impl DecodeSet { } } + /// Waits until every started decoder has finished (or failed). Only call after the capture + /// has finished (`Position::finishing = true`) or [`Self::cancel`] has been called. + pub fn wait(&self) { + for entry in self.entries.write().iter_mut() { + if let Some(decoder) = &mut entry.decoder { + decoder.join(); + } + } + } + + /// Summarizes stream `stream` of decoder `index`, collecting at most `error_limit` leading + /// error events. + pub fn summary(&self, index: u32, stream: u32, error_limit: usize) -> Option { + self.with_decoder(index, |decoder| { + decoder.summary(stream as usize, error_limit) + }) + } + + /// Returns a page of rows from stream `stream` of decoder `index` matching `filter`. + pub fn filter( + &self, + index: u32, + stream: u32, + filter: &EventFilter, + offset: u32, + limit: u32, + ) -> Option { + self.with_decoder(index, |decoder| { + let stream = stream as usize; + let page = decoder.filter(stream, filter, offset as usize, limit as usize)?; + let progress = decoder.progress(stream)?; + Some(StreamPage { + total: page.total, + offset: page.offset, + rows: page.rows, + events: progress.events, + inside: None, + }) + }) + } + pub fn statuses(&self) -> Vec { self.entries .read() diff --git a/crates/hsync-session/src/lib.rs b/crates/hsync-session/src/lib.rs index 3ed42bc5..a30e6b38 100644 --- a/crates/hsync-session/src/lib.rs +++ b/crates/hsync-session/src/lib.rs @@ -41,13 +41,18 @@ pub use entry::{ }; pub use error::SessionError; pub use files::{ExportKind, ExportRequest, ExportSource, read_text, write_text}; -pub use hsync_capture::{PatternCondition, PatternLevel}; +pub use hsync_capture::{ + AnalogProfile, BurstInterval, ChannelActivity, ChannelProfile, DEFAULT_MAX_BURSTS, + DEFAULT_PROFILE_EDGE_LIMIT, EdgeDeltaHit, EdgeDeltaSummary, EdgeKind, GlitchHit, + PatternCondition, PatternLevel, ProfileOptions, PulseDistribution, TransitionRow, +}; pub use hsync_fileio::{ ImportRequest, Waveform, WaveformFormat, WaveformItem, WaveformItemKind, WaveformSummary, read_waveform_file, }; pub use hsync_uiharu::{ - EventRole, EventRow, LaneBlock, Position, RolePart, StreamProgress, StreamView, + EventFilter, EventRole, EventRow, FieldFilter, FieldOp, LaneBlock, Position, RolePart, + StreamProgress, StreamSummary, StreamView, }; pub use instrument::{ CaptureRequest, DeviceState, EndKind, EventSink, Instrument, LivePhase, LiveStatus, From 9a3e5bf5566b4292c5d03da3a58a7e0f403b28e0 Mon Sep 17 00:00:00 2001 From: HalfSweet Date: Sun, 29 Nov 2026 22:09:17 +0800 Subject: [PATCH 05/32] feat(cli): add standalone agent-friendly hsync-cli binary Add crates/hsync-cli providing headless hardware/demo capture, L0 signal inspection, L1/L2 protocol decoding with shorthand auto-wired pipelines and compact transcripts, L3 transition/wave/measure/search queries, export, firmware discovery and structured --json output. --- Cargo.lock | 24 + crates/hsync-cli/Cargo.toml | 36 + crates/hsync-cli/src/args.rs | 190 ++++ crates/hsync-cli/src/commands/capture.rs | 1222 ++++++++++++++++++++++ crates/hsync-cli/src/commands/catalog.rs | 291 ++++++ crates/hsync-cli/src/commands/decode.rs | 684 ++++++++++++ crates/hsync-cli/src/commands/devices.rs | 272 +++++ crates/hsync-cli/src/commands/doctor.rs | 152 +++ crates/hsync-cli/src/commands/export.rs | 154 +++ crates/hsync-cli/src/commands/inspect.rs | 429 ++++++++ crates/hsync-cli/src/commands/measure.rs | 465 ++++++++ crates/hsync-cli/src/commands/mod.rs | 12 + crates/hsync-cli/src/commands/search.rs | 321 ++++++ crates/hsync-cli/src/commands/wave.rs | 350 +++++++ crates/hsync-cli/src/error.rs | 478 +++++++++ crates/hsync-cli/src/main.rs | 163 +++ crates/hsync-cli/src/open.rs | 70 ++ crates/hsync-cli/src/pipeline.rs | 512 +++++++++ crates/hsync-cli/src/resources.rs | 191 ++++ crates/hsync-cli/src/transcript.rs | 761 ++++++++++++++ crates/hsync-cli/src/units.rs | 501 +++++++++ 21 files changed, 7278 insertions(+) create mode 100644 crates/hsync-cli/Cargo.toml create mode 100644 crates/hsync-cli/src/args.rs create mode 100644 crates/hsync-cli/src/commands/capture.rs create mode 100644 crates/hsync-cli/src/commands/catalog.rs create mode 100644 crates/hsync-cli/src/commands/decode.rs create mode 100644 crates/hsync-cli/src/commands/devices.rs create mode 100644 crates/hsync-cli/src/commands/doctor.rs create mode 100644 crates/hsync-cli/src/commands/export.rs create mode 100644 crates/hsync-cli/src/commands/inspect.rs create mode 100644 crates/hsync-cli/src/commands/measure.rs create mode 100644 crates/hsync-cli/src/commands/mod.rs create mode 100644 crates/hsync-cli/src/commands/search.rs create mode 100644 crates/hsync-cli/src/commands/wave.rs create mode 100644 crates/hsync-cli/src/error.rs create mode 100644 crates/hsync-cli/src/main.rs create mode 100644 crates/hsync-cli/src/open.rs create mode 100644 crates/hsync-cli/src/pipeline.rs create mode 100644 crates/hsync-cli/src/resources.rs create mode 100644 crates/hsync-cli/src/transcript.rs create mode 100644 crates/hsync-cli/src/units.rs diff --git a/Cargo.lock b/Cargo.lock index 4cdff5b8..b06f41e1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1630,6 +1630,30 @@ dependencies = [ "ts-rs", ] +[[package]] +name = "hsync-cli" +version = "0.2.9" +dependencies = [ + "crossbeam-channel", + "hsync-atklogic", + "hsync-capture", + "hsync-core", + "hsync-demo", + "hsync-driver", + "hsync-dslogic", + "hsync-fileio", + "hsync-pxlogic", + "hsync-session", + "hsync-slogic", + "hsync-uiharu", + "indexmap 2.14.2", + "log", + "parking_lot", + "serde", + "serde_json", + "uiharu-registry", +] + [[package]] name = "hsync-core" version = "0.2.9" diff --git a/crates/hsync-cli/Cargo.toml b/crates/hsync-cli/Cargo.toml new file mode 100644 index 00000000..42f1e837 --- /dev/null +++ b/crates/hsync-cli/Cargo.toml @@ -0,0 +1,36 @@ +[package] +name = "hsync-cli" +description = "Standalone, agent-friendly command-line interface for HSync logic analyzers and captures" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +authors.workspace = true +publish.workspace = true + +[[bin]] +name = "hsync-cli" +path = "src/main.rs" + +[dependencies] +crossbeam-channel.workspace = true +hsync-atklogic.workspace = true +hsync-capture.workspace = true +hsync-core.workspace = true +hsync-demo.workspace = true +hsync-driver.workspace = true +hsync-dslogic.workspace = true +hsync-fileio.workspace = true +hsync-pxlogic.workspace = true +hsync-session.workspace = true +hsync-slogic.workspace = true +hsync-uiharu.workspace = true +indexmap.workspace = true +log.workspace = true +parking_lot.workspace = true +serde.workspace = true +serde_json.workspace = true +uiharu-registry.workspace = true + +[lints] +workspace = true diff --git a/crates/hsync-cli/src/args.rs b/crates/hsync-cli/src/args.rs new file mode 100644 index 00000000..a4a9287e --- /dev/null +++ b/crates/hsync-cli/src/args.rs @@ -0,0 +1,190 @@ +//! Lightweight command-line argument parser supporting `--option value`, `--option=value`, +//! short aliases (`-o`, `-h`, `-v`), repeatable values, flags and positional arguments. + +use std::collections::BTreeMap; +use std::fmt::Display; +use std::str::FromStr; + +use crate::error::CliError; + +/// Global flags accepted before or after any subcommand. +pub const GLOBAL_FLAGS: &[&str] = &["json", "help", "version"]; + +/// Global value options accepted before or after any subcommand. +pub const GLOBAL_OPTIONS: &[&str] = &["firmware-dir", "demo-file"]; + +/// Parsed command-line arguments. +#[derive(Debug, Default, Clone)] +pub struct Args { + positional: Vec, + options: BTreeMap>, + flags: Vec, +} + +impl Args { + /// Parses `raw` arguments given the flag names (options without values) and short option + /// mappings (`('o', "out")`). + pub fn parse( + raw: impl IntoIterator, + flags: &[&str], + shorts: &[(char, &str)], + ) -> Result { + let mut parsed = Self::default(); + let mut iter = raw.into_iter(); + let is_flag = |name: &str| flags.contains(&name) || GLOBAL_FLAGS.contains(&name); + + while let Some(arg) = iter.next() { + if arg == "--" { + parsed.positional.extend(iter.by_ref()); + break; + } + if let Some(rest) = arg.strip_prefix("--") { + if rest.is_empty() { + continue; + } + if let Some((name, value)) = rest.split_once('=') { + if is_flag(name) { + return Err(CliError::usage(format!( + "flag --{name} does not take a value" + ))); + } + parsed + .options + .entry(name.to_owned()) + .or_default() + .push(value.to_owned()); + } else if is_flag(rest) { + parsed.flags.push(rest.to_owned()); + } else { + let value = iter.next().ok_or_else(|| { + CliError::usage(format!("option --{rest} requires a value")) + })?; + parsed + .options + .entry(rest.to_owned()) + .or_default() + .push(value); + } + continue; + } + if arg.starts_with('-') && arg.len() == 2 { + let ch = arg.as_bytes()[1] as char; + if ch == 'h' { + parsed.flags.push("help".to_owned()); + continue; + } + if ch == 'V' { + parsed.flags.push("version".to_owned()); + continue; + } + if let Some(&(_, long)) = shorts.iter().find(|&&(short, _)| short == ch) { + if is_flag(long) { + parsed.flags.push(long.to_owned()); + } else { + let value = iter.next().ok_or_else(|| { + CliError::usage(format!("option -{ch} (--{long}) requires a value")) + })?; + parsed + .options + .entry(long.to_owned()) + .or_default() + .push(value); + } + continue; + } + } + parsed.positional.push(arg); + } + + Ok(parsed) + } + + /// Positional arguments in order (excluding options and flags). + pub fn positional(&self) -> &[String] { + &self.positional + } + + /// Whether flag `--name` was passed. + pub fn flag(&self, name: &str) -> bool { + self.flags.iter().any(|flag| flag == name) + } + + /// Last value supplied for `--name`. + pub fn value(&self, name: &str) -> Option<&str> { + self.options + .get(name) + .and_then(|values| values.last()) + .map(String::as_str) + } + + /// All values supplied for `--name`, in order. + pub fn values(&self, name: &str) -> Vec<&str> { + self.options + .get(name) + .map(|values| values.iter().map(String::as_str).collect()) + .unwrap_or_default() + } + + /// Parses `--name` as `T`, returning `default` when absent. + pub fn parsed(&self, name: &str, default: T) -> Result + where + T::Err: Display, + { + match self.value(name) { + None => Ok(default), + Some(raw) => raw + .parse() + .map_err(|err| CliError::usage(format!("invalid --{name} '{raw}': {err}"))), + } + } + + /// Rejects any option or flag not listed in `known` or the global option set. + pub fn only(&self, known: &[&str]) -> Result<(), CliError> { + for name in self + .options + .keys() + .map(String::as_str) + .chain(self.flags.iter().map(String::as_str)) + { + if !known.contains(&name) + && !GLOBAL_FLAGS.contains(&name) + && !GLOBAL_OPTIONS.contains(&name) + { + return Err(CliError::usage(format!("unknown option --{name}"))); + } + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_global_short_repeatable_and_positional_args() { + let raw = [ + "capture", + "--json", + "-o", + "out.hsync", + "--decoder=i2c(scl=0,sda=1)", + "--decoder", + "uart(line=2)", + "--instant", + ] + .into_iter() + .map(str::to_owned); + let args = Args::parse(raw, &["instant"], &[('o', "out")]).expect("parses"); + assert_eq!(args.positional(), &["capture"]); + assert!(args.flag("json")); + assert!(args.flag("instant")); + assert_eq!(args.value("out"), Some("out.hsync")); + assert_eq!( + args.values("decoder"), + vec!["i2c(scl=0,sda=1)", "uart(line=2)"] + ); + assert!(args.only(&["out", "decoder", "instant"]).is_ok()); + assert!(args.only(&["out"]).is_err()); + } +} diff --git a/crates/hsync-cli/src/commands/capture.rs b/crates/hsync-cli/src/commands/capture.rs new file mode 100644 index 00000000..da7d2bc3 --- /dev/null +++ b/crates/hsync-cli/src/commands/capture.rs @@ -0,0 +1,1222 @@ +//! `hsync-cli capture`: declarative hardware/demo acquisition with rate-tier resolution, +//! memory guardrails, trigger timeouts, `--fallback-instant`, `--exec` arm-then-act stimulus +//! coordination, optional inline decoding/inspection and `.hsync` / export saving. + +use std::collections::BTreeMap; +use std::fs; +use std::path::Path; +use std::process::Command; +use std::sync::Arc; +use std::thread::JoinHandle; +use std::time::{Duration, Instant}; + +use hsync_capture::ProfileOptions; +use hsync_core::{ANALOG_BASE, ChannelIndex}; +use hsync_driver::{AdvancedTrigger, CapturePreset, OptionKey, OptionKind, OptionValue}; +use hsync_session::{ + CaptureRequest, DeviceState, EndKind, EventSink, ExportKind, ExportRequest, Instrument, + LivePhase, LiveStatus, SessionEvent, Workspace, +}; +use serde::Serialize; + +use crate::args::Args; +use crate::commands::decode::{self, DecoderSummaryReport}; +use crate::commands::devices::resolve_device_id; +use crate::commands::inspect::{self, InspectReport}; +use crate::error::CliError; +use crate::pipeline::{load_graph_file, parse_decoder_spec}; +use crate::resources::Resources; +use crate::units::{ + Timestamp, format_bytes, format_freq_hz, format_samples_time, parse_bytes, parse_channel_list, + parse_count, parse_duration, parse_duration_ns, parse_frequency_hz, parse_trigger_spec, + resolve_channel, +}; + +/// Default memory guardrail (512 MiB) so an agent cannot accidentally allocate gigabytes. +const DEFAULT_MAX_MEMORY: u64 = 512 * 1024 * 1024; +const DEFAULT_TRIGGER_TIMEOUT: Duration = Duration::from_secs(10); +const DEFAULT_TOTAL_TIMEOUT: Duration = Duration::from_secs(60); +const EXEC_OUTPUT_CAP: usize = 4096; + +pub const FLAGS: &[&str] = &[ + "demo", + "instant", + "dry-run", + "inspect", + "fallback-instant", + "every-sample", +]; + +pub const USAGE: &str = "\ +hsync-cli capture [options] + + Captures samples from a connected logic analyzer or the built-in Demo device. + + Device & acquisition options: + --device Device ID (or unique driver/model substring); auto-picks if one + physical analyzer is attached + --demo Use the built-in Demo device (virtual-demo) + --channels Logic channels to enable (e.g. 0-7, D0,D1,D4-D7) + --analog Analog inputs to enable (e.g. 0,1 for A0,A1 on SLogic32U3) + --name Name a channel (repeatable, e.g. --name 0=SCL --name 1=SDA) + --rate Sample rate (e.g. 25MHz, 400kHz) + --duration