Skip to content

Latest commit

 

History

History
296 lines (215 loc) · 17.6 KB

cli.md

File metadata and controls

296 lines (215 loc) · 17.6 KB

HSync CLI (hsync-cli)

hsync-cli is the standalone command-line interface for HSync logic analyzers, capture files and protocol decoding. It shares the hardware drivers, file formats and uiharu decode engine of the desktop app, and is designed for both interactive scripting and AI coding/hardware agents.

Note: uiharu-cli remains the independent Apache-2.0 decoder CLI for raw interleaved binary files. hsync-cli covers hardware acquisition, .hsync/.dsl/VCD/FST/GHW files, signal profiling, timing analysis and structured agent workflows.

Building

Prepare generated DSL sources first, then build hsync-cli:

pnpm dsl:generate
cargo build --release -p hsync-cli

The binary is written to target/release/hsync-cli.

Resource discovery (firmware & demo capture)

DSLogic and PXLogic devices require host-side firmware and FPGA bitstreams (src-tauri/resources/firmware/). hsync-cli searches for them in order:

  1. --firmware-dir <dir>
  2. HSYNC_FIRMWARE_DIR environment variable
  3. Next to the binary (./firmware, ../Resources/firmware, ../lib/HSync/firmware, ../share/hsync/firmware)
  4. Standard installed desktop locations (/Applications/HSync.app/Contents/Resources/firmware, /usr/lib/HSync/firmware, %LOCALAPPDATA%\HSync\firmware)
  5. The repository's src-tauri/resources/firmware in source checkouts

Run hsync-cli doctor to verify firmware readiness, USB devices and OS permissions.

Global options & exit codes

Every subcommand accepts:

  • --json: emit structured JSON on stdout (and structured error objects on stderr with code, message, retryable and hint)
  • --firmware-dir <dir>: override firmware directory
  • --demo-file <file>: override bundled protocol.dsl demo capture
  • -h / --help: show help for the CLI or a specific subcommand

Exit codes:

Code Meaning
0 Success
1 Operational, hardware, USB or I/O error
2 Invalid arguments, unsupported device configuration, memory limit or pipeline validation error
3 Trigger timed out before firing (cli.triggerTimeout)
4 One or more declarative assertions failed in assert (cli.assertionFailed)

Output piped into a reader that stops early (hsync-cli decode … | head) ends the command quietly with exit code 0.

Time, frequency & position syntax

  • Frequencies: 25MHz, 400kHz, 1.4GHz, 115200
  • Durations: 50ns, 250us, 250µs, 100ms, 2s
  • Counts: 4096, 250k, 2.5M
  • Byte limits: 512M, 2G, 256MiB
  • Positions (--from / --to, and <pos> in --pulse <ch>@<pos>):
    • @12000 or 12000: sample index
    • 12.5ms, 500us: absolute time from sample 0
    • t, t+500us, t-100us, t+@64: relative to triggerSample
    • start, end: start or end of capture
  • Channels: 0-7, D0,D1,D4-D7, or capture channel names (SCL,SDA)

All JSON outputs include dual-coordinate timestamps ({ "sample", "timeNs", "relTriggerNs" }) so callers do not need to convert sample indices manually.

Commands

doctor

hsync-cli doctor [--json]

Checks connected USB devices, per-family firmware readiness (DSLogic, PXLogic, ATK-Logic, SLogic, Demo), demo file path, built-in decoder count and OS USB permission tips.

devices

hsync-cli devices [--json]
hsync-cli devices info <device-id> [--json]

Lists connected analyzers (plus virtual-demo) or opens one device to inspect its options, rate tiers, hardware depth, trigger capabilities and analog inputs.

catalog

hsync-cli catalog [--category bus|line|device] [--search <kw>] [--input <schema>] [--ir <file>] [--json]
hsync-cli catalog show <protocol> [--ir <file>] [--json]

Lists available protocol decoders or displays a protocol's full port schema, configuration fields (types, defaults, bounds, enums), event kinds, compatible upstream/downstream decoders and a shorthand usage example.

capture

hsync-cli capture [options]

Declarative capture from hardware or --demo:

# Dry-run settings and memory estimate before capturing
hsync-cli capture --demo --rate 25MHz --duration 50ms --channels 0-7 --dry-run --json

# Arm-then-act: arm hardware trigger, run DUT stimulus command once armed, save .hsync and inspect
hsync-cli capture --channels 0-3 --name 0=CLK --name 1=CS --name 2=MOSI --name 3=MISO \
  --rate 25MHz --duration 100ms --trigger CS=F --trigger-timeout 5s \
  --exec "python trigger_dut.py" \
  --decoder 'spi(clk=CLK,cs=CS,mosi=MOSI,miso=MISO,mode=0) | spi-nor' \
  --inspect -o run.hsync --json

# Trigger timeout with idle-level fallback snapshot
hsync-cli capture --trigger D0=R --trigger-timeout 3s --fallback-instant --json

# Software protocol-event trigger: keep capturing until an I2C error or specific address appears,
# then record 5 ms of trailing traffic and stop automatically
hsync-cli capture --channels 0-1 --rate 4MHz --decoder 'i2c(scl=0,sda=1)' \
  --stop-on-error --post-trigger 5ms --timeout 30s -o fault.hsync --json
hsync-cli capture --demo --stop-on-event 'address 0x62' --post-trigger 5ms --timeout 5s --json

Key behaviors:

  • Resolves OperationMode, RateTier / ChannelMode, enabled channels, sample rate, raw --option overrides, sample limit and threshold voltage in dependency order, so --option samplerate=10MHz --duration 10ms sizes the capture at 10 MHz. Setting the rate both with --rate and --option samplerate, or the sample count both with --samples/--duration and --option samples, is a usage error.
  • Enforces --max-memory (default 512M) before starting acquisition.
  • Distinguishes trigger timeout (exit code 3) from hardware/runtime errors (exit code 1). A trigger counts as fired as soon as the hardware reports it, even while a buffer-mode device is still filling its memory.
  • --timeout defaults to the requested capture length plus half again, the trigger timeout when a trigger is armed and 10 s, but at least 60 s. A capture that does not end within 10 s of being stopped fails with cli.captureTimeout.
  • --exec starts once the device is armed. A command still running when the capture ends gets --exec-grace (default 10s) to finish before it is killed; its exec result then reports success: false.
  • Supports live software protocol-event early stop (--stop-on-error, --stop-on-event <query>, --stop-where <expr>, --stop-after-events <N>, --stop-stream <name>, --post-trigger <dur>) powered by uiharu's streaming decoder (enabling continuous ring-buffer looping on devices that support it):
    • Each look reads only the events decoded since the previous one, so stopping stays prompt on long hunts, and counts include events the ring has since dropped.
    • --stop-after-events <N> stops at a stream's Nth decoded event; with --stop-on-event or --stop-where it stops at the Nth matching event instead (the hit reports matchCount). --stop-stream takes a stream name or a decoder label.
    • A condition that can never match fails at once rather than at --timeout: with the decoder's own error (such as error.decode.missingChannels), or cli.unknownStopStream for a --stop-stream naming nothing. A device that fails or is unplugged reports its own error (exit code 1), not a trigger timeout. --stop-after-events 0, and --stop-stream or --post-trigger without a stop condition, are usage errors.
    • endReason is protocolTrigger only when the match stopped the capture; a match found only after another stop is still reported under protocolTrigger. protocolTrigger.evictedFromBuffer marks a matched event that the ring dropped before the capture ended.
    • Explicit --decoders run live and keep the device's own channel names (such as the Demo protocol pattern's), with --name applied over them.

inspect (L0 signal triage)

hsync-cli inspect <file> [--channels <list>] [--from <pos>] [--to <pos>] [--burst-gap <span>] [--json]

Fast per-channel profile over .hsync, .dsl, .vcd, .fst or .ghw: activity state (constantLow, constantHigh, active), rising/falling edge counts, duty cycle, pulse width & period distributions, estimated clock frequency, suggested standard UART baud rates, activity burst intervals, analog voltage ranges and heuristic hints.

decode (L1 summary & L2 filtered views)

hsync-cli decode <file> [options]

Shorthand pipelines automatically wire ports from the uiharu catalog and resolve channel names:

# L1 summary only (counts by kind/role + leading errors)
hsync-cli decode capture.hsync --decoder 'i2c(scl=SCL,sda=SDA)' --view summary --json

# L2 compact protocol transcript (default view, bounded by --limit)
hsync-cli decode capture.hsync --decoder 'spi(clk=0,cs=1,mosi=2,miso=3,mode=0) | spi-nor' --limit 50

# Structured field filtering & error-only inspection
hsync-cli decode capture.hsync --errors-only --view rows --limit 20 --json
hsync-cli decode capture.hsync --where 'address=0x50' --from 10ms --to 20ms --view rows --json

# Streaming NDJSON (bounded by --limit unless --all is passed)
hsync-cli decode capture.hsync --view ndjson --all > events.ndjson

# Load custom compiled uiharu DSL IR and persist attached decoders into .hsync
hsync-cli decode capture.hsync --ir my_proto.json --decoder 'my-proto(line=0)' --save decoded.hsync

--where supports =, ==, !=, >, >=, <, <= and ~= (case-insensitive substring match), with dot-separated paths and hex/binary/boolean/numeric literals.

transitions & wave (L3 raw waveform inspection)

# Lossless edge transition table
hsync-cli transitions capture.hsync --channels 0,1 --from t-10us --to t+50us --limit 100 --json

# Compact Unicode timing diagram
hsync-cli wave capture.hsync --channels 0-3 --from t-10us --to t+50us --width 80

wave draws at most one column per sample, so a window holding fewer samples than --width is drawn that many columns wide.

measure (L3 precision timing)

hsync-cli measure capture.hsync --pulse D0@1.5ms --json
hsync-cli measure capture.hsync --edges --channels 0-3 --from 0 --to 10ms --json
hsync-cli measure capture.hsync --glitches D0 --max-width 200ns --limit 50 --json
hsync-cli measure capture.hsync --delta CS:fall..CLK:rise --max-delta 50us --json

--pulse reports startIsEdge, endIsEdge and truncated. A pulse cut off by the start or end of the capture is truncated: its width is only a lower bound, and when it has no start edge the period, frequency and duty cycle are left out.

search

hsync-cli search capture.hsync --pattern 'D0=R D1=1' --limit 20 --json
hsync-cli search capture.hsync --query '0x4F 0x32' --decoder 'i2c(scl=0,sda=1)' --json

diff (before/after regression comparison)

hsync-cli diff <before> <after> [--channels <list>] [--decoder <spec>] [--stream <name>] [--context <N>] [--json]

Compares two captures (.hsync, .dsl, .vcd, .fst, .ghw) at both the physical signal level (per-channel activity, edge counts, duty cycle, frequency delta %) and the decoded protocol level (event counts, error counts, and the exact first transcript divergence with surrounding context lines).

A stream is identical when both captures have it with the same event and error counts and its transcripts do not diverge. Streams longer than 100,000 events or 25,000 transcript lines are compared on their first lines only: they can still be identical, and are marked truncated (as is the report, and the human output says the comparison was partial).

assert (declarative verification & HIL gates)

hsync-cli assert <file> [checks...] [--rules <file.json>] [--decoder <spec>] [--json]

Evaluates declarative assertions and exits 0 when all pass or 4 when any check fails (printing every check's expected vs actual value and structured failure evidence):

hsync-cli assert run.hsync \
  --active CLK --freq CLK=95kHz..105kHz --no-glitches SDA:200ns \
  --no-errors --expect-event 'i2c:address 0x62' --forbid-event 'i2c:address 0x7F' \
  --min-events i2c=10 --delta-bound CS:fall..CLK:rise=100ns..50us --json

Assertions can also be passed via --rules <file.json> containing a JSON array of objects tagged by kind. Field names are camelCase and unknown fields are rejected:

kind Fields
noErrors stream (optional)
minEvents stream, min
maxEvents stream, max
expectEvent stream (optional), query
forbidEvent stream (optional), query
frequencyRange channel, minHz, maxHz
channelActivity channel, expected (active, constantHigh, constantLow, empty)
noGlitches channel, maxWidth (e.g. "200ns")
deltaBound delta (e.g. "CS:fall..CLK:rise"), min, max
[
  { "kind": "frequencyRange", "channel": "CLK", "minHz": 95000, "maxHz": 105000 },
  { "kind": "noGlitches", "channel": "SDA", "maxWidth": "200ns" },
  { "kind": "maxEvents", "stream": "i2c", "max": 500 }
]
  • stream names a decoded stream or a decoder label (which selects all of its streams); minEvents and maxEvents add up the streams selected.
  • deltaBound checks every edge pair in the capture and reports the first one outside the bounds.
  • A decoder that failed decoded only part of the capture: upper bounds (maxEvents, forbidEvent) fail on it, and a lower bound that is not met (minEvents, expectEvent) names the failure.

export

hsync-cli export capture.hsync -o slice.vcd --channels 0-3 --from 10ms --to 15ms
hsync-cli export capture.dsl -o capture.hsync
hsync-cli export capture.hsync -o raw.bin --channels 0-3

mcp (stateful MCP server)

hsync-cli mcp [--firmware-dir <dir>] [--demo-file <file>]

Starts a stateful Model Context Protocol (MCP) server over stdio JSON-RPC 2.0 (supporting protocol versions 2025-03-26 and 2024-11-05). Unlike stateless CLI invocations, hsync-cli mcp:

  • Keeps the opened USB logic analyzer open across captures so DSLogic/PXLogic firmware and FPGA bitstreams stay loaded without re-enumerating.
  • Holds opened or captured waveforms in memory under handles (cap-1, cap-2, ...) so repeated L0/L1/L2/L3 queries avoid reloading large .hsync files from disk.
  • Exposes two-phase Arm-then-Act tools (capture_arm → stimulate DUT externally → capture_collect / capture_stop), one-shot capture (including software protocol-event early stop via stopOnError, stopOnEvent, stopWhere, stopAfterEvents, stopStream and postTrigger), closed-loop verification tools (capture_diff, capture_assert), module_load (hot-loading custom uiharu DSL IR JSON modules) and MCP resources (hsync://skill/hsync-cli, hsync://docs/cli).

How the tools behave:

  • Arguments are checked against each tool's input schema: an unknown parameter, a value of the wrong type (such as "samples": 4096 instead of "4096"), a value out of range or not among the choices, or a missing required parameter is a cli.usage error, never silently replaced by a default.
  • Timeouts. capture takes the CLI's timeouts: triggerTimeout applies only until the trigger fires (buffer-mode captures that fired but are still filling are not cut off), the default timeout grows with the requested length (×1.5, plus triggerTimeout when armed, plus 10 s, at least 60 s), and exec gets execGrace (default 10s) to finish after the capture ends. capture_collect counts its triggerTimeout and timeout from the collect call, not from capture_arm.
  • Cancellation. A notifications/cancelled naming a running capture or capture_collect stops the acquisition (and any decoding after it); the cancelled request gets no response. A cancellation without a requestId is ignored.
  • Saving. outPath is checked (extension and existing folder) before anything is captured. If saving still fails, the capture is kept in memory and the error's params.captureId names it, so it can be saved elsewhere with capture_save.
  • Memory. maxMemory (default 512M) covers the new capture plus every capture the session holds; capture_close frees memory.
  • Decoders and modules. A decode_set that fails leaves the capture's previous decoders in place. module_load keeps the module in memory, so its file may change or go afterwards, and loads it into the captures held and the armed capture too; failed lists any capture it could not be loaded into.
  • Devices. device_open, device_info and devices_list rescan, so an analyzer that was unplugged or plugged back in is opened again instead of reusing a dead handle.
  • exec commands get an empty stdin, since stdin is the JSON-RPC stream.

Example MCP client configuration (Claude Code, Cursor, Antigravity, etc.):

{
  "mcpServers": {
    "hsync": {
      "command": "/path/to/hsync-cli",
      "args": ["mcp"]
    }
  }
}