diff --git a/AGENTS.md b/AGENTS.md index c76bb54d..54b14923 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,7 +14,7 @@ These come from the project owner; no change may break them: 1. **Stack**: the desktop shell is **Tauri 2**; the frontend is **Vue 3 + TypeScript + Tailwind CSS v4**; waveforms render with Canvas2D as the baseline, **accelerated with WebGPU where it is available**, and the fallback always stays. 2. **DESIGN.md governs the UI and UX; the `.hsync/` mockups are only a reference**: `.hsync/handoff.md` and the HTML mockup beside it (local files, not in the repository) are a starting point, not a spec to follow. The interface may improve on them for real-world use; such changes go into DESIGN.md. -3. **Internationalization**: the first release supports Simplified Chinese (the default) and English. Every user-visible string in the interface goes through vue-i18n, never hard-coded; the Rust side outputs no natural language, only i18n keys and parameters. +3. **Internationalization**: the first release supports Simplified Chinese (the default) and English. Every user-visible string in the interface goes through vue-i18n, never hard-coded; the Rust side outputs no natural language, only i18n keys and parameters. The one exception is `hsync-cli` (with its MCP server), which prints English directly: the library crates still return only keys and parameters, and the CLI turns them into English in `crates/hsync-cli/src/error.rs`. 4. **All interaction with real hardware is written in Rust**, and USB is reached only through **nusb**. Never bring in libusb, rusb or FFI to any C/C++ driver code; DSView's and PXView's C code and ATK-Logic's C++ are only porting references. 5. **Code style**: the frontend follows **ESLint + Prettier**; Rust follows rustfmt + clippy. **lefthook** makes sure code is formatted when it is committed, and commitlint checks the commit messages. 6. **Commits**: use **fine-grained Conventional Commits**; **write pull requests and issues in English**. See [Commit conventions](#commit-conventions) below. @@ -30,11 +30,12 @@ These come from the project owner; no change may break them: | ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `README.md`, `README.zh-CN.md` | The project page in English and Chinese: features, downloads, getting started, building | | `DESIGN.md` | Interface design spec: layout, design tokens, each area's look and behaviour, accessibility, motion | -| `docs/` | The user guide (`user-guide.md`), updated when the interface or how it works changes, and the maintainer guide on CI, releases and packaging (`maintainer-guide.md`) | +| `docs/` | The user guide (`user-guide.md`), updated when the interface or how it works changes, the standalone CLI guide (`cli.md`), and the maintainer guide on CI, releases and packaging (`maintainer-guide.md`) | +| `skills/` | Official Agent Skills (e.g. `skills/hsync-cli/SKILL.md`) teaching AI agents how to capture and decode with `hsync-cli` | | `assets/` | The brand mark and social preview (`brand/`), the README screenshots (`screenshots/`) | | `src/` | Vue frontend (components, Pinia stores, renderers, IPC wrappers, i18n) | | `src-tauri/` | Tauri app crate (commands, events, resources: firmware and demo data) | -| `crates/hsync-*` | Rust libraries: core, capture, driver, dslogic, atklogic, pxlogic, demo, decode, fileio, session, uiharu (runs the uiharu engine on captures) | +| `crates/hsync-*` | Rust libraries and binaries: core, capture, driver, dslogic, atklogic, pxlogic, slogic, demo, decode, fileio, session, uiharu (runs the uiharu engine on captures), bench, cli (`hsync-cli`, standalone agent-friendly CLI) | | `uiharu/` | The uiharu decode engine (Apache-2.0): `crates/uiharu-core` (the runtime), `crates/uiharu-protocols` (the decoders: SPI, SPI NOR, SD card, APA102, AVR ISP, nRF24L01+, Microwire, 93Cxx EEPROM, I²C, 24xx EEPROM, UART, Modbus RTU, LIN, MIDI, DMX512, CAN, 1-Wire, DS18B20, USB, USB PD, I²S, PWM, timing, parallel, WS281x, JTAG, SWD, MDIO, PS/2, Wiegand, AM230x, NEC/RC-5/RC-6/SIRC infrared), `crates/uiharu-registry` (the node types by name, with their manifests), `crates/uiharu-cli` (the `uiharu` command), `crates/uiharu-ir` (the decoder IR and its checks), `crates/uiharu-codegen` (Rust from the IR), `crates/uiharu-dsl-protocols` (the decoders and contracts generated from the IR: PWM, SPI, SPI NOR, UART and the I²C contract; never edited by hand), `crates/uiharu-interp` (the interpreter of the IR: runs a decoder module loaded at run time as the generated Rust would, bridged to the compiled decoders), `dsl/` (the decoder DSL: its TypeScript declarations, the decoders written in it, the contracts of hand-written decoders and their IR), `compiler/` (the DSL compiler's front end), `docs/` (architecture, the DSL and its IR, how to write a decoder, one page per protocol), `LICENSE` | | `scripts/` | Builds this machine's installers the way releases are built | | `.github/` | CI checks, installer builds and releases | @@ -140,7 +141,7 @@ Format: ``` - **type**: `feat`, `fix`, `perf`, `refactor`, `style`, `test`, `docs`, `build`, `ci`, `chore`, `revert`. -- **scope** (optional; when given it must be on the allow-list in `commitlint.config.js`): `core`, `capture`, `driver`, `dslogic`, `atklogic`, `pxlogic`, `demo`, `decode`, `fileio`, `session`, `app`, `uiharu`, `ui`, `timeline`, `stream`, `trigger`, `render`, `i18n`, `theme`, `ipc`, `store`, `deps`, `tooling`, `repo`. +- **scope** (optional; when given it must be on the allow-list in `commitlint.config.js`): `core`, `capture`, `driver`, `dslogic`, `atklogic`, `pxlogic`, `demo`, `decode`, `fileio`, `session`, `cli`, `app`, `uiharu`, `ui`, `timeline`, `stream`, `trigger`, `render`, `i18n`, `theme`, `ipc`, `store`, `deps`, `tooling`, `repo`. - **subject**: an imperative sentence in English, starting in lower case, without a full stop, at most 72 characters. - **Fine-grained**: a commit does one thing that can be reverted and reviewed on its own. Configuration, scaffolding, features, tests and documentation go in separate commits; formatting and logic changes are never mixed; a new dependency may share a commit with the code that uses it. - Breaking changes add `!` after the type and a `BREAKING CHANGE:` line in the body. diff --git a/Cargo.lock b/Cargo.lock index 4cdff5b8..89cb1836 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1630,6 +1630,31 @@ 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", + "thiserror 2.0.21", + "uiharu-registry", +] + [[package]] name = "hsync-core" version = "0.2.9" diff --git a/README.md b/README.md index ce66007b..70447fce 100644 --- a/README.md +++ b/README.md @@ -100,6 +100,11 @@ Sipeed has given strong support to HSync's work on its SLogic analyzers. - **Keyboard shortcuts** for zooming, panning, searching, opening, saving and more, all of which you can change. - **Updates inside the app**: HSync checks at startup and installs a new version in one click. +### Command line & automation (`hsync-cli`) + +- **Standalone headless CLI (`hsync-cli`)** for scripts, hardware-in-the-loop tests and AI coding agents: `doctor`, `devices`, `catalog`, declarative `capture` (with `--trigger-timeout`, `--fallback-instant`, memory guardrails and `--exec` arm-then-act DUT stimulation), L0 signal `inspect`, L1/L2 `decode` (shorthand pipelines, summaries, structured `--where` filters, compact protocol transcripts and NDJSON), L3 `transitions`, Unicode `wave`, `measure` (pulses, edges, glitches, cross-channel deltas), `search` and `export`. +- **Structured `--json` mode** across every command (including dual sample/time coordinates and actionable error hints) plus a ready-to-use Agent Skill in [skills/hsync-cli/SKILL.md](skills/hsync-cli/SKILL.md). See the [CLI guide](docs/cli.md). + ## Download Get the latest version from the [Releases page](https://github.com/HalfSweet/HSync/releases/latest). diff --git a/README.zh-CN.md b/README.zh-CN.md index d6c921ea..b25066a4 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -99,6 +99,11 @@ SLogic 系列逻辑分析仪的适配得到了矽速科技(Sipeed)的大力 - **快捷键**覆盖缩放、平移、搜索、打开、保存等操作,均可自定义。 - **应用内更新**:启动时检查新版本,一键安装。 +### 命令行与自动化(`hsync-cli`) + +- **独立无头命令行工具(`hsync-cli`)**,面向脚本、硬件在环测试与 AI Agent:涵盖 `doctor`、`devices`、`catalog`、声明式 `capture`(支持 `--trigger-timeout`、`--fallback-instant`、内存护栏与 `--exec` 先武装后激励协同)、L0 信号体检 `inspect`、L1/L2 `decode`(简写流水线、解码摘要、结构化 `--where` 过滤、紧凑协议视图与 NDJSON)、L3 `transitions` / Unicode `wave` / `measure`(脉宽、边沿、毛刺、跨通道延迟)、`search` 与 `export`。 +- **全局 `--json` 结构化输出**(统一双坐标系与可恢复错误提示),并在 [skills/hsync-cli/SKILL.md](skills/hsync-cli/SKILL.md) 提供官方 Agent Skill。参见[命令行指南(英文)](docs/cli.md)。 + ## 下载 在 [Releases 页面](https://github.com/HalfSweet/HSync/releases/latest)下载最新版本。 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', diff --git a/crates/hsync-capture/src/analog.rs b/crates/hsync-capture/src/analog.rs index fc9cf03b..e2b1bf88 100644 --- a/crates/hsync-capture/src/analog.rs +++ b/crates/hsync-capture/src/analog.rs @@ -168,10 +168,13 @@ impl AnalogData { let from = self.head + from as usize; let to = self.head + to as usize; let mut result = None; - for chunk in from / CHUNK..=(to - 1) / CHUNK { + let first_chunk = from / CHUNK; + let last_chunk = (to - 1) / CHUNK; + for (offset, chunk_data) in self.chunks.range(first_chunk..=last_chunk).enumerate() { + let chunk = first_chunk + offset; let base = chunk * CHUNK; let range = from.max(base) - base..to.min(base + CHUNK) - base; - if let Some(part) = self.chunks[chunk].extent(range) { + if let Some(part) = chunk_data.extent(range) { result = Some(join(result, part)); } } @@ -191,11 +194,15 @@ impl AnalogData { end: SampleIndex, bins: usize, ) -> Vec> { - let n = end.saturating_sub(start); - (0..bins as u64) + if bins == 0 || end <= start { + return vec![None; bins]; + } + let n = u128::from(end - start); + let bins_u128 = bins as u128; + (0..bins_u128) .map(|column| { - let from = start + n * column / bins as u64; - let to = start + n * (column + 1) / bins as u64; + let from = start + (n * column / bins_u128) as u64; + let to = start + (n * (column + 1) / bins_u128) as u64; self.volt_extent(from, to.max(from + 1)) }) .collect() 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 + }] + ); + } +} diff --git a/crates/hsync-capture/src/summary.rs b/crates/hsync-capture/src/summary.rs index dc635107..a00c8e40 100644 --- a/crates/hsync-capture/src/summary.rs +++ b/crates/hsync-capture/src/summary.rs @@ -140,9 +140,8 @@ impl Summary { return; } // Below the top, a chunk covers whole blocks of units: drop them. - for depth in 0..LEVELS - 1 { + for (depth, level) in self.levels[..LEVELS - 1].iter_mut().enumerate() { let units = 1usize << (6 * (LEVELS - 1 - depth)); - let level = &mut self.levels[depth]; let blocks = (units / 64 * count).min(level.mixed.len()); level.mixed.drain(..blocks); level.high.drain(..blocks); diff --git a/crates/hsync-cli/Cargo.toml b/crates/hsync-cli/Cargo.toml new file mode 100644 index 00000000..b96838b9 --- /dev/null +++ b/crates/hsync-cli/Cargo.toml @@ -0,0 +1,37 @@ +[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 +thiserror.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..06eec920 --- /dev/null +++ b/crates/hsync-cli/src/args.rs @@ -0,0 +1,211 @@ +//! 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 known `flags` (no value), `options` (one value each) and + /// short option mappings (`('o', "out")`). + pub fn parse( + raw: impl IntoIterator, + flags: &[&str], + options: &[&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); + let is_option = |name: &str| options.contains(&name) || GLOBAL_OPTIONS.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" + ))); + } + if !is_option(name) { + return Err(CliError::usage(format!("unknown option --{name}"))); + } + parsed + .options + .entry(name.to_owned()) + .or_default() + .push(value.to_owned()); + } else if is_flag(rest) { + parsed.flags.push(rest.to_owned()); + } else if is_option(rest) { + 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); + } else { + return Err(CliError::usage(format!("unknown option --{rest}"))); + } + continue; + } + if arg.starts_with('-') && arg.len() >= 2 { + if 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 if is_option(long) { + 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); + } else { + return Err(CliError::usage(format!("unknown option -{ch}"))); + } + continue; + } + } + return Err(CliError::usage(format!( + "unknown option '{arg}' (use `--` before positional arguments starting with `-`)" + ))); + } + 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"], &["out", "decoder"], &[('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()); + + // Unknown long or short flags must fail immediately instead of swallowing the next arg. + let bogus = ["--bogus", "capture"].into_iter().map(str::to_owned); + assert!(Args::parse(bogus, &[], &[], &[]).is_err()); + let bad_short = ["-x", "file.hsync"].into_iter().map(str::to_owned); + assert!(Args::parse(bad_short, &[], &[], &[]).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..676bb1be --- /dev/null +++ b/crates/hsync-cli/src/commands/capture.rs @@ -0,0 +1,1676 @@ +//! `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::io::Read; +use std::path::Path; +use std::process::{Command, Stdio}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::thread::JoinHandle; +use std::time::{Duration, Instant}; + +use parking_lot::Mutex; + +use hsync_capture::ProfileOptions; +use hsync_core::{ANALOG_BASE, ChannelIndex}; +use hsync_driver::{AdvancedTrigger, 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); +/// Floor of the default `--timeout`. +const DEFAULT_TOTAL_TIMEOUT: Duration = Duration::from_secs(60); +/// Fixed allowance of the default `--timeout` for arming, upload and saving. +const TOTAL_TIMEOUT_MARGIN: Duration = Duration::from_secs(10); +/// How long a capture may take to end after it was told to stop before the CLI gives up on it. +const STOP_GRACE: Duration = Duration::from_secs(10); +/// How long `--exec` may keep running after a capture ends before it is killed. +const DEFAULT_EXEC_GRACE: Duration = Duration::from_secs(10); +const EXEC_OUTPUT_CAP: usize = 4096; +/// How long `--exec` output readers may keep draining after the command has exited. +const EXEC_DRAIN: Duration = Duration::from_millis(500); + +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